xref: /openbmc/linux/drivers/md/md.c (revision 42bc47b3)
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 /* bio_clone_mddev
208  * like bio_clone_bioset, but with a local bio set
209  */
210 
211 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
212 			    struct mddev *mddev)
213 {
214 	struct bio *b;
215 
216 	if (!mddev || !bioset_initialized(&mddev->bio_set))
217 		return bio_alloc(gfp_mask, nr_iovecs);
218 
219 	b = bio_alloc_bioset(gfp_mask, nr_iovecs, &mddev->bio_set);
220 	if (!b)
221 		return NULL;
222 	return b;
223 }
224 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
225 
226 static struct bio *md_bio_alloc_sync(struct mddev *mddev)
227 {
228 	if (!mddev || !bioset_initialized(&mddev->sync_set))
229 		return bio_alloc(GFP_NOIO, 1);
230 
231 	return bio_alloc_bioset(GFP_NOIO, 1, &mddev->sync_set);
232 }
233 
234 /*
235  * We have a system wide 'event count' that is incremented
236  * on any 'interesting' event, and readers of /proc/mdstat
237  * can use 'poll' or 'select' to find out when the event
238  * count increases.
239  *
240  * Events are:
241  *  start array, stop array, error, add device, remove device,
242  *  start build, activate spare
243  */
244 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
245 static atomic_t md_event_count;
246 void md_new_event(struct mddev *mddev)
247 {
248 	atomic_inc(&md_event_count);
249 	wake_up(&md_event_waiters);
250 }
251 EXPORT_SYMBOL_GPL(md_new_event);
252 
253 /*
254  * Enables to iterate over all existing md arrays
255  * all_mddevs_lock protects this list.
256  */
257 static LIST_HEAD(all_mddevs);
258 static DEFINE_SPINLOCK(all_mddevs_lock);
259 
260 /*
261  * iterates through all used mddevs in the system.
262  * We take care to grab the all_mddevs_lock whenever navigating
263  * the list, and to always hold a refcount when unlocked.
264  * Any code which breaks out of this loop while own
265  * a reference to the current mddev and must mddev_put it.
266  */
267 #define for_each_mddev(_mddev,_tmp)					\
268 									\
269 	for (({ spin_lock(&all_mddevs_lock);				\
270 		_tmp = all_mddevs.next;					\
271 		_mddev = NULL;});					\
272 	     ({ if (_tmp != &all_mddevs)				\
273 			mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
274 		spin_unlock(&all_mddevs_lock);				\
275 		if (_mddev) mddev_put(_mddev);				\
276 		_mddev = list_entry(_tmp, struct mddev, all_mddevs);	\
277 		_tmp != &all_mddevs;});					\
278 	     ({ spin_lock(&all_mddevs_lock);				\
279 		_tmp = _tmp->next;})					\
280 		)
281 
282 /* Rather than calling directly into the personality make_request function,
283  * IO requests come here first so that we can check if the device is
284  * being suspended pending a reconfiguration.
285  * We hold a refcount over the call to ->make_request.  By the time that
286  * call has finished, the bio has been linked into some internal structure
287  * and so is visible to ->quiesce(), so we don't need the refcount any more.
288  */
289 static bool is_suspended(struct mddev *mddev, struct bio *bio)
290 {
291 	if (mddev->suspended)
292 		return true;
293 	if (bio_data_dir(bio) != WRITE)
294 		return false;
295 	if (mddev->suspend_lo >= mddev->suspend_hi)
296 		return false;
297 	if (bio->bi_iter.bi_sector >= mddev->suspend_hi)
298 		return false;
299 	if (bio_end_sector(bio) < mddev->suspend_lo)
300 		return false;
301 	return true;
302 }
303 
304 void md_handle_request(struct mddev *mddev, struct bio *bio)
305 {
306 check_suspended:
307 	rcu_read_lock();
308 	if (is_suspended(mddev, bio)) {
309 		DEFINE_WAIT(__wait);
310 		for (;;) {
311 			prepare_to_wait(&mddev->sb_wait, &__wait,
312 					TASK_UNINTERRUPTIBLE);
313 			if (!is_suspended(mddev, bio))
314 				break;
315 			rcu_read_unlock();
316 			schedule();
317 			rcu_read_lock();
318 		}
319 		finish_wait(&mddev->sb_wait, &__wait);
320 	}
321 	atomic_inc(&mddev->active_io);
322 	rcu_read_unlock();
323 
324 	if (!mddev->pers->make_request(mddev, bio)) {
325 		atomic_dec(&mddev->active_io);
326 		wake_up(&mddev->sb_wait);
327 		goto check_suspended;
328 	}
329 
330 	if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
331 		wake_up(&mddev->sb_wait);
332 }
333 EXPORT_SYMBOL(md_handle_request);
334 
335 static blk_qc_t md_make_request(struct request_queue *q, struct bio *bio)
336 {
337 	const int rw = bio_data_dir(bio);
338 	struct mddev *mddev = q->queuedata;
339 	unsigned int sectors;
340 	int cpu;
341 
342 	blk_queue_split(q, &bio);
343 
344 	if (mddev == NULL || mddev->pers == NULL) {
345 		bio_io_error(bio);
346 		return BLK_QC_T_NONE;
347 	}
348 	if (mddev->ro == 1 && unlikely(rw == WRITE)) {
349 		if (bio_sectors(bio) != 0)
350 			bio->bi_status = BLK_STS_IOERR;
351 		bio_endio(bio);
352 		return BLK_QC_T_NONE;
353 	}
354 
355 	/*
356 	 * save the sectors now since our bio can
357 	 * go away inside make_request
358 	 */
359 	sectors = bio_sectors(bio);
360 	/* bio could be mergeable after passing to underlayer */
361 	bio->bi_opf &= ~REQ_NOMERGE;
362 
363 	md_handle_request(mddev, bio);
364 
365 	cpu = part_stat_lock();
366 	part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
367 	part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
368 	part_stat_unlock();
369 
370 	return BLK_QC_T_NONE;
371 }
372 
373 /* mddev_suspend makes sure no new requests are submitted
374  * to the device, and that any requests that have been submitted
375  * are completely handled.
376  * Once mddev_detach() is called and completes, the module will be
377  * completely unused.
378  */
379 void mddev_suspend(struct mddev *mddev)
380 {
381 	WARN_ON_ONCE(mddev->thread && current == mddev->thread->tsk);
382 	lockdep_assert_held(&mddev->reconfig_mutex);
383 	if (mddev->suspended++)
384 		return;
385 	synchronize_rcu();
386 	wake_up(&mddev->sb_wait);
387 	set_bit(MD_ALLOW_SB_UPDATE, &mddev->flags);
388 	smp_mb__after_atomic();
389 	wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
390 	mddev->pers->quiesce(mddev, 1);
391 	clear_bit_unlock(MD_ALLOW_SB_UPDATE, &mddev->flags);
392 	wait_event(mddev->sb_wait, !test_bit(MD_UPDATING_SB, &mddev->flags));
393 
394 	del_timer_sync(&mddev->safemode_timer);
395 }
396 EXPORT_SYMBOL_GPL(mddev_suspend);
397 
398 void mddev_resume(struct mddev *mddev)
399 {
400 	lockdep_assert_held(&mddev->reconfig_mutex);
401 	if (--mddev->suspended)
402 		return;
403 	wake_up(&mddev->sb_wait);
404 	mddev->pers->quiesce(mddev, 0);
405 
406 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
407 	md_wakeup_thread(mddev->thread);
408 	md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
409 }
410 EXPORT_SYMBOL_GPL(mddev_resume);
411 
412 int mddev_congested(struct mddev *mddev, int bits)
413 {
414 	struct md_personality *pers = mddev->pers;
415 	int ret = 0;
416 
417 	rcu_read_lock();
418 	if (mddev->suspended)
419 		ret = 1;
420 	else if (pers && pers->congested)
421 		ret = pers->congested(mddev, bits);
422 	rcu_read_unlock();
423 	return ret;
424 }
425 EXPORT_SYMBOL_GPL(mddev_congested);
426 static int md_congested(void *data, int bits)
427 {
428 	struct mddev *mddev = data;
429 	return mddev_congested(mddev, bits);
430 }
431 
432 /*
433  * Generic flush handling for md
434  */
435 static void submit_flushes(struct work_struct *ws)
436 {
437 	struct flush_info *fi = container_of(ws, struct flush_info, flush_work);
438 	struct mddev *mddev = fi->mddev;
439 	struct bio *bio = fi->bio;
440 
441 	bio->bi_opf &= ~REQ_PREFLUSH;
442 	md_handle_request(mddev, bio);
443 
444 	mempool_free(fi, mddev->flush_pool);
445 }
446 
447 static void md_end_flush(struct bio *fbio)
448 {
449 	struct flush_bio *fb = fbio->bi_private;
450 	struct md_rdev *rdev = fb->rdev;
451 	struct flush_info *fi = fb->fi;
452 	struct bio *bio = fi->bio;
453 	struct mddev *mddev = fi->mddev;
454 
455 	rdev_dec_pending(rdev, mddev);
456 
457 	if (atomic_dec_and_test(&fi->flush_pending)) {
458 		if (bio->bi_iter.bi_size == 0)
459 			/* an empty barrier - all done */
460 			bio_endio(bio);
461 		else {
462 			INIT_WORK(&fi->flush_work, submit_flushes);
463 			queue_work(md_wq, &fi->flush_work);
464 		}
465 	}
466 
467 	mempool_free(fb, mddev->flush_bio_pool);
468 	bio_put(fbio);
469 }
470 
471 void md_flush_request(struct mddev *mddev, struct bio *bio)
472 {
473 	struct md_rdev *rdev;
474 	struct flush_info *fi;
475 
476 	fi = mempool_alloc(mddev->flush_pool, GFP_NOIO);
477 
478 	fi->bio = bio;
479 	fi->mddev = mddev;
480 	atomic_set(&fi->flush_pending, 1);
481 
482 	rcu_read_lock();
483 	rdev_for_each_rcu(rdev, mddev)
484 		if (rdev->raid_disk >= 0 &&
485 		    !test_bit(Faulty, &rdev->flags)) {
486 			/* Take two references, one is dropped
487 			 * when request finishes, one after
488 			 * we reclaim rcu_read_lock
489 			 */
490 			struct bio *bi;
491 			struct flush_bio *fb;
492 			atomic_inc(&rdev->nr_pending);
493 			atomic_inc(&rdev->nr_pending);
494 			rcu_read_unlock();
495 
496 			fb = mempool_alloc(mddev->flush_bio_pool, GFP_NOIO);
497 			fb->fi = fi;
498 			fb->rdev = rdev;
499 
500 			bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
501 			bio_set_dev(bi, rdev->bdev);
502 			bi->bi_end_io = md_end_flush;
503 			bi->bi_private = fb;
504 			bi->bi_opf = REQ_OP_WRITE | REQ_PREFLUSH;
505 
506 			atomic_inc(&fi->flush_pending);
507 			submit_bio(bi);
508 
509 			rcu_read_lock();
510 			rdev_dec_pending(rdev, mddev);
511 		}
512 	rcu_read_unlock();
513 
514 	if (atomic_dec_and_test(&fi->flush_pending)) {
515 		if (bio->bi_iter.bi_size == 0)
516 			/* an empty barrier - all done */
517 			bio_endio(bio);
518 		else {
519 			INIT_WORK(&fi->flush_work, submit_flushes);
520 			queue_work(md_wq, &fi->flush_work);
521 		}
522 	}
523 }
524 EXPORT_SYMBOL(md_flush_request);
525 
526 static inline struct mddev *mddev_get(struct mddev *mddev)
527 {
528 	atomic_inc(&mddev->active);
529 	return mddev;
530 }
531 
532 static void mddev_delayed_delete(struct work_struct *ws);
533 
534 static void mddev_put(struct mddev *mddev)
535 {
536 	if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
537 		return;
538 	if (!mddev->raid_disks && list_empty(&mddev->disks) &&
539 	    mddev->ctime == 0 && !mddev->hold_active) {
540 		/* Array is not configured at all, and not held active,
541 		 * so destroy it */
542 		list_del_init(&mddev->all_mddevs);
543 
544 		/*
545 		 * Call queue_work inside the spinlock so that
546 		 * flush_workqueue() after mddev_find will succeed in waiting
547 		 * for the work to be done.
548 		 */
549 		INIT_WORK(&mddev->del_work, mddev_delayed_delete);
550 		queue_work(md_misc_wq, &mddev->del_work);
551 	}
552 	spin_unlock(&all_mddevs_lock);
553 }
554 
555 static void md_safemode_timeout(struct timer_list *t);
556 
557 void mddev_init(struct mddev *mddev)
558 {
559 	kobject_init(&mddev->kobj, &md_ktype);
560 	mutex_init(&mddev->open_mutex);
561 	mutex_init(&mddev->reconfig_mutex);
562 	mutex_init(&mddev->bitmap_info.mutex);
563 	INIT_LIST_HEAD(&mddev->disks);
564 	INIT_LIST_HEAD(&mddev->all_mddevs);
565 	timer_setup(&mddev->safemode_timer, md_safemode_timeout, 0);
566 	atomic_set(&mddev->active, 1);
567 	atomic_set(&mddev->openers, 0);
568 	atomic_set(&mddev->active_io, 0);
569 	spin_lock_init(&mddev->lock);
570 	init_waitqueue_head(&mddev->sb_wait);
571 	init_waitqueue_head(&mddev->recovery_wait);
572 	mddev->reshape_position = MaxSector;
573 	mddev->reshape_backwards = 0;
574 	mddev->last_sync_action = "none";
575 	mddev->resync_min = 0;
576 	mddev->resync_max = MaxSector;
577 	mddev->level = LEVEL_NONE;
578 }
579 EXPORT_SYMBOL_GPL(mddev_init);
580 
581 static struct mddev *mddev_find(dev_t unit)
582 {
583 	struct mddev *mddev, *new = NULL;
584 
585 	if (unit && MAJOR(unit) != MD_MAJOR)
586 		unit &= ~((1<<MdpMinorShift)-1);
587 
588  retry:
589 	spin_lock(&all_mddevs_lock);
590 
591 	if (unit) {
592 		list_for_each_entry(mddev, &all_mddevs, all_mddevs)
593 			if (mddev->unit == unit) {
594 				mddev_get(mddev);
595 				spin_unlock(&all_mddevs_lock);
596 				kfree(new);
597 				return mddev;
598 			}
599 
600 		if (new) {
601 			list_add(&new->all_mddevs, &all_mddevs);
602 			spin_unlock(&all_mddevs_lock);
603 			new->hold_active = UNTIL_IOCTL;
604 			return new;
605 		}
606 	} else if (new) {
607 		/* find an unused unit number */
608 		static int next_minor = 512;
609 		int start = next_minor;
610 		int is_free = 0;
611 		int dev = 0;
612 		while (!is_free) {
613 			dev = MKDEV(MD_MAJOR, next_minor);
614 			next_minor++;
615 			if (next_minor > MINORMASK)
616 				next_minor = 0;
617 			if (next_minor == start) {
618 				/* Oh dear, all in use. */
619 				spin_unlock(&all_mddevs_lock);
620 				kfree(new);
621 				return NULL;
622 			}
623 
624 			is_free = 1;
625 			list_for_each_entry(mddev, &all_mddevs, all_mddevs)
626 				if (mddev->unit == dev) {
627 					is_free = 0;
628 					break;
629 				}
630 		}
631 		new->unit = dev;
632 		new->md_minor = MINOR(dev);
633 		new->hold_active = UNTIL_STOP;
634 		list_add(&new->all_mddevs, &all_mddevs);
635 		spin_unlock(&all_mddevs_lock);
636 		return new;
637 	}
638 	spin_unlock(&all_mddevs_lock);
639 
640 	new = kzalloc(sizeof(*new), GFP_KERNEL);
641 	if (!new)
642 		return NULL;
643 
644 	new->unit = unit;
645 	if (MAJOR(unit) == MD_MAJOR)
646 		new->md_minor = MINOR(unit);
647 	else
648 		new->md_minor = MINOR(unit) >> MdpMinorShift;
649 
650 	mddev_init(new);
651 
652 	goto retry;
653 }
654 
655 static struct attribute_group md_redundancy_group;
656 
657 void mddev_unlock(struct mddev *mddev)
658 {
659 	if (mddev->to_remove) {
660 		/* These cannot be removed under reconfig_mutex as
661 		 * an access to the files will try to take reconfig_mutex
662 		 * while holding the file unremovable, which leads to
663 		 * a deadlock.
664 		 * So hold set sysfs_active while the remove in happeing,
665 		 * and anything else which might set ->to_remove or my
666 		 * otherwise change the sysfs namespace will fail with
667 		 * -EBUSY if sysfs_active is still set.
668 		 * We set sysfs_active under reconfig_mutex and elsewhere
669 		 * test it under the same mutex to ensure its correct value
670 		 * is seen.
671 		 */
672 		struct attribute_group *to_remove = mddev->to_remove;
673 		mddev->to_remove = NULL;
674 		mddev->sysfs_active = 1;
675 		mutex_unlock(&mddev->reconfig_mutex);
676 
677 		if (mddev->kobj.sd) {
678 			if (to_remove != &md_redundancy_group)
679 				sysfs_remove_group(&mddev->kobj, to_remove);
680 			if (mddev->pers == NULL ||
681 			    mddev->pers->sync_request == NULL) {
682 				sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
683 				if (mddev->sysfs_action)
684 					sysfs_put(mddev->sysfs_action);
685 				mddev->sysfs_action = NULL;
686 			}
687 		}
688 		mddev->sysfs_active = 0;
689 	} else
690 		mutex_unlock(&mddev->reconfig_mutex);
691 
692 	/* As we've dropped the mutex we need a spinlock to
693 	 * make sure the thread doesn't disappear
694 	 */
695 	spin_lock(&pers_lock);
696 	md_wakeup_thread(mddev->thread);
697 	wake_up(&mddev->sb_wait);
698 	spin_unlock(&pers_lock);
699 }
700 EXPORT_SYMBOL_GPL(mddev_unlock);
701 
702 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr)
703 {
704 	struct md_rdev *rdev;
705 
706 	rdev_for_each_rcu(rdev, mddev)
707 		if (rdev->desc_nr == nr)
708 			return rdev;
709 
710 	return NULL;
711 }
712 EXPORT_SYMBOL_GPL(md_find_rdev_nr_rcu);
713 
714 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
715 {
716 	struct md_rdev *rdev;
717 
718 	rdev_for_each(rdev, mddev)
719 		if (rdev->bdev->bd_dev == dev)
720 			return rdev;
721 
722 	return NULL;
723 }
724 
725 struct md_rdev *md_find_rdev_rcu(struct mddev *mddev, dev_t dev)
726 {
727 	struct md_rdev *rdev;
728 
729 	rdev_for_each_rcu(rdev, mddev)
730 		if (rdev->bdev->bd_dev == dev)
731 			return rdev;
732 
733 	return NULL;
734 }
735 EXPORT_SYMBOL_GPL(md_find_rdev_rcu);
736 
737 static struct md_personality *find_pers(int level, char *clevel)
738 {
739 	struct md_personality *pers;
740 	list_for_each_entry(pers, &pers_list, list) {
741 		if (level != LEVEL_NONE && pers->level == level)
742 			return pers;
743 		if (strcmp(pers->name, clevel)==0)
744 			return pers;
745 	}
746 	return NULL;
747 }
748 
749 /* return the offset of the super block in 512byte sectors */
750 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
751 {
752 	sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
753 	return MD_NEW_SIZE_SECTORS(num_sectors);
754 }
755 
756 static int alloc_disk_sb(struct md_rdev *rdev)
757 {
758 	rdev->sb_page = alloc_page(GFP_KERNEL);
759 	if (!rdev->sb_page)
760 		return -ENOMEM;
761 	return 0;
762 }
763 
764 void md_rdev_clear(struct md_rdev *rdev)
765 {
766 	if (rdev->sb_page) {
767 		put_page(rdev->sb_page);
768 		rdev->sb_loaded = 0;
769 		rdev->sb_page = NULL;
770 		rdev->sb_start = 0;
771 		rdev->sectors = 0;
772 	}
773 	if (rdev->bb_page) {
774 		put_page(rdev->bb_page);
775 		rdev->bb_page = NULL;
776 	}
777 	badblocks_exit(&rdev->badblocks);
778 }
779 EXPORT_SYMBOL_GPL(md_rdev_clear);
780 
781 static void super_written(struct bio *bio)
782 {
783 	struct md_rdev *rdev = bio->bi_private;
784 	struct mddev *mddev = rdev->mddev;
785 
786 	if (bio->bi_status) {
787 		pr_err("md: super_written gets error=%d\n", bio->bi_status);
788 		md_error(mddev, rdev);
789 		if (!test_bit(Faulty, &rdev->flags)
790 		    && (bio->bi_opf & MD_FAILFAST)) {
791 			set_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags);
792 			set_bit(LastDev, &rdev->flags);
793 		}
794 	} else
795 		clear_bit(LastDev, &rdev->flags);
796 
797 	if (atomic_dec_and_test(&mddev->pending_writes))
798 		wake_up(&mddev->sb_wait);
799 	rdev_dec_pending(rdev, mddev);
800 	bio_put(bio);
801 }
802 
803 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
804 		   sector_t sector, int size, struct page *page)
805 {
806 	/* write first size bytes of page to sector of rdev
807 	 * Increment mddev->pending_writes before returning
808 	 * and decrement it on completion, waking up sb_wait
809 	 * if zero is reached.
810 	 * If an error occurred, call md_error
811 	 */
812 	struct bio *bio;
813 	int ff = 0;
814 
815 	if (!page)
816 		return;
817 
818 	if (test_bit(Faulty, &rdev->flags))
819 		return;
820 
821 	bio = md_bio_alloc_sync(mddev);
822 
823 	atomic_inc(&rdev->nr_pending);
824 
825 	bio_set_dev(bio, rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev);
826 	bio->bi_iter.bi_sector = sector;
827 	bio_add_page(bio, page, size, 0);
828 	bio->bi_private = rdev;
829 	bio->bi_end_io = super_written;
830 
831 	if (test_bit(MD_FAILFAST_SUPPORTED, &mddev->flags) &&
832 	    test_bit(FailFast, &rdev->flags) &&
833 	    !test_bit(LastDev, &rdev->flags))
834 		ff = MD_FAILFAST;
835 	bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH | REQ_FUA | ff;
836 
837 	atomic_inc(&mddev->pending_writes);
838 	submit_bio(bio);
839 }
840 
841 int md_super_wait(struct mddev *mddev)
842 {
843 	/* wait for all superblock writes that were scheduled to complete */
844 	wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
845 	if (test_and_clear_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags))
846 		return -EAGAIN;
847 	return 0;
848 }
849 
850 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
851 		 struct page *page, int op, int op_flags, bool metadata_op)
852 {
853 	struct bio *bio = md_bio_alloc_sync(rdev->mddev);
854 	int ret;
855 
856 	if (metadata_op && rdev->meta_bdev)
857 		bio_set_dev(bio, rdev->meta_bdev);
858 	else
859 		bio_set_dev(bio, rdev->bdev);
860 	bio_set_op_attrs(bio, op, op_flags);
861 	if (metadata_op)
862 		bio->bi_iter.bi_sector = sector + rdev->sb_start;
863 	else if (rdev->mddev->reshape_position != MaxSector &&
864 		 (rdev->mddev->reshape_backwards ==
865 		  (sector >= rdev->mddev->reshape_position)))
866 		bio->bi_iter.bi_sector = sector + rdev->new_data_offset;
867 	else
868 		bio->bi_iter.bi_sector = sector + rdev->data_offset;
869 	bio_add_page(bio, page, size, 0);
870 
871 	submit_bio_wait(bio);
872 
873 	ret = !bio->bi_status;
874 	bio_put(bio);
875 	return ret;
876 }
877 EXPORT_SYMBOL_GPL(sync_page_io);
878 
879 static int read_disk_sb(struct md_rdev *rdev, int size)
880 {
881 	char b[BDEVNAME_SIZE];
882 
883 	if (rdev->sb_loaded)
884 		return 0;
885 
886 	if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, true))
887 		goto fail;
888 	rdev->sb_loaded = 1;
889 	return 0;
890 
891 fail:
892 	pr_err("md: disabled device %s, could not read superblock.\n",
893 	       bdevname(rdev->bdev,b));
894 	return -EINVAL;
895 }
896 
897 static int md_uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
898 {
899 	return	sb1->set_uuid0 == sb2->set_uuid0 &&
900 		sb1->set_uuid1 == sb2->set_uuid1 &&
901 		sb1->set_uuid2 == sb2->set_uuid2 &&
902 		sb1->set_uuid3 == sb2->set_uuid3;
903 }
904 
905 static int md_sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
906 {
907 	int ret;
908 	mdp_super_t *tmp1, *tmp2;
909 
910 	tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
911 	tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
912 
913 	if (!tmp1 || !tmp2) {
914 		ret = 0;
915 		goto abort;
916 	}
917 
918 	*tmp1 = *sb1;
919 	*tmp2 = *sb2;
920 
921 	/*
922 	 * nr_disks is not constant
923 	 */
924 	tmp1->nr_disks = 0;
925 	tmp2->nr_disks = 0;
926 
927 	ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
928 abort:
929 	kfree(tmp1);
930 	kfree(tmp2);
931 	return ret;
932 }
933 
934 static u32 md_csum_fold(u32 csum)
935 {
936 	csum = (csum & 0xffff) + (csum >> 16);
937 	return (csum & 0xffff) + (csum >> 16);
938 }
939 
940 static unsigned int calc_sb_csum(mdp_super_t *sb)
941 {
942 	u64 newcsum = 0;
943 	u32 *sb32 = (u32*)sb;
944 	int i;
945 	unsigned int disk_csum, csum;
946 
947 	disk_csum = sb->sb_csum;
948 	sb->sb_csum = 0;
949 
950 	for (i = 0; i < MD_SB_BYTES/4 ; i++)
951 		newcsum += sb32[i];
952 	csum = (newcsum & 0xffffffff) + (newcsum>>32);
953 
954 #ifdef CONFIG_ALPHA
955 	/* This used to use csum_partial, which was wrong for several
956 	 * reasons including that different results are returned on
957 	 * different architectures.  It isn't critical that we get exactly
958 	 * the same return value as before (we always csum_fold before
959 	 * testing, and that removes any differences).  However as we
960 	 * know that csum_partial always returned a 16bit value on
961 	 * alphas, do a fold to maximise conformity to previous behaviour.
962 	 */
963 	sb->sb_csum = md_csum_fold(disk_csum);
964 #else
965 	sb->sb_csum = disk_csum;
966 #endif
967 	return csum;
968 }
969 
970 /*
971  * Handle superblock details.
972  * We want to be able to handle multiple superblock formats
973  * so we have a common interface to them all, and an array of
974  * different handlers.
975  * We rely on user-space to write the initial superblock, and support
976  * reading and updating of superblocks.
977  * Interface methods are:
978  *   int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
979  *      loads and validates a superblock on dev.
980  *      if refdev != NULL, compare superblocks on both devices
981  *    Return:
982  *      0 - dev has a superblock that is compatible with refdev
983  *      1 - dev has a superblock that is compatible and newer than refdev
984  *          so dev should be used as the refdev in future
985  *     -EINVAL superblock incompatible or invalid
986  *     -othererror e.g. -EIO
987  *
988  *   int validate_super(struct mddev *mddev, struct md_rdev *dev)
989  *      Verify that dev is acceptable into mddev.
990  *       The first time, mddev->raid_disks will be 0, and data from
991  *       dev should be merged in.  Subsequent calls check that dev
992  *       is new enough.  Return 0 or -EINVAL
993  *
994  *   void sync_super(struct mddev *mddev, struct md_rdev *dev)
995  *     Update the superblock for rdev with data in mddev
996  *     This does not write to disc.
997  *
998  */
999 
1000 struct super_type  {
1001 	char		    *name;
1002 	struct module	    *owner;
1003 	int		    (*load_super)(struct md_rdev *rdev,
1004 					  struct md_rdev *refdev,
1005 					  int minor_version);
1006 	int		    (*validate_super)(struct mddev *mddev,
1007 					      struct md_rdev *rdev);
1008 	void		    (*sync_super)(struct mddev *mddev,
1009 					  struct md_rdev *rdev);
1010 	unsigned long long  (*rdev_size_change)(struct md_rdev *rdev,
1011 						sector_t num_sectors);
1012 	int		    (*allow_new_offset)(struct md_rdev *rdev,
1013 						unsigned long long new_offset);
1014 };
1015 
1016 /*
1017  * Check that the given mddev has no bitmap.
1018  *
1019  * This function is called from the run method of all personalities that do not
1020  * support bitmaps. It prints an error message and returns non-zero if mddev
1021  * has a bitmap. Otherwise, it returns 0.
1022  *
1023  */
1024 int md_check_no_bitmap(struct mddev *mddev)
1025 {
1026 	if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1027 		return 0;
1028 	pr_warn("%s: bitmaps are not supported for %s\n",
1029 		mdname(mddev), mddev->pers->name);
1030 	return 1;
1031 }
1032 EXPORT_SYMBOL(md_check_no_bitmap);
1033 
1034 /*
1035  * load_super for 0.90.0
1036  */
1037 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1038 {
1039 	char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1040 	mdp_super_t *sb;
1041 	int ret;
1042 
1043 	/*
1044 	 * Calculate the position of the superblock (512byte sectors),
1045 	 * it's at the end of the disk.
1046 	 *
1047 	 * It also happens to be a multiple of 4Kb.
1048 	 */
1049 	rdev->sb_start = calc_dev_sboffset(rdev);
1050 
1051 	ret = read_disk_sb(rdev, MD_SB_BYTES);
1052 	if (ret)
1053 		return ret;
1054 
1055 	ret = -EINVAL;
1056 
1057 	bdevname(rdev->bdev, b);
1058 	sb = page_address(rdev->sb_page);
1059 
1060 	if (sb->md_magic != MD_SB_MAGIC) {
1061 		pr_warn("md: invalid raid superblock magic on %s\n", b);
1062 		goto abort;
1063 	}
1064 
1065 	if (sb->major_version != 0 ||
1066 	    sb->minor_version < 90 ||
1067 	    sb->minor_version > 91) {
1068 		pr_warn("Bad version number %d.%d on %s\n",
1069 			sb->major_version, sb->minor_version, b);
1070 		goto abort;
1071 	}
1072 
1073 	if (sb->raid_disks <= 0)
1074 		goto abort;
1075 
1076 	if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1077 		pr_warn("md: invalid superblock checksum on %s\n", b);
1078 		goto abort;
1079 	}
1080 
1081 	rdev->preferred_minor = sb->md_minor;
1082 	rdev->data_offset = 0;
1083 	rdev->new_data_offset = 0;
1084 	rdev->sb_size = MD_SB_BYTES;
1085 	rdev->badblocks.shift = -1;
1086 
1087 	if (sb->level == LEVEL_MULTIPATH)
1088 		rdev->desc_nr = -1;
1089 	else
1090 		rdev->desc_nr = sb->this_disk.number;
1091 
1092 	if (!refdev) {
1093 		ret = 1;
1094 	} else {
1095 		__u64 ev1, ev2;
1096 		mdp_super_t *refsb = page_address(refdev->sb_page);
1097 		if (!md_uuid_equal(refsb, sb)) {
1098 			pr_warn("md: %s has different UUID to %s\n",
1099 				b, bdevname(refdev->bdev,b2));
1100 			goto abort;
1101 		}
1102 		if (!md_sb_equal(refsb, sb)) {
1103 			pr_warn("md: %s has same UUID but different superblock to %s\n",
1104 				b, bdevname(refdev->bdev, b2));
1105 			goto abort;
1106 		}
1107 		ev1 = md_event(sb);
1108 		ev2 = md_event(refsb);
1109 		if (ev1 > ev2)
1110 			ret = 1;
1111 		else
1112 			ret = 0;
1113 	}
1114 	rdev->sectors = rdev->sb_start;
1115 	/* Limit to 4TB as metadata cannot record more than that.
1116 	 * (not needed for Linear and RAID0 as metadata doesn't
1117 	 * record this size)
1118 	 */
1119 	if (IS_ENABLED(CONFIG_LBDAF) && (u64)rdev->sectors >= (2ULL << 32) &&
1120 	    sb->level >= 1)
1121 		rdev->sectors = (sector_t)(2ULL << 32) - 2;
1122 
1123 	if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1124 		/* "this cannot possibly happen" ... */
1125 		ret = -EINVAL;
1126 
1127  abort:
1128 	return ret;
1129 }
1130 
1131 /*
1132  * validate_super for 0.90.0
1133  */
1134 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1135 {
1136 	mdp_disk_t *desc;
1137 	mdp_super_t *sb = page_address(rdev->sb_page);
1138 	__u64 ev1 = md_event(sb);
1139 
1140 	rdev->raid_disk = -1;
1141 	clear_bit(Faulty, &rdev->flags);
1142 	clear_bit(In_sync, &rdev->flags);
1143 	clear_bit(Bitmap_sync, &rdev->flags);
1144 	clear_bit(WriteMostly, &rdev->flags);
1145 
1146 	if (mddev->raid_disks == 0) {
1147 		mddev->major_version = 0;
1148 		mddev->minor_version = sb->minor_version;
1149 		mddev->patch_version = sb->patch_version;
1150 		mddev->external = 0;
1151 		mddev->chunk_sectors = sb->chunk_size >> 9;
1152 		mddev->ctime = sb->ctime;
1153 		mddev->utime = sb->utime;
1154 		mddev->level = sb->level;
1155 		mddev->clevel[0] = 0;
1156 		mddev->layout = sb->layout;
1157 		mddev->raid_disks = sb->raid_disks;
1158 		mddev->dev_sectors = ((sector_t)sb->size) * 2;
1159 		mddev->events = ev1;
1160 		mddev->bitmap_info.offset = 0;
1161 		mddev->bitmap_info.space = 0;
1162 		/* bitmap can use 60 K after the 4K superblocks */
1163 		mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1164 		mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1165 		mddev->reshape_backwards = 0;
1166 
1167 		if (mddev->minor_version >= 91) {
1168 			mddev->reshape_position = sb->reshape_position;
1169 			mddev->delta_disks = sb->delta_disks;
1170 			mddev->new_level = sb->new_level;
1171 			mddev->new_layout = sb->new_layout;
1172 			mddev->new_chunk_sectors = sb->new_chunk >> 9;
1173 			if (mddev->delta_disks < 0)
1174 				mddev->reshape_backwards = 1;
1175 		} else {
1176 			mddev->reshape_position = MaxSector;
1177 			mddev->delta_disks = 0;
1178 			mddev->new_level = mddev->level;
1179 			mddev->new_layout = mddev->layout;
1180 			mddev->new_chunk_sectors = mddev->chunk_sectors;
1181 		}
1182 
1183 		if (sb->state & (1<<MD_SB_CLEAN))
1184 			mddev->recovery_cp = MaxSector;
1185 		else {
1186 			if (sb->events_hi == sb->cp_events_hi &&
1187 				sb->events_lo == sb->cp_events_lo) {
1188 				mddev->recovery_cp = sb->recovery_cp;
1189 			} else
1190 				mddev->recovery_cp = 0;
1191 		}
1192 
1193 		memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1194 		memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1195 		memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1196 		memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1197 
1198 		mddev->max_disks = MD_SB_DISKS;
1199 
1200 		if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1201 		    mddev->bitmap_info.file == NULL) {
1202 			mddev->bitmap_info.offset =
1203 				mddev->bitmap_info.default_offset;
1204 			mddev->bitmap_info.space =
1205 				mddev->bitmap_info.default_space;
1206 		}
1207 
1208 	} else if (mddev->pers == NULL) {
1209 		/* Insist on good event counter while assembling, except
1210 		 * for spares (which don't need an event count) */
1211 		++ev1;
1212 		if (sb->disks[rdev->desc_nr].state & (
1213 			    (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1214 			if (ev1 < mddev->events)
1215 				return -EINVAL;
1216 	} else if (mddev->bitmap) {
1217 		/* if adding to array with a bitmap, then we can accept an
1218 		 * older device ... but not too old.
1219 		 */
1220 		if (ev1 < mddev->bitmap->events_cleared)
1221 			return 0;
1222 		if (ev1 < mddev->events)
1223 			set_bit(Bitmap_sync, &rdev->flags);
1224 	} else {
1225 		if (ev1 < mddev->events)
1226 			/* just a hot-add of a new device, leave raid_disk at -1 */
1227 			return 0;
1228 	}
1229 
1230 	if (mddev->level != LEVEL_MULTIPATH) {
1231 		desc = sb->disks + rdev->desc_nr;
1232 
1233 		if (desc->state & (1<<MD_DISK_FAULTY))
1234 			set_bit(Faulty, &rdev->flags);
1235 		else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1236 			    desc->raid_disk < mddev->raid_disks */) {
1237 			set_bit(In_sync, &rdev->flags);
1238 			rdev->raid_disk = desc->raid_disk;
1239 			rdev->saved_raid_disk = desc->raid_disk;
1240 		} else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1241 			/* active but not in sync implies recovery up to
1242 			 * reshape position.  We don't know exactly where
1243 			 * that is, so set to zero for now */
1244 			if (mddev->minor_version >= 91) {
1245 				rdev->recovery_offset = 0;
1246 				rdev->raid_disk = desc->raid_disk;
1247 			}
1248 		}
1249 		if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1250 			set_bit(WriteMostly, &rdev->flags);
1251 		if (desc->state & (1<<MD_DISK_FAILFAST))
1252 			set_bit(FailFast, &rdev->flags);
1253 	} else /* MULTIPATH are always insync */
1254 		set_bit(In_sync, &rdev->flags);
1255 	return 0;
1256 }
1257 
1258 /*
1259  * sync_super for 0.90.0
1260  */
1261 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1262 {
1263 	mdp_super_t *sb;
1264 	struct md_rdev *rdev2;
1265 	int next_spare = mddev->raid_disks;
1266 
1267 	/* make rdev->sb match mddev data..
1268 	 *
1269 	 * 1/ zero out disks
1270 	 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1271 	 * 3/ any empty disks < next_spare become removed
1272 	 *
1273 	 * disks[0] gets initialised to REMOVED because
1274 	 * we cannot be sure from other fields if it has
1275 	 * been initialised or not.
1276 	 */
1277 	int i;
1278 	int active=0, working=0,failed=0,spare=0,nr_disks=0;
1279 
1280 	rdev->sb_size = MD_SB_BYTES;
1281 
1282 	sb = page_address(rdev->sb_page);
1283 
1284 	memset(sb, 0, sizeof(*sb));
1285 
1286 	sb->md_magic = MD_SB_MAGIC;
1287 	sb->major_version = mddev->major_version;
1288 	sb->patch_version = mddev->patch_version;
1289 	sb->gvalid_words  = 0; /* ignored */
1290 	memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1291 	memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1292 	memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1293 	memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1294 
1295 	sb->ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
1296 	sb->level = mddev->level;
1297 	sb->size = mddev->dev_sectors / 2;
1298 	sb->raid_disks = mddev->raid_disks;
1299 	sb->md_minor = mddev->md_minor;
1300 	sb->not_persistent = 0;
1301 	sb->utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
1302 	sb->state = 0;
1303 	sb->events_hi = (mddev->events>>32);
1304 	sb->events_lo = (u32)mddev->events;
1305 
1306 	if (mddev->reshape_position == MaxSector)
1307 		sb->minor_version = 90;
1308 	else {
1309 		sb->minor_version = 91;
1310 		sb->reshape_position = mddev->reshape_position;
1311 		sb->new_level = mddev->new_level;
1312 		sb->delta_disks = mddev->delta_disks;
1313 		sb->new_layout = mddev->new_layout;
1314 		sb->new_chunk = mddev->new_chunk_sectors << 9;
1315 	}
1316 	mddev->minor_version = sb->minor_version;
1317 	if (mddev->in_sync)
1318 	{
1319 		sb->recovery_cp = mddev->recovery_cp;
1320 		sb->cp_events_hi = (mddev->events>>32);
1321 		sb->cp_events_lo = (u32)mddev->events;
1322 		if (mddev->recovery_cp == MaxSector)
1323 			sb->state = (1<< MD_SB_CLEAN);
1324 	} else
1325 		sb->recovery_cp = 0;
1326 
1327 	sb->layout = mddev->layout;
1328 	sb->chunk_size = mddev->chunk_sectors << 9;
1329 
1330 	if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1331 		sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1332 
1333 	sb->disks[0].state = (1<<MD_DISK_REMOVED);
1334 	rdev_for_each(rdev2, mddev) {
1335 		mdp_disk_t *d;
1336 		int desc_nr;
1337 		int is_active = test_bit(In_sync, &rdev2->flags);
1338 
1339 		if (rdev2->raid_disk >= 0 &&
1340 		    sb->minor_version >= 91)
1341 			/* we have nowhere to store the recovery_offset,
1342 			 * but if it is not below the reshape_position,
1343 			 * we can piggy-back on that.
1344 			 */
1345 			is_active = 1;
1346 		if (rdev2->raid_disk < 0 ||
1347 		    test_bit(Faulty, &rdev2->flags))
1348 			is_active = 0;
1349 		if (is_active)
1350 			desc_nr = rdev2->raid_disk;
1351 		else
1352 			desc_nr = next_spare++;
1353 		rdev2->desc_nr = desc_nr;
1354 		d = &sb->disks[rdev2->desc_nr];
1355 		nr_disks++;
1356 		d->number = rdev2->desc_nr;
1357 		d->major = MAJOR(rdev2->bdev->bd_dev);
1358 		d->minor = MINOR(rdev2->bdev->bd_dev);
1359 		if (is_active)
1360 			d->raid_disk = rdev2->raid_disk;
1361 		else
1362 			d->raid_disk = rdev2->desc_nr; /* compatibility */
1363 		if (test_bit(Faulty, &rdev2->flags))
1364 			d->state = (1<<MD_DISK_FAULTY);
1365 		else if (is_active) {
1366 			d->state = (1<<MD_DISK_ACTIVE);
1367 			if (test_bit(In_sync, &rdev2->flags))
1368 				d->state |= (1<<MD_DISK_SYNC);
1369 			active++;
1370 			working++;
1371 		} else {
1372 			d->state = 0;
1373 			spare++;
1374 			working++;
1375 		}
1376 		if (test_bit(WriteMostly, &rdev2->flags))
1377 			d->state |= (1<<MD_DISK_WRITEMOSTLY);
1378 		if (test_bit(FailFast, &rdev2->flags))
1379 			d->state |= (1<<MD_DISK_FAILFAST);
1380 	}
1381 	/* now set the "removed" and "faulty" bits on any missing devices */
1382 	for (i=0 ; i < mddev->raid_disks ; i++) {
1383 		mdp_disk_t *d = &sb->disks[i];
1384 		if (d->state == 0 && d->number == 0) {
1385 			d->number = i;
1386 			d->raid_disk = i;
1387 			d->state = (1<<MD_DISK_REMOVED);
1388 			d->state |= (1<<MD_DISK_FAULTY);
1389 			failed++;
1390 		}
1391 	}
1392 	sb->nr_disks = nr_disks;
1393 	sb->active_disks = active;
1394 	sb->working_disks = working;
1395 	sb->failed_disks = failed;
1396 	sb->spare_disks = spare;
1397 
1398 	sb->this_disk = sb->disks[rdev->desc_nr];
1399 	sb->sb_csum = calc_sb_csum(sb);
1400 }
1401 
1402 /*
1403  * rdev_size_change for 0.90.0
1404  */
1405 static unsigned long long
1406 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1407 {
1408 	if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1409 		return 0; /* component must fit device */
1410 	if (rdev->mddev->bitmap_info.offset)
1411 		return 0; /* can't move bitmap */
1412 	rdev->sb_start = calc_dev_sboffset(rdev);
1413 	if (!num_sectors || num_sectors > rdev->sb_start)
1414 		num_sectors = rdev->sb_start;
1415 	/* Limit to 4TB as metadata cannot record more than that.
1416 	 * 4TB == 2^32 KB, or 2*2^32 sectors.
1417 	 */
1418 	if (IS_ENABLED(CONFIG_LBDAF) && (u64)num_sectors >= (2ULL << 32) &&
1419 	    rdev->mddev->level >= 1)
1420 		num_sectors = (sector_t)(2ULL << 32) - 2;
1421 	do {
1422 		md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1423 		       rdev->sb_page);
1424 	} while (md_super_wait(rdev->mddev) < 0);
1425 	return num_sectors;
1426 }
1427 
1428 static int
1429 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1430 {
1431 	/* non-zero offset changes not possible with v0.90 */
1432 	return new_offset == 0;
1433 }
1434 
1435 /*
1436  * version 1 superblock
1437  */
1438 
1439 static __le32 calc_sb_1_csum(struct mdp_superblock_1 *sb)
1440 {
1441 	__le32 disk_csum;
1442 	u32 csum;
1443 	unsigned long long newcsum;
1444 	int size = 256 + le32_to_cpu(sb->max_dev)*2;
1445 	__le32 *isuper = (__le32*)sb;
1446 
1447 	disk_csum = sb->sb_csum;
1448 	sb->sb_csum = 0;
1449 	newcsum = 0;
1450 	for (; size >= 4; size -= 4)
1451 		newcsum += le32_to_cpu(*isuper++);
1452 
1453 	if (size == 2)
1454 		newcsum += le16_to_cpu(*(__le16*) isuper);
1455 
1456 	csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1457 	sb->sb_csum = disk_csum;
1458 	return cpu_to_le32(csum);
1459 }
1460 
1461 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1462 {
1463 	struct mdp_superblock_1 *sb;
1464 	int ret;
1465 	sector_t sb_start;
1466 	sector_t sectors;
1467 	char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1468 	int bmask;
1469 
1470 	/*
1471 	 * Calculate the position of the superblock in 512byte sectors.
1472 	 * It is always aligned to a 4K boundary and
1473 	 * depeding on minor_version, it can be:
1474 	 * 0: At least 8K, but less than 12K, from end of device
1475 	 * 1: At start of device
1476 	 * 2: 4K from start of device.
1477 	 */
1478 	switch(minor_version) {
1479 	case 0:
1480 		sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1481 		sb_start -= 8*2;
1482 		sb_start &= ~(sector_t)(4*2-1);
1483 		break;
1484 	case 1:
1485 		sb_start = 0;
1486 		break;
1487 	case 2:
1488 		sb_start = 8;
1489 		break;
1490 	default:
1491 		return -EINVAL;
1492 	}
1493 	rdev->sb_start = sb_start;
1494 
1495 	/* superblock is rarely larger than 1K, but it can be larger,
1496 	 * and it is safe to read 4k, so we do that
1497 	 */
1498 	ret = read_disk_sb(rdev, 4096);
1499 	if (ret) return ret;
1500 
1501 	sb = page_address(rdev->sb_page);
1502 
1503 	if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1504 	    sb->major_version != cpu_to_le32(1) ||
1505 	    le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1506 	    le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1507 	    (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1508 		return -EINVAL;
1509 
1510 	if (calc_sb_1_csum(sb) != sb->sb_csum) {
1511 		pr_warn("md: invalid superblock checksum on %s\n",
1512 			bdevname(rdev->bdev,b));
1513 		return -EINVAL;
1514 	}
1515 	if (le64_to_cpu(sb->data_size) < 10) {
1516 		pr_warn("md: data_size too small on %s\n",
1517 			bdevname(rdev->bdev,b));
1518 		return -EINVAL;
1519 	}
1520 	if (sb->pad0 ||
1521 	    sb->pad3[0] ||
1522 	    memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1523 		/* Some padding is non-zero, might be a new feature */
1524 		return -EINVAL;
1525 
1526 	rdev->preferred_minor = 0xffff;
1527 	rdev->data_offset = le64_to_cpu(sb->data_offset);
1528 	rdev->new_data_offset = rdev->data_offset;
1529 	if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1530 	    (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1531 		rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1532 	atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1533 
1534 	rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1535 	bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1536 	if (rdev->sb_size & bmask)
1537 		rdev->sb_size = (rdev->sb_size | bmask) + 1;
1538 
1539 	if (minor_version
1540 	    && rdev->data_offset < sb_start + (rdev->sb_size/512))
1541 		return -EINVAL;
1542 	if (minor_version
1543 	    && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1544 		return -EINVAL;
1545 
1546 	if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1547 		rdev->desc_nr = -1;
1548 	else
1549 		rdev->desc_nr = le32_to_cpu(sb->dev_number);
1550 
1551 	if (!rdev->bb_page) {
1552 		rdev->bb_page = alloc_page(GFP_KERNEL);
1553 		if (!rdev->bb_page)
1554 			return -ENOMEM;
1555 	}
1556 	if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1557 	    rdev->badblocks.count == 0) {
1558 		/* need to load the bad block list.
1559 		 * Currently we limit it to one page.
1560 		 */
1561 		s32 offset;
1562 		sector_t bb_sector;
1563 		u64 *bbp;
1564 		int i;
1565 		int sectors = le16_to_cpu(sb->bblog_size);
1566 		if (sectors > (PAGE_SIZE / 512))
1567 			return -EINVAL;
1568 		offset = le32_to_cpu(sb->bblog_offset);
1569 		if (offset == 0)
1570 			return -EINVAL;
1571 		bb_sector = (long long)offset;
1572 		if (!sync_page_io(rdev, bb_sector, sectors << 9,
1573 				  rdev->bb_page, REQ_OP_READ, 0, true))
1574 			return -EIO;
1575 		bbp = (u64 *)page_address(rdev->bb_page);
1576 		rdev->badblocks.shift = sb->bblog_shift;
1577 		for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1578 			u64 bb = le64_to_cpu(*bbp);
1579 			int count = bb & (0x3ff);
1580 			u64 sector = bb >> 10;
1581 			sector <<= sb->bblog_shift;
1582 			count <<= sb->bblog_shift;
1583 			if (bb + 1 == 0)
1584 				break;
1585 			if (badblocks_set(&rdev->badblocks, sector, count, 1))
1586 				return -EINVAL;
1587 		}
1588 	} else if (sb->bblog_offset != 0)
1589 		rdev->badblocks.shift = 0;
1590 
1591 	if ((le32_to_cpu(sb->feature_map) &
1592 	    (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS))) {
1593 		rdev->ppl.offset = (__s16)le16_to_cpu(sb->ppl.offset);
1594 		rdev->ppl.size = le16_to_cpu(sb->ppl.size);
1595 		rdev->ppl.sector = rdev->sb_start + rdev->ppl.offset;
1596 	}
1597 
1598 	if (!refdev) {
1599 		ret = 1;
1600 	} else {
1601 		__u64 ev1, ev2;
1602 		struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1603 
1604 		if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1605 		    sb->level != refsb->level ||
1606 		    sb->layout != refsb->layout ||
1607 		    sb->chunksize != refsb->chunksize) {
1608 			pr_warn("md: %s has strangely different superblock to %s\n",
1609 				bdevname(rdev->bdev,b),
1610 				bdevname(refdev->bdev,b2));
1611 			return -EINVAL;
1612 		}
1613 		ev1 = le64_to_cpu(sb->events);
1614 		ev2 = le64_to_cpu(refsb->events);
1615 
1616 		if (ev1 > ev2)
1617 			ret = 1;
1618 		else
1619 			ret = 0;
1620 	}
1621 	if (minor_version) {
1622 		sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1623 		sectors -= rdev->data_offset;
1624 	} else
1625 		sectors = rdev->sb_start;
1626 	if (sectors < le64_to_cpu(sb->data_size))
1627 		return -EINVAL;
1628 	rdev->sectors = le64_to_cpu(sb->data_size);
1629 	return ret;
1630 }
1631 
1632 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1633 {
1634 	struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1635 	__u64 ev1 = le64_to_cpu(sb->events);
1636 
1637 	rdev->raid_disk = -1;
1638 	clear_bit(Faulty, &rdev->flags);
1639 	clear_bit(In_sync, &rdev->flags);
1640 	clear_bit(Bitmap_sync, &rdev->flags);
1641 	clear_bit(WriteMostly, &rdev->flags);
1642 
1643 	if (mddev->raid_disks == 0) {
1644 		mddev->major_version = 1;
1645 		mddev->patch_version = 0;
1646 		mddev->external = 0;
1647 		mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1648 		mddev->ctime = le64_to_cpu(sb->ctime);
1649 		mddev->utime = le64_to_cpu(sb->utime);
1650 		mddev->level = le32_to_cpu(sb->level);
1651 		mddev->clevel[0] = 0;
1652 		mddev->layout = le32_to_cpu(sb->layout);
1653 		mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1654 		mddev->dev_sectors = le64_to_cpu(sb->size);
1655 		mddev->events = ev1;
1656 		mddev->bitmap_info.offset = 0;
1657 		mddev->bitmap_info.space = 0;
1658 		/* Default location for bitmap is 1K after superblock
1659 		 * using 3K - total of 4K
1660 		 */
1661 		mddev->bitmap_info.default_offset = 1024 >> 9;
1662 		mddev->bitmap_info.default_space = (4096-1024) >> 9;
1663 		mddev->reshape_backwards = 0;
1664 
1665 		mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1666 		memcpy(mddev->uuid, sb->set_uuid, 16);
1667 
1668 		mddev->max_disks =  (4096-256)/2;
1669 
1670 		if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1671 		    mddev->bitmap_info.file == NULL) {
1672 			mddev->bitmap_info.offset =
1673 				(__s32)le32_to_cpu(sb->bitmap_offset);
1674 			/* Metadata doesn't record how much space is available.
1675 			 * For 1.0, we assume we can use up to the superblock
1676 			 * if before, else to 4K beyond superblock.
1677 			 * For others, assume no change is possible.
1678 			 */
1679 			if (mddev->minor_version > 0)
1680 				mddev->bitmap_info.space = 0;
1681 			else if (mddev->bitmap_info.offset > 0)
1682 				mddev->bitmap_info.space =
1683 					8 - mddev->bitmap_info.offset;
1684 			else
1685 				mddev->bitmap_info.space =
1686 					-mddev->bitmap_info.offset;
1687 		}
1688 
1689 		if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1690 			mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1691 			mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1692 			mddev->new_level = le32_to_cpu(sb->new_level);
1693 			mddev->new_layout = le32_to_cpu(sb->new_layout);
1694 			mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1695 			if (mddev->delta_disks < 0 ||
1696 			    (mddev->delta_disks == 0 &&
1697 			     (le32_to_cpu(sb->feature_map)
1698 			      & MD_FEATURE_RESHAPE_BACKWARDS)))
1699 				mddev->reshape_backwards = 1;
1700 		} else {
1701 			mddev->reshape_position = MaxSector;
1702 			mddev->delta_disks = 0;
1703 			mddev->new_level = mddev->level;
1704 			mddev->new_layout = mddev->layout;
1705 			mddev->new_chunk_sectors = mddev->chunk_sectors;
1706 		}
1707 
1708 		if (le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)
1709 			set_bit(MD_HAS_JOURNAL, &mddev->flags);
1710 
1711 		if (le32_to_cpu(sb->feature_map) &
1712 		    (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS)) {
1713 			if (le32_to_cpu(sb->feature_map) &
1714 			    (MD_FEATURE_BITMAP_OFFSET | MD_FEATURE_JOURNAL))
1715 				return -EINVAL;
1716 			if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_PPL) &&
1717 			    (le32_to_cpu(sb->feature_map) &
1718 					    MD_FEATURE_MULTIPLE_PPLS))
1719 				return -EINVAL;
1720 			set_bit(MD_HAS_PPL, &mddev->flags);
1721 		}
1722 	} else if (mddev->pers == NULL) {
1723 		/* Insist of good event counter while assembling, except for
1724 		 * spares (which don't need an event count) */
1725 		++ev1;
1726 		if (rdev->desc_nr >= 0 &&
1727 		    rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1728 		    (le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < MD_DISK_ROLE_MAX ||
1729 		     le16_to_cpu(sb->dev_roles[rdev->desc_nr]) == MD_DISK_ROLE_JOURNAL))
1730 			if (ev1 < mddev->events)
1731 				return -EINVAL;
1732 	} else if (mddev->bitmap) {
1733 		/* If adding to array with a bitmap, then we can accept an
1734 		 * older device, but not too old.
1735 		 */
1736 		if (ev1 < mddev->bitmap->events_cleared)
1737 			return 0;
1738 		if (ev1 < mddev->events)
1739 			set_bit(Bitmap_sync, &rdev->flags);
1740 	} else {
1741 		if (ev1 < mddev->events)
1742 			/* just a hot-add of a new device, leave raid_disk at -1 */
1743 			return 0;
1744 	}
1745 	if (mddev->level != LEVEL_MULTIPATH) {
1746 		int role;
1747 		if (rdev->desc_nr < 0 ||
1748 		    rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1749 			role = MD_DISK_ROLE_SPARE;
1750 			rdev->desc_nr = -1;
1751 		} else
1752 			role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1753 		switch(role) {
1754 		case MD_DISK_ROLE_SPARE: /* spare */
1755 			break;
1756 		case MD_DISK_ROLE_FAULTY: /* faulty */
1757 			set_bit(Faulty, &rdev->flags);
1758 			break;
1759 		case MD_DISK_ROLE_JOURNAL: /* journal device */
1760 			if (!(le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)) {
1761 				/* journal device without journal feature */
1762 				pr_warn("md: journal device provided without journal feature, ignoring the device\n");
1763 				return -EINVAL;
1764 			}
1765 			set_bit(Journal, &rdev->flags);
1766 			rdev->journal_tail = le64_to_cpu(sb->journal_tail);
1767 			rdev->raid_disk = 0;
1768 			break;
1769 		default:
1770 			rdev->saved_raid_disk = role;
1771 			if ((le32_to_cpu(sb->feature_map) &
1772 			     MD_FEATURE_RECOVERY_OFFSET)) {
1773 				rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1774 				if (!(le32_to_cpu(sb->feature_map) &
1775 				      MD_FEATURE_RECOVERY_BITMAP))
1776 					rdev->saved_raid_disk = -1;
1777 			} else
1778 				set_bit(In_sync, &rdev->flags);
1779 			rdev->raid_disk = role;
1780 			break;
1781 		}
1782 		if (sb->devflags & WriteMostly1)
1783 			set_bit(WriteMostly, &rdev->flags);
1784 		if (sb->devflags & FailFast1)
1785 			set_bit(FailFast, &rdev->flags);
1786 		if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1787 			set_bit(Replacement, &rdev->flags);
1788 	} else /* MULTIPATH are always insync */
1789 		set_bit(In_sync, &rdev->flags);
1790 
1791 	return 0;
1792 }
1793 
1794 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1795 {
1796 	struct mdp_superblock_1 *sb;
1797 	struct md_rdev *rdev2;
1798 	int max_dev, i;
1799 	/* make rdev->sb match mddev and rdev data. */
1800 
1801 	sb = page_address(rdev->sb_page);
1802 
1803 	sb->feature_map = 0;
1804 	sb->pad0 = 0;
1805 	sb->recovery_offset = cpu_to_le64(0);
1806 	memset(sb->pad3, 0, sizeof(sb->pad3));
1807 
1808 	sb->utime = cpu_to_le64((__u64)mddev->utime);
1809 	sb->events = cpu_to_le64(mddev->events);
1810 	if (mddev->in_sync)
1811 		sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1812 	else if (test_bit(MD_JOURNAL_CLEAN, &mddev->flags))
1813 		sb->resync_offset = cpu_to_le64(MaxSector);
1814 	else
1815 		sb->resync_offset = cpu_to_le64(0);
1816 
1817 	sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1818 
1819 	sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1820 	sb->size = cpu_to_le64(mddev->dev_sectors);
1821 	sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1822 	sb->level = cpu_to_le32(mddev->level);
1823 	sb->layout = cpu_to_le32(mddev->layout);
1824 	if (test_bit(FailFast, &rdev->flags))
1825 		sb->devflags |= FailFast1;
1826 	else
1827 		sb->devflags &= ~FailFast1;
1828 
1829 	if (test_bit(WriteMostly, &rdev->flags))
1830 		sb->devflags |= WriteMostly1;
1831 	else
1832 		sb->devflags &= ~WriteMostly1;
1833 	sb->data_offset = cpu_to_le64(rdev->data_offset);
1834 	sb->data_size = cpu_to_le64(rdev->sectors);
1835 
1836 	if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1837 		sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1838 		sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1839 	}
1840 
1841 	if (rdev->raid_disk >= 0 && !test_bit(Journal, &rdev->flags) &&
1842 	    !test_bit(In_sync, &rdev->flags)) {
1843 		sb->feature_map |=
1844 			cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1845 		sb->recovery_offset =
1846 			cpu_to_le64(rdev->recovery_offset);
1847 		if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1848 			sb->feature_map |=
1849 				cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1850 	}
1851 	/* Note: recovery_offset and journal_tail share space  */
1852 	if (test_bit(Journal, &rdev->flags))
1853 		sb->journal_tail = cpu_to_le64(rdev->journal_tail);
1854 	if (test_bit(Replacement, &rdev->flags))
1855 		sb->feature_map |=
1856 			cpu_to_le32(MD_FEATURE_REPLACEMENT);
1857 
1858 	if (mddev->reshape_position != MaxSector) {
1859 		sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1860 		sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1861 		sb->new_layout = cpu_to_le32(mddev->new_layout);
1862 		sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1863 		sb->new_level = cpu_to_le32(mddev->new_level);
1864 		sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1865 		if (mddev->delta_disks == 0 &&
1866 		    mddev->reshape_backwards)
1867 			sb->feature_map
1868 				|= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1869 		if (rdev->new_data_offset != rdev->data_offset) {
1870 			sb->feature_map
1871 				|= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1872 			sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1873 							     - rdev->data_offset));
1874 		}
1875 	}
1876 
1877 	if (mddev_is_clustered(mddev))
1878 		sb->feature_map |= cpu_to_le32(MD_FEATURE_CLUSTERED);
1879 
1880 	if (rdev->badblocks.count == 0)
1881 		/* Nothing to do for bad blocks*/ ;
1882 	else if (sb->bblog_offset == 0)
1883 		/* Cannot record bad blocks on this device */
1884 		md_error(mddev, rdev);
1885 	else {
1886 		struct badblocks *bb = &rdev->badblocks;
1887 		u64 *bbp = (u64 *)page_address(rdev->bb_page);
1888 		u64 *p = bb->page;
1889 		sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1890 		if (bb->changed) {
1891 			unsigned seq;
1892 
1893 retry:
1894 			seq = read_seqbegin(&bb->lock);
1895 
1896 			memset(bbp, 0xff, PAGE_SIZE);
1897 
1898 			for (i = 0 ; i < bb->count ; i++) {
1899 				u64 internal_bb = p[i];
1900 				u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1901 						| BB_LEN(internal_bb));
1902 				bbp[i] = cpu_to_le64(store_bb);
1903 			}
1904 			bb->changed = 0;
1905 			if (read_seqretry(&bb->lock, seq))
1906 				goto retry;
1907 
1908 			bb->sector = (rdev->sb_start +
1909 				      (int)le32_to_cpu(sb->bblog_offset));
1910 			bb->size = le16_to_cpu(sb->bblog_size);
1911 		}
1912 	}
1913 
1914 	max_dev = 0;
1915 	rdev_for_each(rdev2, mddev)
1916 		if (rdev2->desc_nr+1 > max_dev)
1917 			max_dev = rdev2->desc_nr+1;
1918 
1919 	if (max_dev > le32_to_cpu(sb->max_dev)) {
1920 		int bmask;
1921 		sb->max_dev = cpu_to_le32(max_dev);
1922 		rdev->sb_size = max_dev * 2 + 256;
1923 		bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1924 		if (rdev->sb_size & bmask)
1925 			rdev->sb_size = (rdev->sb_size | bmask) + 1;
1926 	} else
1927 		max_dev = le32_to_cpu(sb->max_dev);
1928 
1929 	for (i=0; i<max_dev;i++)
1930 		sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1931 
1932 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags))
1933 		sb->feature_map |= cpu_to_le32(MD_FEATURE_JOURNAL);
1934 
1935 	if (test_bit(MD_HAS_PPL, &mddev->flags)) {
1936 		if (test_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags))
1937 			sb->feature_map |=
1938 			    cpu_to_le32(MD_FEATURE_MULTIPLE_PPLS);
1939 		else
1940 			sb->feature_map |= cpu_to_le32(MD_FEATURE_PPL);
1941 		sb->ppl.offset = cpu_to_le16(rdev->ppl.offset);
1942 		sb->ppl.size = cpu_to_le16(rdev->ppl.size);
1943 	}
1944 
1945 	rdev_for_each(rdev2, mddev) {
1946 		i = rdev2->desc_nr;
1947 		if (test_bit(Faulty, &rdev2->flags))
1948 			sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_FAULTY);
1949 		else if (test_bit(In_sync, &rdev2->flags))
1950 			sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1951 		else if (test_bit(Journal, &rdev2->flags))
1952 			sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_JOURNAL);
1953 		else if (rdev2->raid_disk >= 0)
1954 			sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1955 		else
1956 			sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1957 	}
1958 
1959 	sb->sb_csum = calc_sb_1_csum(sb);
1960 }
1961 
1962 static unsigned long long
1963 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1964 {
1965 	struct mdp_superblock_1 *sb;
1966 	sector_t max_sectors;
1967 	if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1968 		return 0; /* component must fit device */
1969 	if (rdev->data_offset != rdev->new_data_offset)
1970 		return 0; /* too confusing */
1971 	if (rdev->sb_start < rdev->data_offset) {
1972 		/* minor versions 1 and 2; superblock before data */
1973 		max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1974 		max_sectors -= rdev->data_offset;
1975 		if (!num_sectors || num_sectors > max_sectors)
1976 			num_sectors = max_sectors;
1977 	} else if (rdev->mddev->bitmap_info.offset) {
1978 		/* minor version 0 with bitmap we can't move */
1979 		return 0;
1980 	} else {
1981 		/* minor version 0; superblock after data */
1982 		sector_t sb_start;
1983 		sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1984 		sb_start &= ~(sector_t)(4*2 - 1);
1985 		max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1986 		if (!num_sectors || num_sectors > max_sectors)
1987 			num_sectors = max_sectors;
1988 		rdev->sb_start = sb_start;
1989 	}
1990 	sb = page_address(rdev->sb_page);
1991 	sb->data_size = cpu_to_le64(num_sectors);
1992 	sb->super_offset = cpu_to_le64(rdev->sb_start);
1993 	sb->sb_csum = calc_sb_1_csum(sb);
1994 	do {
1995 		md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1996 			       rdev->sb_page);
1997 	} while (md_super_wait(rdev->mddev) < 0);
1998 	return num_sectors;
1999 
2000 }
2001 
2002 static int
2003 super_1_allow_new_offset(struct md_rdev *rdev,
2004 			 unsigned long long new_offset)
2005 {
2006 	/* All necessary checks on new >= old have been done */
2007 	struct bitmap *bitmap;
2008 	if (new_offset >= rdev->data_offset)
2009 		return 1;
2010 
2011 	/* with 1.0 metadata, there is no metadata to tread on
2012 	 * so we can always move back */
2013 	if (rdev->mddev->minor_version == 0)
2014 		return 1;
2015 
2016 	/* otherwise we must be sure not to step on
2017 	 * any metadata, so stay:
2018 	 * 36K beyond start of superblock
2019 	 * beyond end of badblocks
2020 	 * beyond write-intent bitmap
2021 	 */
2022 	if (rdev->sb_start + (32+4)*2 > new_offset)
2023 		return 0;
2024 	bitmap = rdev->mddev->bitmap;
2025 	if (bitmap && !rdev->mddev->bitmap_info.file &&
2026 	    rdev->sb_start + rdev->mddev->bitmap_info.offset +
2027 	    bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
2028 		return 0;
2029 	if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
2030 		return 0;
2031 
2032 	return 1;
2033 }
2034 
2035 static struct super_type super_types[] = {
2036 	[0] = {
2037 		.name	= "0.90.0",
2038 		.owner	= THIS_MODULE,
2039 		.load_super	    = super_90_load,
2040 		.validate_super	    = super_90_validate,
2041 		.sync_super	    = super_90_sync,
2042 		.rdev_size_change   = super_90_rdev_size_change,
2043 		.allow_new_offset   = super_90_allow_new_offset,
2044 	},
2045 	[1] = {
2046 		.name	= "md-1",
2047 		.owner	= THIS_MODULE,
2048 		.load_super	    = super_1_load,
2049 		.validate_super	    = super_1_validate,
2050 		.sync_super	    = super_1_sync,
2051 		.rdev_size_change   = super_1_rdev_size_change,
2052 		.allow_new_offset   = super_1_allow_new_offset,
2053 	},
2054 };
2055 
2056 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
2057 {
2058 	if (mddev->sync_super) {
2059 		mddev->sync_super(mddev, rdev);
2060 		return;
2061 	}
2062 
2063 	BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
2064 
2065 	super_types[mddev->major_version].sync_super(mddev, rdev);
2066 }
2067 
2068 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
2069 {
2070 	struct md_rdev *rdev, *rdev2;
2071 
2072 	rcu_read_lock();
2073 	rdev_for_each_rcu(rdev, mddev1) {
2074 		if (test_bit(Faulty, &rdev->flags) ||
2075 		    test_bit(Journal, &rdev->flags) ||
2076 		    rdev->raid_disk == -1)
2077 			continue;
2078 		rdev_for_each_rcu(rdev2, mddev2) {
2079 			if (test_bit(Faulty, &rdev2->flags) ||
2080 			    test_bit(Journal, &rdev2->flags) ||
2081 			    rdev2->raid_disk == -1)
2082 				continue;
2083 			if (rdev->bdev->bd_contains ==
2084 			    rdev2->bdev->bd_contains) {
2085 				rcu_read_unlock();
2086 				return 1;
2087 			}
2088 		}
2089 	}
2090 	rcu_read_unlock();
2091 	return 0;
2092 }
2093 
2094 static LIST_HEAD(pending_raid_disks);
2095 
2096 /*
2097  * Try to register data integrity profile for an mddev
2098  *
2099  * This is called when an array is started and after a disk has been kicked
2100  * from the array. It only succeeds if all working and active component devices
2101  * are integrity capable with matching profiles.
2102  */
2103 int md_integrity_register(struct mddev *mddev)
2104 {
2105 	struct md_rdev *rdev, *reference = NULL;
2106 
2107 	if (list_empty(&mddev->disks))
2108 		return 0; /* nothing to do */
2109 	if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
2110 		return 0; /* shouldn't register, or already is */
2111 	rdev_for_each(rdev, mddev) {
2112 		/* skip spares and non-functional disks */
2113 		if (test_bit(Faulty, &rdev->flags))
2114 			continue;
2115 		if (rdev->raid_disk < 0)
2116 			continue;
2117 		if (!reference) {
2118 			/* Use the first rdev as the reference */
2119 			reference = rdev;
2120 			continue;
2121 		}
2122 		/* does this rdev's profile match the reference profile? */
2123 		if (blk_integrity_compare(reference->bdev->bd_disk,
2124 				rdev->bdev->bd_disk) < 0)
2125 			return -EINVAL;
2126 	}
2127 	if (!reference || !bdev_get_integrity(reference->bdev))
2128 		return 0;
2129 	/*
2130 	 * All component devices are integrity capable and have matching
2131 	 * profiles, register the common profile for the md device.
2132 	 */
2133 	blk_integrity_register(mddev->gendisk,
2134 			       bdev_get_integrity(reference->bdev));
2135 
2136 	pr_debug("md: data integrity enabled on %s\n", mdname(mddev));
2137 	if (bioset_integrity_create(&mddev->bio_set, BIO_POOL_SIZE)) {
2138 		pr_err("md: failed to create integrity pool for %s\n",
2139 		       mdname(mddev));
2140 		return -EINVAL;
2141 	}
2142 	return 0;
2143 }
2144 EXPORT_SYMBOL(md_integrity_register);
2145 
2146 /*
2147  * Attempt to add an rdev, but only if it is consistent with the current
2148  * integrity profile
2149  */
2150 int md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2151 {
2152 	struct blk_integrity *bi_rdev;
2153 	struct blk_integrity *bi_mddev;
2154 	char name[BDEVNAME_SIZE];
2155 
2156 	if (!mddev->gendisk)
2157 		return 0;
2158 
2159 	bi_rdev = bdev_get_integrity(rdev->bdev);
2160 	bi_mddev = blk_get_integrity(mddev->gendisk);
2161 
2162 	if (!bi_mddev) /* nothing to do */
2163 		return 0;
2164 
2165 	if (blk_integrity_compare(mddev->gendisk, rdev->bdev->bd_disk) != 0) {
2166 		pr_err("%s: incompatible integrity profile for %s\n",
2167 		       mdname(mddev), bdevname(rdev->bdev, name));
2168 		return -ENXIO;
2169 	}
2170 
2171 	return 0;
2172 }
2173 EXPORT_SYMBOL(md_integrity_add_rdev);
2174 
2175 static int bind_rdev_to_array(struct md_rdev *rdev, struct mddev *mddev)
2176 {
2177 	char b[BDEVNAME_SIZE];
2178 	struct kobject *ko;
2179 	int err;
2180 
2181 	/* prevent duplicates */
2182 	if (find_rdev(mddev, rdev->bdev->bd_dev))
2183 		return -EEXIST;
2184 
2185 	if ((bdev_read_only(rdev->bdev) || bdev_read_only(rdev->meta_bdev)) &&
2186 	    mddev->pers)
2187 		return -EROFS;
2188 
2189 	/* make sure rdev->sectors exceeds mddev->dev_sectors */
2190 	if (!test_bit(Journal, &rdev->flags) &&
2191 	    rdev->sectors &&
2192 	    (mddev->dev_sectors == 0 || rdev->sectors < mddev->dev_sectors)) {
2193 		if (mddev->pers) {
2194 			/* Cannot change size, so fail
2195 			 * If mddev->level <= 0, then we don't care
2196 			 * about aligning sizes (e.g. linear)
2197 			 */
2198 			if (mddev->level > 0)
2199 				return -ENOSPC;
2200 		} else
2201 			mddev->dev_sectors = rdev->sectors;
2202 	}
2203 
2204 	/* Verify rdev->desc_nr is unique.
2205 	 * If it is -1, assign a free number, else
2206 	 * check number is not in use
2207 	 */
2208 	rcu_read_lock();
2209 	if (rdev->desc_nr < 0) {
2210 		int choice = 0;
2211 		if (mddev->pers)
2212 			choice = mddev->raid_disks;
2213 		while (md_find_rdev_nr_rcu(mddev, choice))
2214 			choice++;
2215 		rdev->desc_nr = choice;
2216 	} else {
2217 		if (md_find_rdev_nr_rcu(mddev, rdev->desc_nr)) {
2218 			rcu_read_unlock();
2219 			return -EBUSY;
2220 		}
2221 	}
2222 	rcu_read_unlock();
2223 	if (!test_bit(Journal, &rdev->flags) &&
2224 	    mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2225 		pr_warn("md: %s: array is limited to %d devices\n",
2226 			mdname(mddev), mddev->max_disks);
2227 		return -EBUSY;
2228 	}
2229 	bdevname(rdev->bdev,b);
2230 	strreplace(b, '/', '!');
2231 
2232 	rdev->mddev = mddev;
2233 	pr_debug("md: bind<%s>\n", b);
2234 
2235 	if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2236 		goto fail;
2237 
2238 	ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2239 	if (sysfs_create_link(&rdev->kobj, ko, "block"))
2240 		/* failure here is OK */;
2241 	rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2242 
2243 	list_add_rcu(&rdev->same_set, &mddev->disks);
2244 	bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2245 
2246 	/* May as well allow recovery to be retried once */
2247 	mddev->recovery_disabled++;
2248 
2249 	return 0;
2250 
2251  fail:
2252 	pr_warn("md: failed to register dev-%s for %s\n",
2253 		b, mdname(mddev));
2254 	return err;
2255 }
2256 
2257 static void md_delayed_delete(struct work_struct *ws)
2258 {
2259 	struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2260 	kobject_del(&rdev->kobj);
2261 	kobject_put(&rdev->kobj);
2262 }
2263 
2264 static void unbind_rdev_from_array(struct md_rdev *rdev)
2265 {
2266 	char b[BDEVNAME_SIZE];
2267 
2268 	bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2269 	list_del_rcu(&rdev->same_set);
2270 	pr_debug("md: unbind<%s>\n", bdevname(rdev->bdev,b));
2271 	rdev->mddev = NULL;
2272 	sysfs_remove_link(&rdev->kobj, "block");
2273 	sysfs_put(rdev->sysfs_state);
2274 	rdev->sysfs_state = NULL;
2275 	rdev->badblocks.count = 0;
2276 	/* We need to delay this, otherwise we can deadlock when
2277 	 * writing to 'remove' to "dev/state".  We also need
2278 	 * to delay it due to rcu usage.
2279 	 */
2280 	synchronize_rcu();
2281 	INIT_WORK(&rdev->del_work, md_delayed_delete);
2282 	kobject_get(&rdev->kobj);
2283 	queue_work(md_misc_wq, &rdev->del_work);
2284 }
2285 
2286 /*
2287  * prevent the device from being mounted, repartitioned or
2288  * otherwise reused by a RAID array (or any other kernel
2289  * subsystem), by bd_claiming the device.
2290  */
2291 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2292 {
2293 	int err = 0;
2294 	struct block_device *bdev;
2295 	char b[BDEVNAME_SIZE];
2296 
2297 	bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2298 				 shared ? (struct md_rdev *)lock_rdev : rdev);
2299 	if (IS_ERR(bdev)) {
2300 		pr_warn("md: could not open %s.\n", __bdevname(dev, b));
2301 		return PTR_ERR(bdev);
2302 	}
2303 	rdev->bdev = bdev;
2304 	return err;
2305 }
2306 
2307 static void unlock_rdev(struct md_rdev *rdev)
2308 {
2309 	struct block_device *bdev = rdev->bdev;
2310 	rdev->bdev = NULL;
2311 	blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2312 }
2313 
2314 void md_autodetect_dev(dev_t dev);
2315 
2316 static void export_rdev(struct md_rdev *rdev)
2317 {
2318 	char b[BDEVNAME_SIZE];
2319 
2320 	pr_debug("md: export_rdev(%s)\n", bdevname(rdev->bdev,b));
2321 	md_rdev_clear(rdev);
2322 #ifndef MODULE
2323 	if (test_bit(AutoDetected, &rdev->flags))
2324 		md_autodetect_dev(rdev->bdev->bd_dev);
2325 #endif
2326 	unlock_rdev(rdev);
2327 	kobject_put(&rdev->kobj);
2328 }
2329 
2330 void md_kick_rdev_from_array(struct md_rdev *rdev)
2331 {
2332 	unbind_rdev_from_array(rdev);
2333 	export_rdev(rdev);
2334 }
2335 EXPORT_SYMBOL_GPL(md_kick_rdev_from_array);
2336 
2337 static void export_array(struct mddev *mddev)
2338 {
2339 	struct md_rdev *rdev;
2340 
2341 	while (!list_empty(&mddev->disks)) {
2342 		rdev = list_first_entry(&mddev->disks, struct md_rdev,
2343 					same_set);
2344 		md_kick_rdev_from_array(rdev);
2345 	}
2346 	mddev->raid_disks = 0;
2347 	mddev->major_version = 0;
2348 }
2349 
2350 static bool set_in_sync(struct mddev *mddev)
2351 {
2352 	lockdep_assert_held(&mddev->lock);
2353 	if (!mddev->in_sync) {
2354 		mddev->sync_checkers++;
2355 		spin_unlock(&mddev->lock);
2356 		percpu_ref_switch_to_atomic_sync(&mddev->writes_pending);
2357 		spin_lock(&mddev->lock);
2358 		if (!mddev->in_sync &&
2359 		    percpu_ref_is_zero(&mddev->writes_pending)) {
2360 			mddev->in_sync = 1;
2361 			/*
2362 			 * Ensure ->in_sync is visible before we clear
2363 			 * ->sync_checkers.
2364 			 */
2365 			smp_mb();
2366 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2367 			sysfs_notify_dirent_safe(mddev->sysfs_state);
2368 		}
2369 		if (--mddev->sync_checkers == 0)
2370 			percpu_ref_switch_to_percpu(&mddev->writes_pending);
2371 	}
2372 	if (mddev->safemode == 1)
2373 		mddev->safemode = 0;
2374 	return mddev->in_sync;
2375 }
2376 
2377 static void sync_sbs(struct mddev *mddev, int nospares)
2378 {
2379 	/* Update each superblock (in-memory image), but
2380 	 * if we are allowed to, skip spares which already
2381 	 * have the right event counter, or have one earlier
2382 	 * (which would mean they aren't being marked as dirty
2383 	 * with the rest of the array)
2384 	 */
2385 	struct md_rdev *rdev;
2386 	rdev_for_each(rdev, mddev) {
2387 		if (rdev->sb_events == mddev->events ||
2388 		    (nospares &&
2389 		     rdev->raid_disk < 0 &&
2390 		     rdev->sb_events+1 == mddev->events)) {
2391 			/* Don't update this superblock */
2392 			rdev->sb_loaded = 2;
2393 		} else {
2394 			sync_super(mddev, rdev);
2395 			rdev->sb_loaded = 1;
2396 		}
2397 	}
2398 }
2399 
2400 static bool does_sb_need_changing(struct mddev *mddev)
2401 {
2402 	struct md_rdev *rdev;
2403 	struct mdp_superblock_1 *sb;
2404 	int role;
2405 
2406 	/* Find a good rdev */
2407 	rdev_for_each(rdev, mddev)
2408 		if ((rdev->raid_disk >= 0) && !test_bit(Faulty, &rdev->flags))
2409 			break;
2410 
2411 	/* No good device found. */
2412 	if (!rdev)
2413 		return false;
2414 
2415 	sb = page_address(rdev->sb_page);
2416 	/* Check if a device has become faulty or a spare become active */
2417 	rdev_for_each(rdev, mddev) {
2418 		role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
2419 		/* Device activated? */
2420 		if (role == 0xffff && rdev->raid_disk >=0 &&
2421 		    !test_bit(Faulty, &rdev->flags))
2422 			return true;
2423 		/* Device turned faulty? */
2424 		if (test_bit(Faulty, &rdev->flags) && (role < 0xfffd))
2425 			return true;
2426 	}
2427 
2428 	/* Check if any mddev parameters have changed */
2429 	if ((mddev->dev_sectors != le64_to_cpu(sb->size)) ||
2430 	    (mddev->reshape_position != le64_to_cpu(sb->reshape_position)) ||
2431 	    (mddev->layout != le32_to_cpu(sb->layout)) ||
2432 	    (mddev->raid_disks != le32_to_cpu(sb->raid_disks)) ||
2433 	    (mddev->chunk_sectors != le32_to_cpu(sb->chunksize)))
2434 		return true;
2435 
2436 	return false;
2437 }
2438 
2439 void md_update_sb(struct mddev *mddev, int force_change)
2440 {
2441 	struct md_rdev *rdev;
2442 	int sync_req;
2443 	int nospares = 0;
2444 	int any_badblocks_changed = 0;
2445 	int ret = -1;
2446 
2447 	if (mddev->ro) {
2448 		if (force_change)
2449 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2450 		return;
2451 	}
2452 
2453 repeat:
2454 	if (mddev_is_clustered(mddev)) {
2455 		if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2456 			force_change = 1;
2457 		if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2458 			nospares = 1;
2459 		ret = md_cluster_ops->metadata_update_start(mddev);
2460 		/* Has someone else has updated the sb */
2461 		if (!does_sb_need_changing(mddev)) {
2462 			if (ret == 0)
2463 				md_cluster_ops->metadata_update_cancel(mddev);
2464 			bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2465 							 BIT(MD_SB_CHANGE_DEVS) |
2466 							 BIT(MD_SB_CHANGE_CLEAN));
2467 			return;
2468 		}
2469 	}
2470 
2471 	/*
2472 	 * First make sure individual recovery_offsets are correct
2473 	 * curr_resync_completed can only be used during recovery.
2474 	 * During reshape/resync it might use array-addresses rather
2475 	 * that device addresses.
2476 	 */
2477 	rdev_for_each(rdev, mddev) {
2478 		if (rdev->raid_disk >= 0 &&
2479 		    mddev->delta_disks >= 0 &&
2480 		    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
2481 		    test_bit(MD_RECOVERY_RECOVER, &mddev->recovery) &&
2482 		    !test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
2483 		    !test_bit(Journal, &rdev->flags) &&
2484 		    !test_bit(In_sync, &rdev->flags) &&
2485 		    mddev->curr_resync_completed > rdev->recovery_offset)
2486 				rdev->recovery_offset = mddev->curr_resync_completed;
2487 
2488 	}
2489 	if (!mddev->persistent) {
2490 		clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2491 		clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2492 		if (!mddev->external) {
2493 			clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
2494 			rdev_for_each(rdev, mddev) {
2495 				if (rdev->badblocks.changed) {
2496 					rdev->badblocks.changed = 0;
2497 					ack_all_badblocks(&rdev->badblocks);
2498 					md_error(mddev, rdev);
2499 				}
2500 				clear_bit(Blocked, &rdev->flags);
2501 				clear_bit(BlockedBadBlocks, &rdev->flags);
2502 				wake_up(&rdev->blocked_wait);
2503 			}
2504 		}
2505 		wake_up(&mddev->sb_wait);
2506 		return;
2507 	}
2508 
2509 	spin_lock(&mddev->lock);
2510 
2511 	mddev->utime = ktime_get_real_seconds();
2512 
2513 	if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2514 		force_change = 1;
2515 	if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2516 		/* just a clean<-> dirty transition, possibly leave spares alone,
2517 		 * though if events isn't the right even/odd, we will have to do
2518 		 * spares after all
2519 		 */
2520 		nospares = 1;
2521 	if (force_change)
2522 		nospares = 0;
2523 	if (mddev->degraded)
2524 		/* If the array is degraded, then skipping spares is both
2525 		 * dangerous and fairly pointless.
2526 		 * Dangerous because a device that was removed from the array
2527 		 * might have a event_count that still looks up-to-date,
2528 		 * so it can be re-added without a resync.
2529 		 * Pointless because if there are any spares to skip,
2530 		 * then a recovery will happen and soon that array won't
2531 		 * be degraded any more and the spare can go back to sleep then.
2532 		 */
2533 		nospares = 0;
2534 
2535 	sync_req = mddev->in_sync;
2536 
2537 	/* If this is just a dirty<->clean transition, and the array is clean
2538 	 * and 'events' is odd, we can roll back to the previous clean state */
2539 	if (nospares
2540 	    && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2541 	    && mddev->can_decrease_events
2542 	    && mddev->events != 1) {
2543 		mddev->events--;
2544 		mddev->can_decrease_events = 0;
2545 	} else {
2546 		/* otherwise we have to go forward and ... */
2547 		mddev->events ++;
2548 		mddev->can_decrease_events = nospares;
2549 	}
2550 
2551 	/*
2552 	 * This 64-bit counter should never wrap.
2553 	 * Either we are in around ~1 trillion A.C., assuming
2554 	 * 1 reboot per second, or we have a bug...
2555 	 */
2556 	WARN_ON(mddev->events == 0);
2557 
2558 	rdev_for_each(rdev, mddev) {
2559 		if (rdev->badblocks.changed)
2560 			any_badblocks_changed++;
2561 		if (test_bit(Faulty, &rdev->flags))
2562 			set_bit(FaultRecorded, &rdev->flags);
2563 	}
2564 
2565 	sync_sbs(mddev, nospares);
2566 	spin_unlock(&mddev->lock);
2567 
2568 	pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2569 		 mdname(mddev), mddev->in_sync);
2570 
2571 	if (mddev->queue)
2572 		blk_add_trace_msg(mddev->queue, "md md_update_sb");
2573 rewrite:
2574 	bitmap_update_sb(mddev->bitmap);
2575 	rdev_for_each(rdev, mddev) {
2576 		char b[BDEVNAME_SIZE];
2577 
2578 		if (rdev->sb_loaded != 1)
2579 			continue; /* no noise on spare devices */
2580 
2581 		if (!test_bit(Faulty, &rdev->flags)) {
2582 			md_super_write(mddev,rdev,
2583 				       rdev->sb_start, rdev->sb_size,
2584 				       rdev->sb_page);
2585 			pr_debug("md: (write) %s's sb offset: %llu\n",
2586 				 bdevname(rdev->bdev, b),
2587 				 (unsigned long long)rdev->sb_start);
2588 			rdev->sb_events = mddev->events;
2589 			if (rdev->badblocks.size) {
2590 				md_super_write(mddev, rdev,
2591 					       rdev->badblocks.sector,
2592 					       rdev->badblocks.size << 9,
2593 					       rdev->bb_page);
2594 				rdev->badblocks.size = 0;
2595 			}
2596 
2597 		} else
2598 			pr_debug("md: %s (skipping faulty)\n",
2599 				 bdevname(rdev->bdev, b));
2600 
2601 		if (mddev->level == LEVEL_MULTIPATH)
2602 			/* only need to write one superblock... */
2603 			break;
2604 	}
2605 	if (md_super_wait(mddev) < 0)
2606 		goto rewrite;
2607 	/* if there was a failure, MD_SB_CHANGE_DEVS was set, and we re-write super */
2608 
2609 	if (mddev_is_clustered(mddev) && ret == 0)
2610 		md_cluster_ops->metadata_update_finish(mddev);
2611 
2612 	if (mddev->in_sync != sync_req ||
2613 	    !bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2614 			       BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_CLEAN)))
2615 		/* have to write it out again */
2616 		goto repeat;
2617 	wake_up(&mddev->sb_wait);
2618 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2619 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2620 
2621 	rdev_for_each(rdev, mddev) {
2622 		if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2623 			clear_bit(Blocked, &rdev->flags);
2624 
2625 		if (any_badblocks_changed)
2626 			ack_all_badblocks(&rdev->badblocks);
2627 		clear_bit(BlockedBadBlocks, &rdev->flags);
2628 		wake_up(&rdev->blocked_wait);
2629 	}
2630 }
2631 EXPORT_SYMBOL(md_update_sb);
2632 
2633 static int add_bound_rdev(struct md_rdev *rdev)
2634 {
2635 	struct mddev *mddev = rdev->mddev;
2636 	int err = 0;
2637 	bool add_journal = test_bit(Journal, &rdev->flags);
2638 
2639 	if (!mddev->pers->hot_remove_disk || add_journal) {
2640 		/* If there is hot_add_disk but no hot_remove_disk
2641 		 * then added disks for geometry changes,
2642 		 * and should be added immediately.
2643 		 */
2644 		super_types[mddev->major_version].
2645 			validate_super(mddev, rdev);
2646 		if (add_journal)
2647 			mddev_suspend(mddev);
2648 		err = mddev->pers->hot_add_disk(mddev, rdev);
2649 		if (add_journal)
2650 			mddev_resume(mddev);
2651 		if (err) {
2652 			md_kick_rdev_from_array(rdev);
2653 			return err;
2654 		}
2655 	}
2656 	sysfs_notify_dirent_safe(rdev->sysfs_state);
2657 
2658 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2659 	if (mddev->degraded)
2660 		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2661 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2662 	md_new_event(mddev);
2663 	md_wakeup_thread(mddev->thread);
2664 	return 0;
2665 }
2666 
2667 /* words written to sysfs files may, or may not, be \n terminated.
2668  * We want to accept with case. For this we use cmd_match.
2669  */
2670 static int cmd_match(const char *cmd, const char *str)
2671 {
2672 	/* See if cmd, written into a sysfs file, matches
2673 	 * str.  They must either be the same, or cmd can
2674 	 * have a trailing newline
2675 	 */
2676 	while (*cmd && *str && *cmd == *str) {
2677 		cmd++;
2678 		str++;
2679 	}
2680 	if (*cmd == '\n')
2681 		cmd++;
2682 	if (*str || *cmd)
2683 		return 0;
2684 	return 1;
2685 }
2686 
2687 struct rdev_sysfs_entry {
2688 	struct attribute attr;
2689 	ssize_t (*show)(struct md_rdev *, char *);
2690 	ssize_t (*store)(struct md_rdev *, const char *, size_t);
2691 };
2692 
2693 static ssize_t
2694 state_show(struct md_rdev *rdev, char *page)
2695 {
2696 	char *sep = ",";
2697 	size_t len = 0;
2698 	unsigned long flags = READ_ONCE(rdev->flags);
2699 
2700 	if (test_bit(Faulty, &flags) ||
2701 	    (!test_bit(ExternalBbl, &flags) &&
2702 	    rdev->badblocks.unacked_exist))
2703 		len += sprintf(page+len, "faulty%s", sep);
2704 	if (test_bit(In_sync, &flags))
2705 		len += sprintf(page+len, "in_sync%s", sep);
2706 	if (test_bit(Journal, &flags))
2707 		len += sprintf(page+len, "journal%s", sep);
2708 	if (test_bit(WriteMostly, &flags))
2709 		len += sprintf(page+len, "write_mostly%s", sep);
2710 	if (test_bit(Blocked, &flags) ||
2711 	    (rdev->badblocks.unacked_exist
2712 	     && !test_bit(Faulty, &flags)))
2713 		len += sprintf(page+len, "blocked%s", sep);
2714 	if (!test_bit(Faulty, &flags) &&
2715 	    !test_bit(Journal, &flags) &&
2716 	    !test_bit(In_sync, &flags))
2717 		len += sprintf(page+len, "spare%s", sep);
2718 	if (test_bit(WriteErrorSeen, &flags))
2719 		len += sprintf(page+len, "write_error%s", sep);
2720 	if (test_bit(WantReplacement, &flags))
2721 		len += sprintf(page+len, "want_replacement%s", sep);
2722 	if (test_bit(Replacement, &flags))
2723 		len += sprintf(page+len, "replacement%s", sep);
2724 	if (test_bit(ExternalBbl, &flags))
2725 		len += sprintf(page+len, "external_bbl%s", sep);
2726 	if (test_bit(FailFast, &flags))
2727 		len += sprintf(page+len, "failfast%s", sep);
2728 
2729 	if (len)
2730 		len -= strlen(sep);
2731 
2732 	return len+sprintf(page+len, "\n");
2733 }
2734 
2735 static ssize_t
2736 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2737 {
2738 	/* can write
2739 	 *  faulty  - simulates an error
2740 	 *  remove  - disconnects the device
2741 	 *  writemostly - sets write_mostly
2742 	 *  -writemostly - clears write_mostly
2743 	 *  blocked - sets the Blocked flags
2744 	 *  -blocked - clears the Blocked and possibly simulates an error
2745 	 *  insync - sets Insync providing device isn't active
2746 	 *  -insync - clear Insync for a device with a slot assigned,
2747 	 *            so that it gets rebuilt based on bitmap
2748 	 *  write_error - sets WriteErrorSeen
2749 	 *  -write_error - clears WriteErrorSeen
2750 	 *  {,-}failfast - set/clear FailFast
2751 	 */
2752 	int err = -EINVAL;
2753 	if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2754 		md_error(rdev->mddev, rdev);
2755 		if (test_bit(Faulty, &rdev->flags))
2756 			err = 0;
2757 		else
2758 			err = -EBUSY;
2759 	} else if (cmd_match(buf, "remove")) {
2760 		if (rdev->mddev->pers) {
2761 			clear_bit(Blocked, &rdev->flags);
2762 			remove_and_add_spares(rdev->mddev, rdev);
2763 		}
2764 		if (rdev->raid_disk >= 0)
2765 			err = -EBUSY;
2766 		else {
2767 			struct mddev *mddev = rdev->mddev;
2768 			err = 0;
2769 			if (mddev_is_clustered(mddev))
2770 				err = md_cluster_ops->remove_disk(mddev, rdev);
2771 
2772 			if (err == 0) {
2773 				md_kick_rdev_from_array(rdev);
2774 				if (mddev->pers) {
2775 					set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2776 					md_wakeup_thread(mddev->thread);
2777 				}
2778 				md_new_event(mddev);
2779 			}
2780 		}
2781 	} else if (cmd_match(buf, "writemostly")) {
2782 		set_bit(WriteMostly, &rdev->flags);
2783 		err = 0;
2784 	} else if (cmd_match(buf, "-writemostly")) {
2785 		clear_bit(WriteMostly, &rdev->flags);
2786 		err = 0;
2787 	} else if (cmd_match(buf, "blocked")) {
2788 		set_bit(Blocked, &rdev->flags);
2789 		err = 0;
2790 	} else if (cmd_match(buf, "-blocked")) {
2791 		if (!test_bit(Faulty, &rdev->flags) &&
2792 		    !test_bit(ExternalBbl, &rdev->flags) &&
2793 		    rdev->badblocks.unacked_exist) {
2794 			/* metadata handler doesn't understand badblocks,
2795 			 * so we need to fail the device
2796 			 */
2797 			md_error(rdev->mddev, rdev);
2798 		}
2799 		clear_bit(Blocked, &rdev->flags);
2800 		clear_bit(BlockedBadBlocks, &rdev->flags);
2801 		wake_up(&rdev->blocked_wait);
2802 		set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2803 		md_wakeup_thread(rdev->mddev->thread);
2804 
2805 		err = 0;
2806 	} else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2807 		set_bit(In_sync, &rdev->flags);
2808 		err = 0;
2809 	} else if (cmd_match(buf, "failfast")) {
2810 		set_bit(FailFast, &rdev->flags);
2811 		err = 0;
2812 	} else if (cmd_match(buf, "-failfast")) {
2813 		clear_bit(FailFast, &rdev->flags);
2814 		err = 0;
2815 	} else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0 &&
2816 		   !test_bit(Journal, &rdev->flags)) {
2817 		if (rdev->mddev->pers == NULL) {
2818 			clear_bit(In_sync, &rdev->flags);
2819 			rdev->saved_raid_disk = rdev->raid_disk;
2820 			rdev->raid_disk = -1;
2821 			err = 0;
2822 		}
2823 	} else if (cmd_match(buf, "write_error")) {
2824 		set_bit(WriteErrorSeen, &rdev->flags);
2825 		err = 0;
2826 	} else if (cmd_match(buf, "-write_error")) {
2827 		clear_bit(WriteErrorSeen, &rdev->flags);
2828 		err = 0;
2829 	} else if (cmd_match(buf, "want_replacement")) {
2830 		/* Any non-spare device that is not a replacement can
2831 		 * become want_replacement at any time, but we then need to
2832 		 * check if recovery is needed.
2833 		 */
2834 		if (rdev->raid_disk >= 0 &&
2835 		    !test_bit(Journal, &rdev->flags) &&
2836 		    !test_bit(Replacement, &rdev->flags))
2837 			set_bit(WantReplacement, &rdev->flags);
2838 		set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2839 		md_wakeup_thread(rdev->mddev->thread);
2840 		err = 0;
2841 	} else if (cmd_match(buf, "-want_replacement")) {
2842 		/* Clearing 'want_replacement' is always allowed.
2843 		 * Once replacements starts it is too late though.
2844 		 */
2845 		err = 0;
2846 		clear_bit(WantReplacement, &rdev->flags);
2847 	} else if (cmd_match(buf, "replacement")) {
2848 		/* Can only set a device as a replacement when array has not
2849 		 * yet been started.  Once running, replacement is automatic
2850 		 * from spares, or by assigning 'slot'.
2851 		 */
2852 		if (rdev->mddev->pers)
2853 			err = -EBUSY;
2854 		else {
2855 			set_bit(Replacement, &rdev->flags);
2856 			err = 0;
2857 		}
2858 	} else if (cmd_match(buf, "-replacement")) {
2859 		/* Similarly, can only clear Replacement before start */
2860 		if (rdev->mddev->pers)
2861 			err = -EBUSY;
2862 		else {
2863 			clear_bit(Replacement, &rdev->flags);
2864 			err = 0;
2865 		}
2866 	} else if (cmd_match(buf, "re-add")) {
2867 		if (test_bit(Faulty, &rdev->flags) && (rdev->raid_disk == -1) &&
2868 			rdev->saved_raid_disk >= 0) {
2869 			/* clear_bit is performed _after_ all the devices
2870 			 * have their local Faulty bit cleared. If any writes
2871 			 * happen in the meantime in the local node, they
2872 			 * will land in the local bitmap, which will be synced
2873 			 * by this node eventually
2874 			 */
2875 			if (!mddev_is_clustered(rdev->mddev) ||
2876 			    (err = md_cluster_ops->gather_bitmaps(rdev)) == 0) {
2877 				clear_bit(Faulty, &rdev->flags);
2878 				err = add_bound_rdev(rdev);
2879 			}
2880 		} else
2881 			err = -EBUSY;
2882 	} else if (cmd_match(buf, "external_bbl") && (rdev->mddev->external)) {
2883 		set_bit(ExternalBbl, &rdev->flags);
2884 		rdev->badblocks.shift = 0;
2885 		err = 0;
2886 	} else if (cmd_match(buf, "-external_bbl") && (rdev->mddev->external)) {
2887 		clear_bit(ExternalBbl, &rdev->flags);
2888 		err = 0;
2889 	}
2890 	if (!err)
2891 		sysfs_notify_dirent_safe(rdev->sysfs_state);
2892 	return err ? err : len;
2893 }
2894 static struct rdev_sysfs_entry rdev_state =
2895 __ATTR_PREALLOC(state, S_IRUGO|S_IWUSR, state_show, state_store);
2896 
2897 static ssize_t
2898 errors_show(struct md_rdev *rdev, char *page)
2899 {
2900 	return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2901 }
2902 
2903 static ssize_t
2904 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2905 {
2906 	unsigned int n;
2907 	int rv;
2908 
2909 	rv = kstrtouint(buf, 10, &n);
2910 	if (rv < 0)
2911 		return rv;
2912 	atomic_set(&rdev->corrected_errors, n);
2913 	return len;
2914 }
2915 static struct rdev_sysfs_entry rdev_errors =
2916 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2917 
2918 static ssize_t
2919 slot_show(struct md_rdev *rdev, char *page)
2920 {
2921 	if (test_bit(Journal, &rdev->flags))
2922 		return sprintf(page, "journal\n");
2923 	else if (rdev->raid_disk < 0)
2924 		return sprintf(page, "none\n");
2925 	else
2926 		return sprintf(page, "%d\n", rdev->raid_disk);
2927 }
2928 
2929 static ssize_t
2930 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2931 {
2932 	int slot;
2933 	int err;
2934 
2935 	if (test_bit(Journal, &rdev->flags))
2936 		return -EBUSY;
2937 	if (strncmp(buf, "none", 4)==0)
2938 		slot = -1;
2939 	else {
2940 		err = kstrtouint(buf, 10, (unsigned int *)&slot);
2941 		if (err < 0)
2942 			return err;
2943 	}
2944 	if (rdev->mddev->pers && slot == -1) {
2945 		/* Setting 'slot' on an active array requires also
2946 		 * updating the 'rd%d' link, and communicating
2947 		 * with the personality with ->hot_*_disk.
2948 		 * For now we only support removing
2949 		 * failed/spare devices.  This normally happens automatically,
2950 		 * but not when the metadata is externally managed.
2951 		 */
2952 		if (rdev->raid_disk == -1)
2953 			return -EEXIST;
2954 		/* personality does all needed checks */
2955 		if (rdev->mddev->pers->hot_remove_disk == NULL)
2956 			return -EINVAL;
2957 		clear_bit(Blocked, &rdev->flags);
2958 		remove_and_add_spares(rdev->mddev, rdev);
2959 		if (rdev->raid_disk >= 0)
2960 			return -EBUSY;
2961 		set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2962 		md_wakeup_thread(rdev->mddev->thread);
2963 	} else if (rdev->mddev->pers) {
2964 		/* Activating a spare .. or possibly reactivating
2965 		 * if we ever get bitmaps working here.
2966 		 */
2967 		int err;
2968 
2969 		if (rdev->raid_disk != -1)
2970 			return -EBUSY;
2971 
2972 		if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2973 			return -EBUSY;
2974 
2975 		if (rdev->mddev->pers->hot_add_disk == NULL)
2976 			return -EINVAL;
2977 
2978 		if (slot >= rdev->mddev->raid_disks &&
2979 		    slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2980 			return -ENOSPC;
2981 
2982 		rdev->raid_disk = slot;
2983 		if (test_bit(In_sync, &rdev->flags))
2984 			rdev->saved_raid_disk = slot;
2985 		else
2986 			rdev->saved_raid_disk = -1;
2987 		clear_bit(In_sync, &rdev->flags);
2988 		clear_bit(Bitmap_sync, &rdev->flags);
2989 		err = rdev->mddev->pers->
2990 			hot_add_disk(rdev->mddev, rdev);
2991 		if (err) {
2992 			rdev->raid_disk = -1;
2993 			return err;
2994 		} else
2995 			sysfs_notify_dirent_safe(rdev->sysfs_state);
2996 		if (sysfs_link_rdev(rdev->mddev, rdev))
2997 			/* failure here is OK */;
2998 		/* don't wakeup anyone, leave that to userspace. */
2999 	} else {
3000 		if (slot >= rdev->mddev->raid_disks &&
3001 		    slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
3002 			return -ENOSPC;
3003 		rdev->raid_disk = slot;
3004 		/* assume it is working */
3005 		clear_bit(Faulty, &rdev->flags);
3006 		clear_bit(WriteMostly, &rdev->flags);
3007 		set_bit(In_sync, &rdev->flags);
3008 		sysfs_notify_dirent_safe(rdev->sysfs_state);
3009 	}
3010 	return len;
3011 }
3012 
3013 static struct rdev_sysfs_entry rdev_slot =
3014 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
3015 
3016 static ssize_t
3017 offset_show(struct md_rdev *rdev, char *page)
3018 {
3019 	return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
3020 }
3021 
3022 static ssize_t
3023 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
3024 {
3025 	unsigned long long offset;
3026 	if (kstrtoull(buf, 10, &offset) < 0)
3027 		return -EINVAL;
3028 	if (rdev->mddev->pers && rdev->raid_disk >= 0)
3029 		return -EBUSY;
3030 	if (rdev->sectors && rdev->mddev->external)
3031 		/* Must set offset before size, so overlap checks
3032 		 * can be sane */
3033 		return -EBUSY;
3034 	rdev->data_offset = offset;
3035 	rdev->new_data_offset = offset;
3036 	return len;
3037 }
3038 
3039 static struct rdev_sysfs_entry rdev_offset =
3040 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
3041 
3042 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
3043 {
3044 	return sprintf(page, "%llu\n",
3045 		       (unsigned long long)rdev->new_data_offset);
3046 }
3047 
3048 static ssize_t new_offset_store(struct md_rdev *rdev,
3049 				const char *buf, size_t len)
3050 {
3051 	unsigned long long new_offset;
3052 	struct mddev *mddev = rdev->mddev;
3053 
3054 	if (kstrtoull(buf, 10, &new_offset) < 0)
3055 		return -EINVAL;
3056 
3057 	if (mddev->sync_thread ||
3058 	    test_bit(MD_RECOVERY_RUNNING,&mddev->recovery))
3059 		return -EBUSY;
3060 	if (new_offset == rdev->data_offset)
3061 		/* reset is always permitted */
3062 		;
3063 	else if (new_offset > rdev->data_offset) {
3064 		/* must not push array size beyond rdev_sectors */
3065 		if (new_offset - rdev->data_offset
3066 		    + mddev->dev_sectors > rdev->sectors)
3067 				return -E2BIG;
3068 	}
3069 	/* Metadata worries about other space details. */
3070 
3071 	/* decreasing the offset is inconsistent with a backwards
3072 	 * reshape.
3073 	 */
3074 	if (new_offset < rdev->data_offset &&
3075 	    mddev->reshape_backwards)
3076 		return -EINVAL;
3077 	/* Increasing offset is inconsistent with forwards
3078 	 * reshape.  reshape_direction should be set to
3079 	 * 'backwards' first.
3080 	 */
3081 	if (new_offset > rdev->data_offset &&
3082 	    !mddev->reshape_backwards)
3083 		return -EINVAL;
3084 
3085 	if (mddev->pers && mddev->persistent &&
3086 	    !super_types[mddev->major_version]
3087 	    .allow_new_offset(rdev, new_offset))
3088 		return -E2BIG;
3089 	rdev->new_data_offset = new_offset;
3090 	if (new_offset > rdev->data_offset)
3091 		mddev->reshape_backwards = 1;
3092 	else if (new_offset < rdev->data_offset)
3093 		mddev->reshape_backwards = 0;
3094 
3095 	return len;
3096 }
3097 static struct rdev_sysfs_entry rdev_new_offset =
3098 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
3099 
3100 static ssize_t
3101 rdev_size_show(struct md_rdev *rdev, char *page)
3102 {
3103 	return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
3104 }
3105 
3106 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
3107 {
3108 	/* check if two start/length pairs overlap */
3109 	if (s1+l1 <= s2)
3110 		return 0;
3111 	if (s2+l2 <= s1)
3112 		return 0;
3113 	return 1;
3114 }
3115 
3116 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
3117 {
3118 	unsigned long long blocks;
3119 	sector_t new;
3120 
3121 	if (kstrtoull(buf, 10, &blocks) < 0)
3122 		return -EINVAL;
3123 
3124 	if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
3125 		return -EINVAL; /* sector conversion overflow */
3126 
3127 	new = blocks * 2;
3128 	if (new != blocks * 2)
3129 		return -EINVAL; /* unsigned long long to sector_t overflow */
3130 
3131 	*sectors = new;
3132 	return 0;
3133 }
3134 
3135 static ssize_t
3136 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3137 {
3138 	struct mddev *my_mddev = rdev->mddev;
3139 	sector_t oldsectors = rdev->sectors;
3140 	sector_t sectors;
3141 
3142 	if (test_bit(Journal, &rdev->flags))
3143 		return -EBUSY;
3144 	if (strict_blocks_to_sectors(buf, &sectors) < 0)
3145 		return -EINVAL;
3146 	if (rdev->data_offset != rdev->new_data_offset)
3147 		return -EINVAL; /* too confusing */
3148 	if (my_mddev->pers && rdev->raid_disk >= 0) {
3149 		if (my_mddev->persistent) {
3150 			sectors = super_types[my_mddev->major_version].
3151 				rdev_size_change(rdev, sectors);
3152 			if (!sectors)
3153 				return -EBUSY;
3154 		} else if (!sectors)
3155 			sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
3156 				rdev->data_offset;
3157 		if (!my_mddev->pers->resize)
3158 			/* Cannot change size for RAID0 or Linear etc */
3159 			return -EINVAL;
3160 	}
3161 	if (sectors < my_mddev->dev_sectors)
3162 		return -EINVAL; /* component must fit device */
3163 
3164 	rdev->sectors = sectors;
3165 	if (sectors > oldsectors && my_mddev->external) {
3166 		/* Need to check that all other rdevs with the same
3167 		 * ->bdev do not overlap.  'rcu' is sufficient to walk
3168 		 * the rdev lists safely.
3169 		 * This check does not provide a hard guarantee, it
3170 		 * just helps avoid dangerous mistakes.
3171 		 */
3172 		struct mddev *mddev;
3173 		int overlap = 0;
3174 		struct list_head *tmp;
3175 
3176 		rcu_read_lock();
3177 		for_each_mddev(mddev, tmp) {
3178 			struct md_rdev *rdev2;
3179 
3180 			rdev_for_each(rdev2, mddev)
3181 				if (rdev->bdev == rdev2->bdev &&
3182 				    rdev != rdev2 &&
3183 				    overlaps(rdev->data_offset, rdev->sectors,
3184 					     rdev2->data_offset,
3185 					     rdev2->sectors)) {
3186 					overlap = 1;
3187 					break;
3188 				}
3189 			if (overlap) {
3190 				mddev_put(mddev);
3191 				break;
3192 			}
3193 		}
3194 		rcu_read_unlock();
3195 		if (overlap) {
3196 			/* Someone else could have slipped in a size
3197 			 * change here, but doing so is just silly.
3198 			 * We put oldsectors back because we *know* it is
3199 			 * safe, and trust userspace not to race with
3200 			 * itself
3201 			 */
3202 			rdev->sectors = oldsectors;
3203 			return -EBUSY;
3204 		}
3205 	}
3206 	return len;
3207 }
3208 
3209 static struct rdev_sysfs_entry rdev_size =
3210 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3211 
3212 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3213 {
3214 	unsigned long long recovery_start = rdev->recovery_offset;
3215 
3216 	if (test_bit(In_sync, &rdev->flags) ||
3217 	    recovery_start == MaxSector)
3218 		return sprintf(page, "none\n");
3219 
3220 	return sprintf(page, "%llu\n", recovery_start);
3221 }
3222 
3223 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3224 {
3225 	unsigned long long recovery_start;
3226 
3227 	if (cmd_match(buf, "none"))
3228 		recovery_start = MaxSector;
3229 	else if (kstrtoull(buf, 10, &recovery_start))
3230 		return -EINVAL;
3231 
3232 	if (rdev->mddev->pers &&
3233 	    rdev->raid_disk >= 0)
3234 		return -EBUSY;
3235 
3236 	rdev->recovery_offset = recovery_start;
3237 	if (recovery_start == MaxSector)
3238 		set_bit(In_sync, &rdev->flags);
3239 	else
3240 		clear_bit(In_sync, &rdev->flags);
3241 	return len;
3242 }
3243 
3244 static struct rdev_sysfs_entry rdev_recovery_start =
3245 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3246 
3247 /* sysfs access to bad-blocks list.
3248  * We present two files.
3249  * 'bad-blocks' lists sector numbers and lengths of ranges that
3250  *    are recorded as bad.  The list is truncated to fit within
3251  *    the one-page limit of sysfs.
3252  *    Writing "sector length" to this file adds an acknowledged
3253  *    bad block list.
3254  * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
3255  *    been acknowledged.  Writing to this file adds bad blocks
3256  *    without acknowledging them.  This is largely for testing.
3257  */
3258 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3259 {
3260 	return badblocks_show(&rdev->badblocks, page, 0);
3261 }
3262 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3263 {
3264 	int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3265 	/* Maybe that ack was all we needed */
3266 	if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3267 		wake_up(&rdev->blocked_wait);
3268 	return rv;
3269 }
3270 static struct rdev_sysfs_entry rdev_bad_blocks =
3271 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3272 
3273 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3274 {
3275 	return badblocks_show(&rdev->badblocks, page, 1);
3276 }
3277 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3278 {
3279 	return badblocks_store(&rdev->badblocks, page, len, 1);
3280 }
3281 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3282 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3283 
3284 static ssize_t
3285 ppl_sector_show(struct md_rdev *rdev, char *page)
3286 {
3287 	return sprintf(page, "%llu\n", (unsigned long long)rdev->ppl.sector);
3288 }
3289 
3290 static ssize_t
3291 ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len)
3292 {
3293 	unsigned long long sector;
3294 
3295 	if (kstrtoull(buf, 10, &sector) < 0)
3296 		return -EINVAL;
3297 	if (sector != (sector_t)sector)
3298 		return -EINVAL;
3299 
3300 	if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3301 	    rdev->raid_disk >= 0)
3302 		return -EBUSY;
3303 
3304 	if (rdev->mddev->persistent) {
3305 		if (rdev->mddev->major_version == 0)
3306 			return -EINVAL;
3307 		if ((sector > rdev->sb_start &&
3308 		     sector - rdev->sb_start > S16_MAX) ||
3309 		    (sector < rdev->sb_start &&
3310 		     rdev->sb_start - sector > -S16_MIN))
3311 			return -EINVAL;
3312 		rdev->ppl.offset = sector - rdev->sb_start;
3313 	} else if (!rdev->mddev->external) {
3314 		return -EBUSY;
3315 	}
3316 	rdev->ppl.sector = sector;
3317 	return len;
3318 }
3319 
3320 static struct rdev_sysfs_entry rdev_ppl_sector =
3321 __ATTR(ppl_sector, S_IRUGO|S_IWUSR, ppl_sector_show, ppl_sector_store);
3322 
3323 static ssize_t
3324 ppl_size_show(struct md_rdev *rdev, char *page)
3325 {
3326 	return sprintf(page, "%u\n", rdev->ppl.size);
3327 }
3328 
3329 static ssize_t
3330 ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3331 {
3332 	unsigned int size;
3333 
3334 	if (kstrtouint(buf, 10, &size) < 0)
3335 		return -EINVAL;
3336 
3337 	if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3338 	    rdev->raid_disk >= 0)
3339 		return -EBUSY;
3340 
3341 	if (rdev->mddev->persistent) {
3342 		if (rdev->mddev->major_version == 0)
3343 			return -EINVAL;
3344 		if (size > U16_MAX)
3345 			return -EINVAL;
3346 	} else if (!rdev->mddev->external) {
3347 		return -EBUSY;
3348 	}
3349 	rdev->ppl.size = size;
3350 	return len;
3351 }
3352 
3353 static struct rdev_sysfs_entry rdev_ppl_size =
3354 __ATTR(ppl_size, S_IRUGO|S_IWUSR, ppl_size_show, ppl_size_store);
3355 
3356 static struct attribute *rdev_default_attrs[] = {
3357 	&rdev_state.attr,
3358 	&rdev_errors.attr,
3359 	&rdev_slot.attr,
3360 	&rdev_offset.attr,
3361 	&rdev_new_offset.attr,
3362 	&rdev_size.attr,
3363 	&rdev_recovery_start.attr,
3364 	&rdev_bad_blocks.attr,
3365 	&rdev_unack_bad_blocks.attr,
3366 	&rdev_ppl_sector.attr,
3367 	&rdev_ppl_size.attr,
3368 	NULL,
3369 };
3370 static ssize_t
3371 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3372 {
3373 	struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3374 	struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3375 
3376 	if (!entry->show)
3377 		return -EIO;
3378 	if (!rdev->mddev)
3379 		return -EBUSY;
3380 	return entry->show(rdev, page);
3381 }
3382 
3383 static ssize_t
3384 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3385 	      const char *page, size_t length)
3386 {
3387 	struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3388 	struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3389 	ssize_t rv;
3390 	struct mddev *mddev = rdev->mddev;
3391 
3392 	if (!entry->store)
3393 		return -EIO;
3394 	if (!capable(CAP_SYS_ADMIN))
3395 		return -EACCES;
3396 	rv = mddev ? mddev_lock(mddev): -EBUSY;
3397 	if (!rv) {
3398 		if (rdev->mddev == NULL)
3399 			rv = -EBUSY;
3400 		else
3401 			rv = entry->store(rdev, page, length);
3402 		mddev_unlock(mddev);
3403 	}
3404 	return rv;
3405 }
3406 
3407 static void rdev_free(struct kobject *ko)
3408 {
3409 	struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3410 	kfree(rdev);
3411 }
3412 static const struct sysfs_ops rdev_sysfs_ops = {
3413 	.show		= rdev_attr_show,
3414 	.store		= rdev_attr_store,
3415 };
3416 static struct kobj_type rdev_ktype = {
3417 	.release	= rdev_free,
3418 	.sysfs_ops	= &rdev_sysfs_ops,
3419 	.default_attrs	= rdev_default_attrs,
3420 };
3421 
3422 int md_rdev_init(struct md_rdev *rdev)
3423 {
3424 	rdev->desc_nr = -1;
3425 	rdev->saved_raid_disk = -1;
3426 	rdev->raid_disk = -1;
3427 	rdev->flags = 0;
3428 	rdev->data_offset = 0;
3429 	rdev->new_data_offset = 0;
3430 	rdev->sb_events = 0;
3431 	rdev->last_read_error = 0;
3432 	rdev->sb_loaded = 0;
3433 	rdev->bb_page = NULL;
3434 	atomic_set(&rdev->nr_pending, 0);
3435 	atomic_set(&rdev->read_errors, 0);
3436 	atomic_set(&rdev->corrected_errors, 0);
3437 
3438 	INIT_LIST_HEAD(&rdev->same_set);
3439 	init_waitqueue_head(&rdev->blocked_wait);
3440 
3441 	/* Add space to store bad block list.
3442 	 * This reserves the space even on arrays where it cannot
3443 	 * be used - I wonder if that matters
3444 	 */
3445 	return badblocks_init(&rdev->badblocks, 0);
3446 }
3447 EXPORT_SYMBOL_GPL(md_rdev_init);
3448 /*
3449  * Import a device. If 'super_format' >= 0, then sanity check the superblock
3450  *
3451  * mark the device faulty if:
3452  *
3453  *   - the device is nonexistent (zero size)
3454  *   - the device has no valid superblock
3455  *
3456  * a faulty rdev _never_ has rdev->sb set.
3457  */
3458 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3459 {
3460 	char b[BDEVNAME_SIZE];
3461 	int err;
3462 	struct md_rdev *rdev;
3463 	sector_t size;
3464 
3465 	rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3466 	if (!rdev)
3467 		return ERR_PTR(-ENOMEM);
3468 
3469 	err = md_rdev_init(rdev);
3470 	if (err)
3471 		goto abort_free;
3472 	err = alloc_disk_sb(rdev);
3473 	if (err)
3474 		goto abort_free;
3475 
3476 	err = lock_rdev(rdev, newdev, super_format == -2);
3477 	if (err)
3478 		goto abort_free;
3479 
3480 	kobject_init(&rdev->kobj, &rdev_ktype);
3481 
3482 	size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3483 	if (!size) {
3484 		pr_warn("md: %s has zero or unknown size, marking faulty!\n",
3485 			bdevname(rdev->bdev,b));
3486 		err = -EINVAL;
3487 		goto abort_free;
3488 	}
3489 
3490 	if (super_format >= 0) {
3491 		err = super_types[super_format].
3492 			load_super(rdev, NULL, super_minor);
3493 		if (err == -EINVAL) {
3494 			pr_warn("md: %s does not have a valid v%d.%d superblock, not importing!\n",
3495 				bdevname(rdev->bdev,b),
3496 				super_format, super_minor);
3497 			goto abort_free;
3498 		}
3499 		if (err < 0) {
3500 			pr_warn("md: could not read %s's sb, not importing!\n",
3501 				bdevname(rdev->bdev,b));
3502 			goto abort_free;
3503 		}
3504 	}
3505 
3506 	return rdev;
3507 
3508 abort_free:
3509 	if (rdev->bdev)
3510 		unlock_rdev(rdev);
3511 	md_rdev_clear(rdev);
3512 	kfree(rdev);
3513 	return ERR_PTR(err);
3514 }
3515 
3516 /*
3517  * Check a full RAID array for plausibility
3518  */
3519 
3520 static void analyze_sbs(struct mddev *mddev)
3521 {
3522 	int i;
3523 	struct md_rdev *rdev, *freshest, *tmp;
3524 	char b[BDEVNAME_SIZE];
3525 
3526 	freshest = NULL;
3527 	rdev_for_each_safe(rdev, tmp, mddev)
3528 		switch (super_types[mddev->major_version].
3529 			load_super(rdev, freshest, mddev->minor_version)) {
3530 		case 1:
3531 			freshest = rdev;
3532 			break;
3533 		case 0:
3534 			break;
3535 		default:
3536 			pr_warn("md: fatal superblock inconsistency in %s -- removing from array\n",
3537 				bdevname(rdev->bdev,b));
3538 			md_kick_rdev_from_array(rdev);
3539 		}
3540 
3541 	super_types[mddev->major_version].
3542 		validate_super(mddev, freshest);
3543 
3544 	i = 0;
3545 	rdev_for_each_safe(rdev, tmp, mddev) {
3546 		if (mddev->max_disks &&
3547 		    (rdev->desc_nr >= mddev->max_disks ||
3548 		     i > mddev->max_disks)) {
3549 			pr_warn("md: %s: %s: only %d devices permitted\n",
3550 				mdname(mddev), bdevname(rdev->bdev, b),
3551 				mddev->max_disks);
3552 			md_kick_rdev_from_array(rdev);
3553 			continue;
3554 		}
3555 		if (rdev != freshest) {
3556 			if (super_types[mddev->major_version].
3557 			    validate_super(mddev, rdev)) {
3558 				pr_warn("md: kicking non-fresh %s from array!\n",
3559 					bdevname(rdev->bdev,b));
3560 				md_kick_rdev_from_array(rdev);
3561 				continue;
3562 			}
3563 		}
3564 		if (mddev->level == LEVEL_MULTIPATH) {
3565 			rdev->desc_nr = i++;
3566 			rdev->raid_disk = rdev->desc_nr;
3567 			set_bit(In_sync, &rdev->flags);
3568 		} else if (rdev->raid_disk >=
3569 			    (mddev->raid_disks - min(0, mddev->delta_disks)) &&
3570 			   !test_bit(Journal, &rdev->flags)) {
3571 			rdev->raid_disk = -1;
3572 			clear_bit(In_sync, &rdev->flags);
3573 		}
3574 	}
3575 }
3576 
3577 /* Read a fixed-point number.
3578  * Numbers in sysfs attributes should be in "standard" units where
3579  * possible, so time should be in seconds.
3580  * However we internally use a a much smaller unit such as
3581  * milliseconds or jiffies.
3582  * This function takes a decimal number with a possible fractional
3583  * component, and produces an integer which is the result of
3584  * multiplying that number by 10^'scale'.
3585  * all without any floating-point arithmetic.
3586  */
3587 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3588 {
3589 	unsigned long result = 0;
3590 	long decimals = -1;
3591 	while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3592 		if (*cp == '.')
3593 			decimals = 0;
3594 		else if (decimals < scale) {
3595 			unsigned int value;
3596 			value = *cp - '0';
3597 			result = result * 10 + value;
3598 			if (decimals >= 0)
3599 				decimals++;
3600 		}
3601 		cp++;
3602 	}
3603 	if (*cp == '\n')
3604 		cp++;
3605 	if (*cp)
3606 		return -EINVAL;
3607 	if (decimals < 0)
3608 		decimals = 0;
3609 	while (decimals < scale) {
3610 		result *= 10;
3611 		decimals ++;
3612 	}
3613 	*res = result;
3614 	return 0;
3615 }
3616 
3617 static ssize_t
3618 safe_delay_show(struct mddev *mddev, char *page)
3619 {
3620 	int msec = (mddev->safemode_delay*1000)/HZ;
3621 	return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3622 }
3623 static ssize_t
3624 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3625 {
3626 	unsigned long msec;
3627 
3628 	if (mddev_is_clustered(mddev)) {
3629 		pr_warn("md: Safemode is disabled for clustered mode\n");
3630 		return -EINVAL;
3631 	}
3632 
3633 	if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3634 		return -EINVAL;
3635 	if (msec == 0)
3636 		mddev->safemode_delay = 0;
3637 	else {
3638 		unsigned long old_delay = mddev->safemode_delay;
3639 		unsigned long new_delay = (msec*HZ)/1000;
3640 
3641 		if (new_delay == 0)
3642 			new_delay = 1;
3643 		mddev->safemode_delay = new_delay;
3644 		if (new_delay < old_delay || old_delay == 0)
3645 			mod_timer(&mddev->safemode_timer, jiffies+1);
3646 	}
3647 	return len;
3648 }
3649 static struct md_sysfs_entry md_safe_delay =
3650 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3651 
3652 static ssize_t
3653 level_show(struct mddev *mddev, char *page)
3654 {
3655 	struct md_personality *p;
3656 	int ret;
3657 	spin_lock(&mddev->lock);
3658 	p = mddev->pers;
3659 	if (p)
3660 		ret = sprintf(page, "%s\n", p->name);
3661 	else if (mddev->clevel[0])
3662 		ret = sprintf(page, "%s\n", mddev->clevel);
3663 	else if (mddev->level != LEVEL_NONE)
3664 		ret = sprintf(page, "%d\n", mddev->level);
3665 	else
3666 		ret = 0;
3667 	spin_unlock(&mddev->lock);
3668 	return ret;
3669 }
3670 
3671 static ssize_t
3672 level_store(struct mddev *mddev, const char *buf, size_t len)
3673 {
3674 	char clevel[16];
3675 	ssize_t rv;
3676 	size_t slen = len;
3677 	struct md_personality *pers, *oldpers;
3678 	long level;
3679 	void *priv, *oldpriv;
3680 	struct md_rdev *rdev;
3681 
3682 	if (slen == 0 || slen >= sizeof(clevel))
3683 		return -EINVAL;
3684 
3685 	rv = mddev_lock(mddev);
3686 	if (rv)
3687 		return rv;
3688 
3689 	if (mddev->pers == NULL) {
3690 		strncpy(mddev->clevel, buf, slen);
3691 		if (mddev->clevel[slen-1] == '\n')
3692 			slen--;
3693 		mddev->clevel[slen] = 0;
3694 		mddev->level = LEVEL_NONE;
3695 		rv = len;
3696 		goto out_unlock;
3697 	}
3698 	rv = -EROFS;
3699 	if (mddev->ro)
3700 		goto out_unlock;
3701 
3702 	/* request to change the personality.  Need to ensure:
3703 	 *  - array is not engaged in resync/recovery/reshape
3704 	 *  - old personality can be suspended
3705 	 *  - new personality will access other array.
3706 	 */
3707 
3708 	rv = -EBUSY;
3709 	if (mddev->sync_thread ||
3710 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3711 	    mddev->reshape_position != MaxSector ||
3712 	    mddev->sysfs_active)
3713 		goto out_unlock;
3714 
3715 	rv = -EINVAL;
3716 	if (!mddev->pers->quiesce) {
3717 		pr_warn("md: %s: %s does not support online personality change\n",
3718 			mdname(mddev), mddev->pers->name);
3719 		goto out_unlock;
3720 	}
3721 
3722 	/* Now find the new personality */
3723 	strncpy(clevel, buf, slen);
3724 	if (clevel[slen-1] == '\n')
3725 		slen--;
3726 	clevel[slen] = 0;
3727 	if (kstrtol(clevel, 10, &level))
3728 		level = LEVEL_NONE;
3729 
3730 	if (request_module("md-%s", clevel) != 0)
3731 		request_module("md-level-%s", clevel);
3732 	spin_lock(&pers_lock);
3733 	pers = find_pers(level, clevel);
3734 	if (!pers || !try_module_get(pers->owner)) {
3735 		spin_unlock(&pers_lock);
3736 		pr_warn("md: personality %s not loaded\n", clevel);
3737 		rv = -EINVAL;
3738 		goto out_unlock;
3739 	}
3740 	spin_unlock(&pers_lock);
3741 
3742 	if (pers == mddev->pers) {
3743 		/* Nothing to do! */
3744 		module_put(pers->owner);
3745 		rv = len;
3746 		goto out_unlock;
3747 	}
3748 	if (!pers->takeover) {
3749 		module_put(pers->owner);
3750 		pr_warn("md: %s: %s does not support personality takeover\n",
3751 			mdname(mddev), clevel);
3752 		rv = -EINVAL;
3753 		goto out_unlock;
3754 	}
3755 
3756 	rdev_for_each(rdev, mddev)
3757 		rdev->new_raid_disk = rdev->raid_disk;
3758 
3759 	/* ->takeover must set new_* and/or delta_disks
3760 	 * if it succeeds, and may set them when it fails.
3761 	 */
3762 	priv = pers->takeover(mddev);
3763 	if (IS_ERR(priv)) {
3764 		mddev->new_level = mddev->level;
3765 		mddev->new_layout = mddev->layout;
3766 		mddev->new_chunk_sectors = mddev->chunk_sectors;
3767 		mddev->raid_disks -= mddev->delta_disks;
3768 		mddev->delta_disks = 0;
3769 		mddev->reshape_backwards = 0;
3770 		module_put(pers->owner);
3771 		pr_warn("md: %s: %s would not accept array\n",
3772 			mdname(mddev), clevel);
3773 		rv = PTR_ERR(priv);
3774 		goto out_unlock;
3775 	}
3776 
3777 	/* Looks like we have a winner */
3778 	mddev_suspend(mddev);
3779 	mddev_detach(mddev);
3780 
3781 	spin_lock(&mddev->lock);
3782 	oldpers = mddev->pers;
3783 	oldpriv = mddev->private;
3784 	mddev->pers = pers;
3785 	mddev->private = priv;
3786 	strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3787 	mddev->level = mddev->new_level;
3788 	mddev->layout = mddev->new_layout;
3789 	mddev->chunk_sectors = mddev->new_chunk_sectors;
3790 	mddev->delta_disks = 0;
3791 	mddev->reshape_backwards = 0;
3792 	mddev->degraded = 0;
3793 	spin_unlock(&mddev->lock);
3794 
3795 	if (oldpers->sync_request == NULL &&
3796 	    mddev->external) {
3797 		/* We are converting from a no-redundancy array
3798 		 * to a redundancy array and metadata is managed
3799 		 * externally so we need to be sure that writes
3800 		 * won't block due to a need to transition
3801 		 *      clean->dirty
3802 		 * until external management is started.
3803 		 */
3804 		mddev->in_sync = 0;
3805 		mddev->safemode_delay = 0;
3806 		mddev->safemode = 0;
3807 	}
3808 
3809 	oldpers->free(mddev, oldpriv);
3810 
3811 	if (oldpers->sync_request == NULL &&
3812 	    pers->sync_request != NULL) {
3813 		/* need to add the md_redundancy_group */
3814 		if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3815 			pr_warn("md: cannot register extra attributes for %s\n",
3816 				mdname(mddev));
3817 		mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
3818 	}
3819 	if (oldpers->sync_request != NULL &&
3820 	    pers->sync_request == NULL) {
3821 		/* need to remove the md_redundancy_group */
3822 		if (mddev->to_remove == NULL)
3823 			mddev->to_remove = &md_redundancy_group;
3824 	}
3825 
3826 	module_put(oldpers->owner);
3827 
3828 	rdev_for_each(rdev, mddev) {
3829 		if (rdev->raid_disk < 0)
3830 			continue;
3831 		if (rdev->new_raid_disk >= mddev->raid_disks)
3832 			rdev->new_raid_disk = -1;
3833 		if (rdev->new_raid_disk == rdev->raid_disk)
3834 			continue;
3835 		sysfs_unlink_rdev(mddev, rdev);
3836 	}
3837 	rdev_for_each(rdev, mddev) {
3838 		if (rdev->raid_disk < 0)
3839 			continue;
3840 		if (rdev->new_raid_disk == rdev->raid_disk)
3841 			continue;
3842 		rdev->raid_disk = rdev->new_raid_disk;
3843 		if (rdev->raid_disk < 0)
3844 			clear_bit(In_sync, &rdev->flags);
3845 		else {
3846 			if (sysfs_link_rdev(mddev, rdev))
3847 				pr_warn("md: cannot register rd%d for %s after level change\n",
3848 					rdev->raid_disk, mdname(mddev));
3849 		}
3850 	}
3851 
3852 	if (pers->sync_request == NULL) {
3853 		/* this is now an array without redundancy, so
3854 		 * it must always be in_sync
3855 		 */
3856 		mddev->in_sync = 1;
3857 		del_timer_sync(&mddev->safemode_timer);
3858 	}
3859 	blk_set_stacking_limits(&mddev->queue->limits);
3860 	pers->run(mddev);
3861 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
3862 	mddev_resume(mddev);
3863 	if (!mddev->thread)
3864 		md_update_sb(mddev, 1);
3865 	sysfs_notify(&mddev->kobj, NULL, "level");
3866 	md_new_event(mddev);
3867 	rv = len;
3868 out_unlock:
3869 	mddev_unlock(mddev);
3870 	return rv;
3871 }
3872 
3873 static struct md_sysfs_entry md_level =
3874 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3875 
3876 static ssize_t
3877 layout_show(struct mddev *mddev, char *page)
3878 {
3879 	/* just a number, not meaningful for all levels */
3880 	if (mddev->reshape_position != MaxSector &&
3881 	    mddev->layout != mddev->new_layout)
3882 		return sprintf(page, "%d (%d)\n",
3883 			       mddev->new_layout, mddev->layout);
3884 	return sprintf(page, "%d\n", mddev->layout);
3885 }
3886 
3887 static ssize_t
3888 layout_store(struct mddev *mddev, const char *buf, size_t len)
3889 {
3890 	unsigned int n;
3891 	int err;
3892 
3893 	err = kstrtouint(buf, 10, &n);
3894 	if (err < 0)
3895 		return err;
3896 	err = mddev_lock(mddev);
3897 	if (err)
3898 		return err;
3899 
3900 	if (mddev->pers) {
3901 		if (mddev->pers->check_reshape == NULL)
3902 			err = -EBUSY;
3903 		else if (mddev->ro)
3904 			err = -EROFS;
3905 		else {
3906 			mddev->new_layout = n;
3907 			err = mddev->pers->check_reshape(mddev);
3908 			if (err)
3909 				mddev->new_layout = mddev->layout;
3910 		}
3911 	} else {
3912 		mddev->new_layout = n;
3913 		if (mddev->reshape_position == MaxSector)
3914 			mddev->layout = n;
3915 	}
3916 	mddev_unlock(mddev);
3917 	return err ?: len;
3918 }
3919 static struct md_sysfs_entry md_layout =
3920 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3921 
3922 static ssize_t
3923 raid_disks_show(struct mddev *mddev, char *page)
3924 {
3925 	if (mddev->raid_disks == 0)
3926 		return 0;
3927 	if (mddev->reshape_position != MaxSector &&
3928 	    mddev->delta_disks != 0)
3929 		return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3930 			       mddev->raid_disks - mddev->delta_disks);
3931 	return sprintf(page, "%d\n", mddev->raid_disks);
3932 }
3933 
3934 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3935 
3936 static ssize_t
3937 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3938 {
3939 	unsigned int n;
3940 	int err;
3941 
3942 	err = kstrtouint(buf, 10, &n);
3943 	if (err < 0)
3944 		return err;
3945 
3946 	err = mddev_lock(mddev);
3947 	if (err)
3948 		return err;
3949 	if (mddev->pers)
3950 		err = update_raid_disks(mddev, n);
3951 	else if (mddev->reshape_position != MaxSector) {
3952 		struct md_rdev *rdev;
3953 		int olddisks = mddev->raid_disks - mddev->delta_disks;
3954 
3955 		err = -EINVAL;
3956 		rdev_for_each(rdev, mddev) {
3957 			if (olddisks < n &&
3958 			    rdev->data_offset < rdev->new_data_offset)
3959 				goto out_unlock;
3960 			if (olddisks > n &&
3961 			    rdev->data_offset > rdev->new_data_offset)
3962 				goto out_unlock;
3963 		}
3964 		err = 0;
3965 		mddev->delta_disks = n - olddisks;
3966 		mddev->raid_disks = n;
3967 		mddev->reshape_backwards = (mddev->delta_disks < 0);
3968 	} else
3969 		mddev->raid_disks = n;
3970 out_unlock:
3971 	mddev_unlock(mddev);
3972 	return err ? err : len;
3973 }
3974 static struct md_sysfs_entry md_raid_disks =
3975 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3976 
3977 static ssize_t
3978 chunk_size_show(struct mddev *mddev, char *page)
3979 {
3980 	if (mddev->reshape_position != MaxSector &&
3981 	    mddev->chunk_sectors != mddev->new_chunk_sectors)
3982 		return sprintf(page, "%d (%d)\n",
3983 			       mddev->new_chunk_sectors << 9,
3984 			       mddev->chunk_sectors << 9);
3985 	return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3986 }
3987 
3988 static ssize_t
3989 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3990 {
3991 	unsigned long n;
3992 	int err;
3993 
3994 	err = kstrtoul(buf, 10, &n);
3995 	if (err < 0)
3996 		return err;
3997 
3998 	err = mddev_lock(mddev);
3999 	if (err)
4000 		return err;
4001 	if (mddev->pers) {
4002 		if (mddev->pers->check_reshape == NULL)
4003 			err = -EBUSY;
4004 		else if (mddev->ro)
4005 			err = -EROFS;
4006 		else {
4007 			mddev->new_chunk_sectors = n >> 9;
4008 			err = mddev->pers->check_reshape(mddev);
4009 			if (err)
4010 				mddev->new_chunk_sectors = mddev->chunk_sectors;
4011 		}
4012 	} else {
4013 		mddev->new_chunk_sectors = n >> 9;
4014 		if (mddev->reshape_position == MaxSector)
4015 			mddev->chunk_sectors = n >> 9;
4016 	}
4017 	mddev_unlock(mddev);
4018 	return err ?: len;
4019 }
4020 static struct md_sysfs_entry md_chunk_size =
4021 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
4022 
4023 static ssize_t
4024 resync_start_show(struct mddev *mddev, char *page)
4025 {
4026 	if (mddev->recovery_cp == MaxSector)
4027 		return sprintf(page, "none\n");
4028 	return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
4029 }
4030 
4031 static ssize_t
4032 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
4033 {
4034 	unsigned long long n;
4035 	int err;
4036 
4037 	if (cmd_match(buf, "none"))
4038 		n = MaxSector;
4039 	else {
4040 		err = kstrtoull(buf, 10, &n);
4041 		if (err < 0)
4042 			return err;
4043 		if (n != (sector_t)n)
4044 			return -EINVAL;
4045 	}
4046 
4047 	err = mddev_lock(mddev);
4048 	if (err)
4049 		return err;
4050 	if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4051 		err = -EBUSY;
4052 
4053 	if (!err) {
4054 		mddev->recovery_cp = n;
4055 		if (mddev->pers)
4056 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
4057 	}
4058 	mddev_unlock(mddev);
4059 	return err ?: len;
4060 }
4061 static struct md_sysfs_entry md_resync_start =
4062 __ATTR_PREALLOC(resync_start, S_IRUGO|S_IWUSR,
4063 		resync_start_show, resync_start_store);
4064 
4065 /*
4066  * The array state can be:
4067  *
4068  * clear
4069  *     No devices, no size, no level
4070  *     Equivalent to STOP_ARRAY ioctl
4071  * inactive
4072  *     May have some settings, but array is not active
4073  *        all IO results in error
4074  *     When written, doesn't tear down array, but just stops it
4075  * suspended (not supported yet)
4076  *     All IO requests will block. The array can be reconfigured.
4077  *     Writing this, if accepted, will block until array is quiescent
4078  * readonly
4079  *     no resync can happen.  no superblocks get written.
4080  *     write requests fail
4081  * read-auto
4082  *     like readonly, but behaves like 'clean' on a write request.
4083  *
4084  * clean - no pending writes, but otherwise active.
4085  *     When written to inactive array, starts without resync
4086  *     If a write request arrives then
4087  *       if metadata is known, mark 'dirty' and switch to 'active'.
4088  *       if not known, block and switch to write-pending
4089  *     If written to an active array that has pending writes, then fails.
4090  * active
4091  *     fully active: IO and resync can be happening.
4092  *     When written to inactive array, starts with resync
4093  *
4094  * write-pending
4095  *     clean, but writes are blocked waiting for 'active' to be written.
4096  *
4097  * active-idle
4098  *     like active, but no writes have been seen for a while (100msec).
4099  *
4100  */
4101 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
4102 		   write_pending, active_idle, bad_word};
4103 static char *array_states[] = {
4104 	"clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
4105 	"write-pending", "active-idle", NULL };
4106 
4107 static int match_word(const char *word, char **list)
4108 {
4109 	int n;
4110 	for (n=0; list[n]; n++)
4111 		if (cmd_match(word, list[n]))
4112 			break;
4113 	return n;
4114 }
4115 
4116 static ssize_t
4117 array_state_show(struct mddev *mddev, char *page)
4118 {
4119 	enum array_state st = inactive;
4120 
4121 	if (mddev->pers)
4122 		switch(mddev->ro) {
4123 		case 1:
4124 			st = readonly;
4125 			break;
4126 		case 2:
4127 			st = read_auto;
4128 			break;
4129 		case 0:
4130 			spin_lock(&mddev->lock);
4131 			if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
4132 				st = write_pending;
4133 			else if (mddev->in_sync)
4134 				st = clean;
4135 			else if (mddev->safemode)
4136 				st = active_idle;
4137 			else
4138 				st = active;
4139 			spin_unlock(&mddev->lock);
4140 		}
4141 	else {
4142 		if (list_empty(&mddev->disks) &&
4143 		    mddev->raid_disks == 0 &&
4144 		    mddev->dev_sectors == 0)
4145 			st = clear;
4146 		else
4147 			st = inactive;
4148 	}
4149 	return sprintf(page, "%s\n", array_states[st]);
4150 }
4151 
4152 static int do_md_stop(struct mddev *mddev, int ro, struct block_device *bdev);
4153 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev);
4154 static int do_md_run(struct mddev *mddev);
4155 static int restart_array(struct mddev *mddev);
4156 
4157 static ssize_t
4158 array_state_store(struct mddev *mddev, const char *buf, size_t len)
4159 {
4160 	int err = 0;
4161 	enum array_state st = match_word(buf, array_states);
4162 
4163 	if (mddev->pers && (st == active || st == clean) && mddev->ro != 1) {
4164 		/* don't take reconfig_mutex when toggling between
4165 		 * clean and active
4166 		 */
4167 		spin_lock(&mddev->lock);
4168 		if (st == active) {
4169 			restart_array(mddev);
4170 			clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4171 			md_wakeup_thread(mddev->thread);
4172 			wake_up(&mddev->sb_wait);
4173 		} else /* st == clean */ {
4174 			restart_array(mddev);
4175 			if (!set_in_sync(mddev))
4176 				err = -EBUSY;
4177 		}
4178 		if (!err)
4179 			sysfs_notify_dirent_safe(mddev->sysfs_state);
4180 		spin_unlock(&mddev->lock);
4181 		return err ?: len;
4182 	}
4183 	err = mddev_lock(mddev);
4184 	if (err)
4185 		return err;
4186 	err = -EINVAL;
4187 	switch(st) {
4188 	case bad_word:
4189 		break;
4190 	case clear:
4191 		/* stopping an active array */
4192 		err = do_md_stop(mddev, 0, NULL);
4193 		break;
4194 	case inactive:
4195 		/* stopping an active array */
4196 		if (mddev->pers)
4197 			err = do_md_stop(mddev, 2, NULL);
4198 		else
4199 			err = 0; /* already inactive */
4200 		break;
4201 	case suspended:
4202 		break; /* not supported yet */
4203 	case readonly:
4204 		if (mddev->pers)
4205 			err = md_set_readonly(mddev, NULL);
4206 		else {
4207 			mddev->ro = 1;
4208 			set_disk_ro(mddev->gendisk, 1);
4209 			err = do_md_run(mddev);
4210 		}
4211 		break;
4212 	case read_auto:
4213 		if (mddev->pers) {
4214 			if (mddev->ro == 0)
4215 				err = md_set_readonly(mddev, NULL);
4216 			else if (mddev->ro == 1)
4217 				err = restart_array(mddev);
4218 			if (err == 0) {
4219 				mddev->ro = 2;
4220 				set_disk_ro(mddev->gendisk, 0);
4221 			}
4222 		} else {
4223 			mddev->ro = 2;
4224 			err = do_md_run(mddev);
4225 		}
4226 		break;
4227 	case clean:
4228 		if (mddev->pers) {
4229 			err = restart_array(mddev);
4230 			if (err)
4231 				break;
4232 			spin_lock(&mddev->lock);
4233 			if (!set_in_sync(mddev))
4234 				err = -EBUSY;
4235 			spin_unlock(&mddev->lock);
4236 		} else
4237 			err = -EINVAL;
4238 		break;
4239 	case active:
4240 		if (mddev->pers) {
4241 			err = restart_array(mddev);
4242 			if (err)
4243 				break;
4244 			clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4245 			wake_up(&mddev->sb_wait);
4246 			err = 0;
4247 		} else {
4248 			mddev->ro = 0;
4249 			set_disk_ro(mddev->gendisk, 0);
4250 			err = do_md_run(mddev);
4251 		}
4252 		break;
4253 	case write_pending:
4254 	case active_idle:
4255 		/* these cannot be set */
4256 		break;
4257 	}
4258 
4259 	if (!err) {
4260 		if (mddev->hold_active == UNTIL_IOCTL)
4261 			mddev->hold_active = 0;
4262 		sysfs_notify_dirent_safe(mddev->sysfs_state);
4263 	}
4264 	mddev_unlock(mddev);
4265 	return err ?: len;
4266 }
4267 static struct md_sysfs_entry md_array_state =
4268 __ATTR_PREALLOC(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
4269 
4270 static ssize_t
4271 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
4272 	return sprintf(page, "%d\n",
4273 		       atomic_read(&mddev->max_corr_read_errors));
4274 }
4275 
4276 static ssize_t
4277 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
4278 {
4279 	unsigned int n;
4280 	int rv;
4281 
4282 	rv = kstrtouint(buf, 10, &n);
4283 	if (rv < 0)
4284 		return rv;
4285 	atomic_set(&mddev->max_corr_read_errors, n);
4286 	return len;
4287 }
4288 
4289 static struct md_sysfs_entry max_corr_read_errors =
4290 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
4291 	max_corrected_read_errors_store);
4292 
4293 static ssize_t
4294 null_show(struct mddev *mddev, char *page)
4295 {
4296 	return -EINVAL;
4297 }
4298 
4299 static ssize_t
4300 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
4301 {
4302 	/* buf must be %d:%d\n? giving major and minor numbers */
4303 	/* The new device is added to the array.
4304 	 * If the array has a persistent superblock, we read the
4305 	 * superblock to initialise info and check validity.
4306 	 * Otherwise, only checking done is that in bind_rdev_to_array,
4307 	 * which mainly checks size.
4308 	 */
4309 	char *e;
4310 	int major = simple_strtoul(buf, &e, 10);
4311 	int minor;
4312 	dev_t dev;
4313 	struct md_rdev *rdev;
4314 	int err;
4315 
4316 	if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
4317 		return -EINVAL;
4318 	minor = simple_strtoul(e+1, &e, 10);
4319 	if (*e && *e != '\n')
4320 		return -EINVAL;
4321 	dev = MKDEV(major, minor);
4322 	if (major != MAJOR(dev) ||
4323 	    minor != MINOR(dev))
4324 		return -EOVERFLOW;
4325 
4326 	flush_workqueue(md_misc_wq);
4327 
4328 	err = mddev_lock(mddev);
4329 	if (err)
4330 		return err;
4331 	if (mddev->persistent) {
4332 		rdev = md_import_device(dev, mddev->major_version,
4333 					mddev->minor_version);
4334 		if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
4335 			struct md_rdev *rdev0
4336 				= list_entry(mddev->disks.next,
4337 					     struct md_rdev, same_set);
4338 			err = super_types[mddev->major_version]
4339 				.load_super(rdev, rdev0, mddev->minor_version);
4340 			if (err < 0)
4341 				goto out;
4342 		}
4343 	} else if (mddev->external)
4344 		rdev = md_import_device(dev, -2, -1);
4345 	else
4346 		rdev = md_import_device(dev, -1, -1);
4347 
4348 	if (IS_ERR(rdev)) {
4349 		mddev_unlock(mddev);
4350 		return PTR_ERR(rdev);
4351 	}
4352 	err = bind_rdev_to_array(rdev, mddev);
4353  out:
4354 	if (err)
4355 		export_rdev(rdev);
4356 	mddev_unlock(mddev);
4357 	if (!err)
4358 		md_new_event(mddev);
4359 	return err ? err : len;
4360 }
4361 
4362 static struct md_sysfs_entry md_new_device =
4363 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4364 
4365 static ssize_t
4366 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4367 {
4368 	char *end;
4369 	unsigned long chunk, end_chunk;
4370 	int err;
4371 
4372 	err = mddev_lock(mddev);
4373 	if (err)
4374 		return err;
4375 	if (!mddev->bitmap)
4376 		goto out;
4377 	/* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4378 	while (*buf) {
4379 		chunk = end_chunk = simple_strtoul(buf, &end, 0);
4380 		if (buf == end) break;
4381 		if (*end == '-') { /* range */
4382 			buf = end + 1;
4383 			end_chunk = simple_strtoul(buf, &end, 0);
4384 			if (buf == end) break;
4385 		}
4386 		if (*end && !isspace(*end)) break;
4387 		bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4388 		buf = skip_spaces(end);
4389 	}
4390 	bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4391 out:
4392 	mddev_unlock(mddev);
4393 	return len;
4394 }
4395 
4396 static struct md_sysfs_entry md_bitmap =
4397 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4398 
4399 static ssize_t
4400 size_show(struct mddev *mddev, char *page)
4401 {
4402 	return sprintf(page, "%llu\n",
4403 		(unsigned long long)mddev->dev_sectors / 2);
4404 }
4405 
4406 static int update_size(struct mddev *mddev, sector_t num_sectors);
4407 
4408 static ssize_t
4409 size_store(struct mddev *mddev, const char *buf, size_t len)
4410 {
4411 	/* If array is inactive, we can reduce the component size, but
4412 	 * not increase it (except from 0).
4413 	 * If array is active, we can try an on-line resize
4414 	 */
4415 	sector_t sectors;
4416 	int err = strict_blocks_to_sectors(buf, &sectors);
4417 
4418 	if (err < 0)
4419 		return err;
4420 	err = mddev_lock(mddev);
4421 	if (err)
4422 		return err;
4423 	if (mddev->pers) {
4424 		err = update_size(mddev, sectors);
4425 		if (err == 0)
4426 			md_update_sb(mddev, 1);
4427 	} else {
4428 		if (mddev->dev_sectors == 0 ||
4429 		    mddev->dev_sectors > sectors)
4430 			mddev->dev_sectors = sectors;
4431 		else
4432 			err = -ENOSPC;
4433 	}
4434 	mddev_unlock(mddev);
4435 	return err ? err : len;
4436 }
4437 
4438 static struct md_sysfs_entry md_size =
4439 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4440 
4441 /* Metadata version.
4442  * This is one of
4443  *   'none' for arrays with no metadata (good luck...)
4444  *   'external' for arrays with externally managed metadata,
4445  * or N.M for internally known formats
4446  */
4447 static ssize_t
4448 metadata_show(struct mddev *mddev, char *page)
4449 {
4450 	if (mddev->persistent)
4451 		return sprintf(page, "%d.%d\n",
4452 			       mddev->major_version, mddev->minor_version);
4453 	else if (mddev->external)
4454 		return sprintf(page, "external:%s\n", mddev->metadata_type);
4455 	else
4456 		return sprintf(page, "none\n");
4457 }
4458 
4459 static ssize_t
4460 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4461 {
4462 	int major, minor;
4463 	char *e;
4464 	int err;
4465 	/* Changing the details of 'external' metadata is
4466 	 * always permitted.  Otherwise there must be
4467 	 * no devices attached to the array.
4468 	 */
4469 
4470 	err = mddev_lock(mddev);
4471 	if (err)
4472 		return err;
4473 	err = -EBUSY;
4474 	if (mddev->external && strncmp(buf, "external:", 9) == 0)
4475 		;
4476 	else if (!list_empty(&mddev->disks))
4477 		goto out_unlock;
4478 
4479 	err = 0;
4480 	if (cmd_match(buf, "none")) {
4481 		mddev->persistent = 0;
4482 		mddev->external = 0;
4483 		mddev->major_version = 0;
4484 		mddev->minor_version = 90;
4485 		goto out_unlock;
4486 	}
4487 	if (strncmp(buf, "external:", 9) == 0) {
4488 		size_t namelen = len-9;
4489 		if (namelen >= sizeof(mddev->metadata_type))
4490 			namelen = sizeof(mddev->metadata_type)-1;
4491 		strncpy(mddev->metadata_type, buf+9, namelen);
4492 		mddev->metadata_type[namelen] = 0;
4493 		if (namelen && mddev->metadata_type[namelen-1] == '\n')
4494 			mddev->metadata_type[--namelen] = 0;
4495 		mddev->persistent = 0;
4496 		mddev->external = 1;
4497 		mddev->major_version = 0;
4498 		mddev->minor_version = 90;
4499 		goto out_unlock;
4500 	}
4501 	major = simple_strtoul(buf, &e, 10);
4502 	err = -EINVAL;
4503 	if (e==buf || *e != '.')
4504 		goto out_unlock;
4505 	buf = e+1;
4506 	minor = simple_strtoul(buf, &e, 10);
4507 	if (e==buf || (*e && *e != '\n') )
4508 		goto out_unlock;
4509 	err = -ENOENT;
4510 	if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4511 		goto out_unlock;
4512 	mddev->major_version = major;
4513 	mddev->minor_version = minor;
4514 	mddev->persistent = 1;
4515 	mddev->external = 0;
4516 	err = 0;
4517 out_unlock:
4518 	mddev_unlock(mddev);
4519 	return err ?: len;
4520 }
4521 
4522 static struct md_sysfs_entry md_metadata =
4523 __ATTR_PREALLOC(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4524 
4525 static ssize_t
4526 action_show(struct mddev *mddev, char *page)
4527 {
4528 	char *type = "idle";
4529 	unsigned long recovery = mddev->recovery;
4530 	if (test_bit(MD_RECOVERY_FROZEN, &recovery))
4531 		type = "frozen";
4532 	else if (test_bit(MD_RECOVERY_RUNNING, &recovery) ||
4533 	    (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &recovery))) {
4534 		if (test_bit(MD_RECOVERY_RESHAPE, &recovery))
4535 			type = "reshape";
4536 		else if (test_bit(MD_RECOVERY_SYNC, &recovery)) {
4537 			if (!test_bit(MD_RECOVERY_REQUESTED, &recovery))
4538 				type = "resync";
4539 			else if (test_bit(MD_RECOVERY_CHECK, &recovery))
4540 				type = "check";
4541 			else
4542 				type = "repair";
4543 		} else if (test_bit(MD_RECOVERY_RECOVER, &recovery))
4544 			type = "recover";
4545 		else if (mddev->reshape_position != MaxSector)
4546 			type = "reshape";
4547 	}
4548 	return sprintf(page, "%s\n", type);
4549 }
4550 
4551 static ssize_t
4552 action_store(struct mddev *mddev, const char *page, size_t len)
4553 {
4554 	if (!mddev->pers || !mddev->pers->sync_request)
4555 		return -EINVAL;
4556 
4557 
4558 	if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4559 		if (cmd_match(page, "frozen"))
4560 			set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4561 		else
4562 			clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4563 		if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4564 		    mddev_lock(mddev) == 0) {
4565 			flush_workqueue(md_misc_wq);
4566 			if (mddev->sync_thread) {
4567 				set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4568 				md_reap_sync_thread(mddev);
4569 			}
4570 			mddev_unlock(mddev);
4571 		}
4572 	} else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4573 		return -EBUSY;
4574 	else if (cmd_match(page, "resync"))
4575 		clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4576 	else if (cmd_match(page, "recover")) {
4577 		clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4578 		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4579 	} else if (cmd_match(page, "reshape")) {
4580 		int err;
4581 		if (mddev->pers->start_reshape == NULL)
4582 			return -EINVAL;
4583 		err = mddev_lock(mddev);
4584 		if (!err) {
4585 			if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4586 				err =  -EBUSY;
4587 			else {
4588 				clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4589 				err = mddev->pers->start_reshape(mddev);
4590 			}
4591 			mddev_unlock(mddev);
4592 		}
4593 		if (err)
4594 			return err;
4595 		sysfs_notify(&mddev->kobj, NULL, "degraded");
4596 	} else {
4597 		if (cmd_match(page, "check"))
4598 			set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4599 		else if (!cmd_match(page, "repair"))
4600 			return -EINVAL;
4601 		clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4602 		set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4603 		set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4604 	}
4605 	if (mddev->ro == 2) {
4606 		/* A write to sync_action is enough to justify
4607 		 * canceling read-auto mode
4608 		 */
4609 		mddev->ro = 0;
4610 		md_wakeup_thread(mddev->sync_thread);
4611 	}
4612 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4613 	md_wakeup_thread(mddev->thread);
4614 	sysfs_notify_dirent_safe(mddev->sysfs_action);
4615 	return len;
4616 }
4617 
4618 static struct md_sysfs_entry md_scan_mode =
4619 __ATTR_PREALLOC(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4620 
4621 static ssize_t
4622 last_sync_action_show(struct mddev *mddev, char *page)
4623 {
4624 	return sprintf(page, "%s\n", mddev->last_sync_action);
4625 }
4626 
4627 static struct md_sysfs_entry md_last_scan_mode = __ATTR_RO(last_sync_action);
4628 
4629 static ssize_t
4630 mismatch_cnt_show(struct mddev *mddev, char *page)
4631 {
4632 	return sprintf(page, "%llu\n",
4633 		       (unsigned long long)
4634 		       atomic64_read(&mddev->resync_mismatches));
4635 }
4636 
4637 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4638 
4639 static ssize_t
4640 sync_min_show(struct mddev *mddev, char *page)
4641 {
4642 	return sprintf(page, "%d (%s)\n", speed_min(mddev),
4643 		       mddev->sync_speed_min ? "local": "system");
4644 }
4645 
4646 static ssize_t
4647 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4648 {
4649 	unsigned int min;
4650 	int rv;
4651 
4652 	if (strncmp(buf, "system", 6)==0) {
4653 		min = 0;
4654 	} else {
4655 		rv = kstrtouint(buf, 10, &min);
4656 		if (rv < 0)
4657 			return rv;
4658 		if (min == 0)
4659 			return -EINVAL;
4660 	}
4661 	mddev->sync_speed_min = min;
4662 	return len;
4663 }
4664 
4665 static struct md_sysfs_entry md_sync_min =
4666 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4667 
4668 static ssize_t
4669 sync_max_show(struct mddev *mddev, char *page)
4670 {
4671 	return sprintf(page, "%d (%s)\n", speed_max(mddev),
4672 		       mddev->sync_speed_max ? "local": "system");
4673 }
4674 
4675 static ssize_t
4676 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4677 {
4678 	unsigned int max;
4679 	int rv;
4680 
4681 	if (strncmp(buf, "system", 6)==0) {
4682 		max = 0;
4683 	} else {
4684 		rv = kstrtouint(buf, 10, &max);
4685 		if (rv < 0)
4686 			return rv;
4687 		if (max == 0)
4688 			return -EINVAL;
4689 	}
4690 	mddev->sync_speed_max = max;
4691 	return len;
4692 }
4693 
4694 static struct md_sysfs_entry md_sync_max =
4695 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4696 
4697 static ssize_t
4698 degraded_show(struct mddev *mddev, char *page)
4699 {
4700 	return sprintf(page, "%d\n", mddev->degraded);
4701 }
4702 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4703 
4704 static ssize_t
4705 sync_force_parallel_show(struct mddev *mddev, char *page)
4706 {
4707 	return sprintf(page, "%d\n", mddev->parallel_resync);
4708 }
4709 
4710 static ssize_t
4711 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4712 {
4713 	long n;
4714 
4715 	if (kstrtol(buf, 10, &n))
4716 		return -EINVAL;
4717 
4718 	if (n != 0 && n != 1)
4719 		return -EINVAL;
4720 
4721 	mddev->parallel_resync = n;
4722 
4723 	if (mddev->sync_thread)
4724 		wake_up(&resync_wait);
4725 
4726 	return len;
4727 }
4728 
4729 /* force parallel resync, even with shared block devices */
4730 static struct md_sysfs_entry md_sync_force_parallel =
4731 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4732        sync_force_parallel_show, sync_force_parallel_store);
4733 
4734 static ssize_t
4735 sync_speed_show(struct mddev *mddev, char *page)
4736 {
4737 	unsigned long resync, dt, db;
4738 	if (mddev->curr_resync == 0)
4739 		return sprintf(page, "none\n");
4740 	resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4741 	dt = (jiffies - mddev->resync_mark) / HZ;
4742 	if (!dt) dt++;
4743 	db = resync - mddev->resync_mark_cnt;
4744 	return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4745 }
4746 
4747 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4748 
4749 static ssize_t
4750 sync_completed_show(struct mddev *mddev, char *page)
4751 {
4752 	unsigned long long max_sectors, resync;
4753 
4754 	if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4755 		return sprintf(page, "none\n");
4756 
4757 	if (mddev->curr_resync == 1 ||
4758 	    mddev->curr_resync == 2)
4759 		return sprintf(page, "delayed\n");
4760 
4761 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4762 	    test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4763 		max_sectors = mddev->resync_max_sectors;
4764 	else
4765 		max_sectors = mddev->dev_sectors;
4766 
4767 	resync = mddev->curr_resync_completed;
4768 	return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4769 }
4770 
4771 static struct md_sysfs_entry md_sync_completed =
4772 	__ATTR_PREALLOC(sync_completed, S_IRUGO, sync_completed_show, NULL);
4773 
4774 static ssize_t
4775 min_sync_show(struct mddev *mddev, char *page)
4776 {
4777 	return sprintf(page, "%llu\n",
4778 		       (unsigned long long)mddev->resync_min);
4779 }
4780 static ssize_t
4781 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4782 {
4783 	unsigned long long min;
4784 	int err;
4785 
4786 	if (kstrtoull(buf, 10, &min))
4787 		return -EINVAL;
4788 
4789 	spin_lock(&mddev->lock);
4790 	err = -EINVAL;
4791 	if (min > mddev->resync_max)
4792 		goto out_unlock;
4793 
4794 	err = -EBUSY;
4795 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4796 		goto out_unlock;
4797 
4798 	/* Round down to multiple of 4K for safety */
4799 	mddev->resync_min = round_down(min, 8);
4800 	err = 0;
4801 
4802 out_unlock:
4803 	spin_unlock(&mddev->lock);
4804 	return err ?: len;
4805 }
4806 
4807 static struct md_sysfs_entry md_min_sync =
4808 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4809 
4810 static ssize_t
4811 max_sync_show(struct mddev *mddev, char *page)
4812 {
4813 	if (mddev->resync_max == MaxSector)
4814 		return sprintf(page, "max\n");
4815 	else
4816 		return sprintf(page, "%llu\n",
4817 			       (unsigned long long)mddev->resync_max);
4818 }
4819 static ssize_t
4820 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4821 {
4822 	int err;
4823 	spin_lock(&mddev->lock);
4824 	if (strncmp(buf, "max", 3) == 0)
4825 		mddev->resync_max = MaxSector;
4826 	else {
4827 		unsigned long long max;
4828 		int chunk;
4829 
4830 		err = -EINVAL;
4831 		if (kstrtoull(buf, 10, &max))
4832 			goto out_unlock;
4833 		if (max < mddev->resync_min)
4834 			goto out_unlock;
4835 
4836 		err = -EBUSY;
4837 		if (max < mddev->resync_max &&
4838 		    mddev->ro == 0 &&
4839 		    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4840 			goto out_unlock;
4841 
4842 		/* Must be a multiple of chunk_size */
4843 		chunk = mddev->chunk_sectors;
4844 		if (chunk) {
4845 			sector_t temp = max;
4846 
4847 			err = -EINVAL;
4848 			if (sector_div(temp, chunk))
4849 				goto out_unlock;
4850 		}
4851 		mddev->resync_max = max;
4852 	}
4853 	wake_up(&mddev->recovery_wait);
4854 	err = 0;
4855 out_unlock:
4856 	spin_unlock(&mddev->lock);
4857 	return err ?: len;
4858 }
4859 
4860 static struct md_sysfs_entry md_max_sync =
4861 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4862 
4863 static ssize_t
4864 suspend_lo_show(struct mddev *mddev, char *page)
4865 {
4866 	return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4867 }
4868 
4869 static ssize_t
4870 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4871 {
4872 	unsigned long long new;
4873 	int err;
4874 
4875 	err = kstrtoull(buf, 10, &new);
4876 	if (err < 0)
4877 		return err;
4878 	if (new != (sector_t)new)
4879 		return -EINVAL;
4880 
4881 	err = mddev_lock(mddev);
4882 	if (err)
4883 		return err;
4884 	err = -EINVAL;
4885 	if (mddev->pers == NULL ||
4886 	    mddev->pers->quiesce == NULL)
4887 		goto unlock;
4888 	mddev_suspend(mddev);
4889 	mddev->suspend_lo = new;
4890 	mddev_resume(mddev);
4891 
4892 	err = 0;
4893 unlock:
4894 	mddev_unlock(mddev);
4895 	return err ?: len;
4896 }
4897 static struct md_sysfs_entry md_suspend_lo =
4898 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4899 
4900 static ssize_t
4901 suspend_hi_show(struct mddev *mddev, char *page)
4902 {
4903 	return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4904 }
4905 
4906 static ssize_t
4907 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4908 {
4909 	unsigned long long new;
4910 	int err;
4911 
4912 	err = kstrtoull(buf, 10, &new);
4913 	if (err < 0)
4914 		return err;
4915 	if (new != (sector_t)new)
4916 		return -EINVAL;
4917 
4918 	err = mddev_lock(mddev);
4919 	if (err)
4920 		return err;
4921 	err = -EINVAL;
4922 	if (mddev->pers == NULL)
4923 		goto unlock;
4924 
4925 	mddev_suspend(mddev);
4926 	mddev->suspend_hi = new;
4927 	mddev_resume(mddev);
4928 
4929 	err = 0;
4930 unlock:
4931 	mddev_unlock(mddev);
4932 	return err ?: len;
4933 }
4934 static struct md_sysfs_entry md_suspend_hi =
4935 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4936 
4937 static ssize_t
4938 reshape_position_show(struct mddev *mddev, char *page)
4939 {
4940 	if (mddev->reshape_position != MaxSector)
4941 		return sprintf(page, "%llu\n",
4942 			       (unsigned long long)mddev->reshape_position);
4943 	strcpy(page, "none\n");
4944 	return 5;
4945 }
4946 
4947 static ssize_t
4948 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4949 {
4950 	struct md_rdev *rdev;
4951 	unsigned long long new;
4952 	int err;
4953 
4954 	err = kstrtoull(buf, 10, &new);
4955 	if (err < 0)
4956 		return err;
4957 	if (new != (sector_t)new)
4958 		return -EINVAL;
4959 	err = mddev_lock(mddev);
4960 	if (err)
4961 		return err;
4962 	err = -EBUSY;
4963 	if (mddev->pers)
4964 		goto unlock;
4965 	mddev->reshape_position = new;
4966 	mddev->delta_disks = 0;
4967 	mddev->reshape_backwards = 0;
4968 	mddev->new_level = mddev->level;
4969 	mddev->new_layout = mddev->layout;
4970 	mddev->new_chunk_sectors = mddev->chunk_sectors;
4971 	rdev_for_each(rdev, mddev)
4972 		rdev->new_data_offset = rdev->data_offset;
4973 	err = 0;
4974 unlock:
4975 	mddev_unlock(mddev);
4976 	return err ?: len;
4977 }
4978 
4979 static struct md_sysfs_entry md_reshape_position =
4980 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4981        reshape_position_store);
4982 
4983 static ssize_t
4984 reshape_direction_show(struct mddev *mddev, char *page)
4985 {
4986 	return sprintf(page, "%s\n",
4987 		       mddev->reshape_backwards ? "backwards" : "forwards");
4988 }
4989 
4990 static ssize_t
4991 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
4992 {
4993 	int backwards = 0;
4994 	int err;
4995 
4996 	if (cmd_match(buf, "forwards"))
4997 		backwards = 0;
4998 	else if (cmd_match(buf, "backwards"))
4999 		backwards = 1;
5000 	else
5001 		return -EINVAL;
5002 	if (mddev->reshape_backwards == backwards)
5003 		return len;
5004 
5005 	err = mddev_lock(mddev);
5006 	if (err)
5007 		return err;
5008 	/* check if we are allowed to change */
5009 	if (mddev->delta_disks)
5010 		err = -EBUSY;
5011 	else if (mddev->persistent &&
5012 	    mddev->major_version == 0)
5013 		err =  -EINVAL;
5014 	else
5015 		mddev->reshape_backwards = backwards;
5016 	mddev_unlock(mddev);
5017 	return err ?: len;
5018 }
5019 
5020 static struct md_sysfs_entry md_reshape_direction =
5021 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
5022        reshape_direction_store);
5023 
5024 static ssize_t
5025 array_size_show(struct mddev *mddev, char *page)
5026 {
5027 	if (mddev->external_size)
5028 		return sprintf(page, "%llu\n",
5029 			       (unsigned long long)mddev->array_sectors/2);
5030 	else
5031 		return sprintf(page, "default\n");
5032 }
5033 
5034 static ssize_t
5035 array_size_store(struct mddev *mddev, const char *buf, size_t len)
5036 {
5037 	sector_t sectors;
5038 	int err;
5039 
5040 	err = mddev_lock(mddev);
5041 	if (err)
5042 		return err;
5043 
5044 	/* cluster raid doesn't support change array_sectors */
5045 	if (mddev_is_clustered(mddev)) {
5046 		mddev_unlock(mddev);
5047 		return -EINVAL;
5048 	}
5049 
5050 	if (strncmp(buf, "default", 7) == 0) {
5051 		if (mddev->pers)
5052 			sectors = mddev->pers->size(mddev, 0, 0);
5053 		else
5054 			sectors = mddev->array_sectors;
5055 
5056 		mddev->external_size = 0;
5057 	} else {
5058 		if (strict_blocks_to_sectors(buf, &sectors) < 0)
5059 			err = -EINVAL;
5060 		else if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
5061 			err = -E2BIG;
5062 		else
5063 			mddev->external_size = 1;
5064 	}
5065 
5066 	if (!err) {
5067 		mddev->array_sectors = sectors;
5068 		if (mddev->pers) {
5069 			set_capacity(mddev->gendisk, mddev->array_sectors);
5070 			revalidate_disk(mddev->gendisk);
5071 		}
5072 	}
5073 	mddev_unlock(mddev);
5074 	return err ?: len;
5075 }
5076 
5077 static struct md_sysfs_entry md_array_size =
5078 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
5079        array_size_store);
5080 
5081 static ssize_t
5082 consistency_policy_show(struct mddev *mddev, char *page)
5083 {
5084 	int ret;
5085 
5086 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
5087 		ret = sprintf(page, "journal\n");
5088 	} else if (test_bit(MD_HAS_PPL, &mddev->flags)) {
5089 		ret = sprintf(page, "ppl\n");
5090 	} else if (mddev->bitmap) {
5091 		ret = sprintf(page, "bitmap\n");
5092 	} else if (mddev->pers) {
5093 		if (mddev->pers->sync_request)
5094 			ret = sprintf(page, "resync\n");
5095 		else
5096 			ret = sprintf(page, "none\n");
5097 	} else {
5098 		ret = sprintf(page, "unknown\n");
5099 	}
5100 
5101 	return ret;
5102 }
5103 
5104 static ssize_t
5105 consistency_policy_store(struct mddev *mddev, const char *buf, size_t len)
5106 {
5107 	int err = 0;
5108 
5109 	if (mddev->pers) {
5110 		if (mddev->pers->change_consistency_policy)
5111 			err = mddev->pers->change_consistency_policy(mddev, buf);
5112 		else
5113 			err = -EBUSY;
5114 	} else if (mddev->external && strncmp(buf, "ppl", 3) == 0) {
5115 		set_bit(MD_HAS_PPL, &mddev->flags);
5116 	} else {
5117 		err = -EINVAL;
5118 	}
5119 
5120 	return err ? err : len;
5121 }
5122 
5123 static struct md_sysfs_entry md_consistency_policy =
5124 __ATTR(consistency_policy, S_IRUGO | S_IWUSR, consistency_policy_show,
5125        consistency_policy_store);
5126 
5127 static struct attribute *md_default_attrs[] = {
5128 	&md_level.attr,
5129 	&md_layout.attr,
5130 	&md_raid_disks.attr,
5131 	&md_chunk_size.attr,
5132 	&md_size.attr,
5133 	&md_resync_start.attr,
5134 	&md_metadata.attr,
5135 	&md_new_device.attr,
5136 	&md_safe_delay.attr,
5137 	&md_array_state.attr,
5138 	&md_reshape_position.attr,
5139 	&md_reshape_direction.attr,
5140 	&md_array_size.attr,
5141 	&max_corr_read_errors.attr,
5142 	&md_consistency_policy.attr,
5143 	NULL,
5144 };
5145 
5146 static struct attribute *md_redundancy_attrs[] = {
5147 	&md_scan_mode.attr,
5148 	&md_last_scan_mode.attr,
5149 	&md_mismatches.attr,
5150 	&md_sync_min.attr,
5151 	&md_sync_max.attr,
5152 	&md_sync_speed.attr,
5153 	&md_sync_force_parallel.attr,
5154 	&md_sync_completed.attr,
5155 	&md_min_sync.attr,
5156 	&md_max_sync.attr,
5157 	&md_suspend_lo.attr,
5158 	&md_suspend_hi.attr,
5159 	&md_bitmap.attr,
5160 	&md_degraded.attr,
5161 	NULL,
5162 };
5163 static struct attribute_group md_redundancy_group = {
5164 	.name = NULL,
5165 	.attrs = md_redundancy_attrs,
5166 };
5167 
5168 static ssize_t
5169 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
5170 {
5171 	struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5172 	struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5173 	ssize_t rv;
5174 
5175 	if (!entry->show)
5176 		return -EIO;
5177 	spin_lock(&all_mddevs_lock);
5178 	if (list_empty(&mddev->all_mddevs)) {
5179 		spin_unlock(&all_mddevs_lock);
5180 		return -EBUSY;
5181 	}
5182 	mddev_get(mddev);
5183 	spin_unlock(&all_mddevs_lock);
5184 
5185 	rv = entry->show(mddev, page);
5186 	mddev_put(mddev);
5187 	return rv;
5188 }
5189 
5190 static ssize_t
5191 md_attr_store(struct kobject *kobj, struct attribute *attr,
5192 	      const char *page, size_t length)
5193 {
5194 	struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5195 	struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5196 	ssize_t rv;
5197 
5198 	if (!entry->store)
5199 		return -EIO;
5200 	if (!capable(CAP_SYS_ADMIN))
5201 		return -EACCES;
5202 	spin_lock(&all_mddevs_lock);
5203 	if (list_empty(&mddev->all_mddevs)) {
5204 		spin_unlock(&all_mddevs_lock);
5205 		return -EBUSY;
5206 	}
5207 	mddev_get(mddev);
5208 	spin_unlock(&all_mddevs_lock);
5209 	rv = entry->store(mddev, page, length);
5210 	mddev_put(mddev);
5211 	return rv;
5212 }
5213 
5214 static void md_free(struct kobject *ko)
5215 {
5216 	struct mddev *mddev = container_of(ko, struct mddev, kobj);
5217 
5218 	if (mddev->sysfs_state)
5219 		sysfs_put(mddev->sysfs_state);
5220 
5221 	if (mddev->gendisk)
5222 		del_gendisk(mddev->gendisk);
5223 	if (mddev->queue)
5224 		blk_cleanup_queue(mddev->queue);
5225 	if (mddev->gendisk)
5226 		put_disk(mddev->gendisk);
5227 	percpu_ref_exit(&mddev->writes_pending);
5228 
5229 	bioset_exit(&mddev->bio_set);
5230 	bioset_exit(&mddev->sync_set);
5231 	kfree(mddev);
5232 }
5233 
5234 static const struct sysfs_ops md_sysfs_ops = {
5235 	.show	= md_attr_show,
5236 	.store	= md_attr_store,
5237 };
5238 static struct kobj_type md_ktype = {
5239 	.release	= md_free,
5240 	.sysfs_ops	= &md_sysfs_ops,
5241 	.default_attrs	= md_default_attrs,
5242 };
5243 
5244 int mdp_major = 0;
5245 
5246 static void mddev_delayed_delete(struct work_struct *ws)
5247 {
5248 	struct mddev *mddev = container_of(ws, struct mddev, del_work);
5249 
5250 	sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
5251 	kobject_del(&mddev->kobj);
5252 	kobject_put(&mddev->kobj);
5253 }
5254 
5255 static void no_op(struct percpu_ref *r) {}
5256 
5257 int mddev_init_writes_pending(struct mddev *mddev)
5258 {
5259 	if (mddev->writes_pending.percpu_count_ptr)
5260 		return 0;
5261 	if (percpu_ref_init(&mddev->writes_pending, no_op, 0, GFP_KERNEL) < 0)
5262 		return -ENOMEM;
5263 	/* We want to start with the refcount at zero */
5264 	percpu_ref_put(&mddev->writes_pending);
5265 	return 0;
5266 }
5267 EXPORT_SYMBOL_GPL(mddev_init_writes_pending);
5268 
5269 static int md_alloc(dev_t dev, char *name)
5270 {
5271 	/*
5272 	 * If dev is zero, name is the name of a device to allocate with
5273 	 * an arbitrary minor number.  It will be "md_???"
5274 	 * If dev is non-zero it must be a device number with a MAJOR of
5275 	 * MD_MAJOR or mdp_major.  In this case, if "name" is NULL, then
5276 	 * the device is being created by opening a node in /dev.
5277 	 * If "name" is not NULL, the device is being created by
5278 	 * writing to /sys/module/md_mod/parameters/new_array.
5279 	 */
5280 	static DEFINE_MUTEX(disks_mutex);
5281 	struct mddev *mddev = mddev_find(dev);
5282 	struct gendisk *disk;
5283 	int partitioned;
5284 	int shift;
5285 	int unit;
5286 	int error;
5287 
5288 	if (!mddev)
5289 		return -ENODEV;
5290 
5291 	partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
5292 	shift = partitioned ? MdpMinorShift : 0;
5293 	unit = MINOR(mddev->unit) >> shift;
5294 
5295 	/* wait for any previous instance of this device to be
5296 	 * completely removed (mddev_delayed_delete).
5297 	 */
5298 	flush_workqueue(md_misc_wq);
5299 
5300 	mutex_lock(&disks_mutex);
5301 	error = -EEXIST;
5302 	if (mddev->gendisk)
5303 		goto abort;
5304 
5305 	if (name && !dev) {
5306 		/* Need to ensure that 'name' is not a duplicate.
5307 		 */
5308 		struct mddev *mddev2;
5309 		spin_lock(&all_mddevs_lock);
5310 
5311 		list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
5312 			if (mddev2->gendisk &&
5313 			    strcmp(mddev2->gendisk->disk_name, name) == 0) {
5314 				spin_unlock(&all_mddevs_lock);
5315 				goto abort;
5316 			}
5317 		spin_unlock(&all_mddevs_lock);
5318 	}
5319 	if (name && dev)
5320 		/*
5321 		 * Creating /dev/mdNNN via "newarray", so adjust hold_active.
5322 		 */
5323 		mddev->hold_active = UNTIL_STOP;
5324 
5325 	error = -ENOMEM;
5326 	mddev->queue = blk_alloc_queue(GFP_KERNEL);
5327 	if (!mddev->queue)
5328 		goto abort;
5329 	mddev->queue->queuedata = mddev;
5330 
5331 	blk_queue_make_request(mddev->queue, md_make_request);
5332 	blk_set_stacking_limits(&mddev->queue->limits);
5333 
5334 	disk = alloc_disk(1 << shift);
5335 	if (!disk) {
5336 		blk_cleanup_queue(mddev->queue);
5337 		mddev->queue = NULL;
5338 		goto abort;
5339 	}
5340 	disk->major = MAJOR(mddev->unit);
5341 	disk->first_minor = unit << shift;
5342 	if (name)
5343 		strcpy(disk->disk_name, name);
5344 	else if (partitioned)
5345 		sprintf(disk->disk_name, "md_d%d", unit);
5346 	else
5347 		sprintf(disk->disk_name, "md%d", unit);
5348 	disk->fops = &md_fops;
5349 	disk->private_data = mddev;
5350 	disk->queue = mddev->queue;
5351 	blk_queue_write_cache(mddev->queue, true, true);
5352 	/* Allow extended partitions.  This makes the
5353 	 * 'mdp' device redundant, but we can't really
5354 	 * remove it now.
5355 	 */
5356 	disk->flags |= GENHD_FL_EXT_DEVT;
5357 	mddev->gendisk = disk;
5358 	/* As soon as we call add_disk(), another thread could get
5359 	 * through to md_open, so make sure it doesn't get too far
5360 	 */
5361 	mutex_lock(&mddev->open_mutex);
5362 	add_disk(disk);
5363 
5364 	error = kobject_add(&mddev->kobj, &disk_to_dev(disk)->kobj, "%s", "md");
5365 	if (error) {
5366 		/* This isn't possible, but as kobject_init_and_add is marked
5367 		 * __must_check, we must do something with the result
5368 		 */
5369 		pr_debug("md: cannot register %s/md - name in use\n",
5370 			 disk->disk_name);
5371 		error = 0;
5372 	}
5373 	if (mddev->kobj.sd &&
5374 	    sysfs_create_group(&mddev->kobj, &md_bitmap_group))
5375 		pr_debug("pointless warning\n");
5376 	mutex_unlock(&mddev->open_mutex);
5377  abort:
5378 	mutex_unlock(&disks_mutex);
5379 	if (!error && mddev->kobj.sd) {
5380 		kobject_uevent(&mddev->kobj, KOBJ_ADD);
5381 		mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
5382 	}
5383 	mddev_put(mddev);
5384 	return error;
5385 }
5386 
5387 static struct kobject *md_probe(dev_t dev, int *part, void *data)
5388 {
5389 	if (create_on_open)
5390 		md_alloc(dev, NULL);
5391 	return NULL;
5392 }
5393 
5394 static int add_named_array(const char *val, const struct kernel_param *kp)
5395 {
5396 	/*
5397 	 * val must be "md_*" or "mdNNN".
5398 	 * For "md_*" we allocate an array with a large free minor number, and
5399 	 * set the name to val.  val must not already be an active name.
5400 	 * For "mdNNN" we allocate an array with the minor number NNN
5401 	 * which must not already be in use.
5402 	 */
5403 	int len = strlen(val);
5404 	char buf[DISK_NAME_LEN];
5405 	unsigned long devnum;
5406 
5407 	while (len && val[len-1] == '\n')
5408 		len--;
5409 	if (len >= DISK_NAME_LEN)
5410 		return -E2BIG;
5411 	strlcpy(buf, val, len+1);
5412 	if (strncmp(buf, "md_", 3) == 0)
5413 		return md_alloc(0, buf);
5414 	if (strncmp(buf, "md", 2) == 0 &&
5415 	    isdigit(buf[2]) &&
5416 	    kstrtoul(buf+2, 10, &devnum) == 0 &&
5417 	    devnum <= MINORMASK)
5418 		return md_alloc(MKDEV(MD_MAJOR, devnum), NULL);
5419 
5420 	return -EINVAL;
5421 }
5422 
5423 static void md_safemode_timeout(struct timer_list *t)
5424 {
5425 	struct mddev *mddev = from_timer(mddev, t, safemode_timer);
5426 
5427 	mddev->safemode = 1;
5428 	if (mddev->external)
5429 		sysfs_notify_dirent_safe(mddev->sysfs_state);
5430 
5431 	md_wakeup_thread(mddev->thread);
5432 }
5433 
5434 static int start_dirty_degraded;
5435 
5436 int md_run(struct mddev *mddev)
5437 {
5438 	int err;
5439 	struct md_rdev *rdev;
5440 	struct md_personality *pers;
5441 
5442 	if (list_empty(&mddev->disks))
5443 		/* cannot run an array with no devices.. */
5444 		return -EINVAL;
5445 
5446 	if (mddev->pers)
5447 		return -EBUSY;
5448 	/* Cannot run until previous stop completes properly */
5449 	if (mddev->sysfs_active)
5450 		return -EBUSY;
5451 
5452 	/*
5453 	 * Analyze all RAID superblock(s)
5454 	 */
5455 	if (!mddev->raid_disks) {
5456 		if (!mddev->persistent)
5457 			return -EINVAL;
5458 		analyze_sbs(mddev);
5459 	}
5460 
5461 	if (mddev->level != LEVEL_NONE)
5462 		request_module("md-level-%d", mddev->level);
5463 	else if (mddev->clevel[0])
5464 		request_module("md-%s", mddev->clevel);
5465 
5466 	/*
5467 	 * Drop all container device buffers, from now on
5468 	 * the only valid external interface is through the md
5469 	 * device.
5470 	 */
5471 	mddev->has_superblocks = false;
5472 	rdev_for_each(rdev, mddev) {
5473 		if (test_bit(Faulty, &rdev->flags))
5474 			continue;
5475 		sync_blockdev(rdev->bdev);
5476 		invalidate_bdev(rdev->bdev);
5477 		if (mddev->ro != 1 &&
5478 		    (bdev_read_only(rdev->bdev) ||
5479 		     bdev_read_only(rdev->meta_bdev))) {
5480 			mddev->ro = 1;
5481 			if (mddev->gendisk)
5482 				set_disk_ro(mddev->gendisk, 1);
5483 		}
5484 
5485 		if (rdev->sb_page)
5486 			mddev->has_superblocks = true;
5487 
5488 		/* perform some consistency tests on the device.
5489 		 * We don't want the data to overlap the metadata,
5490 		 * Internal Bitmap issues have been handled elsewhere.
5491 		 */
5492 		if (rdev->meta_bdev) {
5493 			/* Nothing to check */;
5494 		} else if (rdev->data_offset < rdev->sb_start) {
5495 			if (mddev->dev_sectors &&
5496 			    rdev->data_offset + mddev->dev_sectors
5497 			    > rdev->sb_start) {
5498 				pr_warn("md: %s: data overlaps metadata\n",
5499 					mdname(mddev));
5500 				return -EINVAL;
5501 			}
5502 		} else {
5503 			if (rdev->sb_start + rdev->sb_size/512
5504 			    > rdev->data_offset) {
5505 				pr_warn("md: %s: metadata overlaps data\n",
5506 					mdname(mddev));
5507 				return -EINVAL;
5508 			}
5509 		}
5510 		sysfs_notify_dirent_safe(rdev->sysfs_state);
5511 	}
5512 
5513 	if (!bioset_initialized(&mddev->bio_set)) {
5514 		err = bioset_init(&mddev->bio_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5515 		if (err)
5516 			return err;
5517 	}
5518 	if (!bioset_initialized(&mddev->sync_set)) {
5519 		err = bioset_init(&mddev->sync_set, BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5520 		if (err)
5521 			return err;
5522 	}
5523 	if (mddev->flush_pool == NULL) {
5524 		mddev->flush_pool = mempool_create(NR_FLUSH_INFOS, flush_info_alloc,
5525 						flush_info_free, mddev);
5526 		if (!mddev->flush_pool) {
5527 			err = -ENOMEM;
5528 			goto abort;
5529 		}
5530 	}
5531 	if (mddev->flush_bio_pool == NULL) {
5532 		mddev->flush_bio_pool = mempool_create(NR_FLUSH_BIOS, flush_bio_alloc,
5533 						flush_bio_free, mddev);
5534 		if (!mddev->flush_bio_pool) {
5535 			err = -ENOMEM;
5536 			goto abort;
5537 		}
5538 	}
5539 
5540 	spin_lock(&pers_lock);
5541 	pers = find_pers(mddev->level, mddev->clevel);
5542 	if (!pers || !try_module_get(pers->owner)) {
5543 		spin_unlock(&pers_lock);
5544 		if (mddev->level != LEVEL_NONE)
5545 			pr_warn("md: personality for level %d is not loaded!\n",
5546 				mddev->level);
5547 		else
5548 			pr_warn("md: personality for level %s is not loaded!\n",
5549 				mddev->clevel);
5550 		return -EINVAL;
5551 	}
5552 	spin_unlock(&pers_lock);
5553 	if (mddev->level != pers->level) {
5554 		mddev->level = pers->level;
5555 		mddev->new_level = pers->level;
5556 	}
5557 	strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5558 
5559 	if (mddev->reshape_position != MaxSector &&
5560 	    pers->start_reshape == NULL) {
5561 		/* This personality cannot handle reshaping... */
5562 		module_put(pers->owner);
5563 		return -EINVAL;
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 = 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 		bitmap_destroy(mddev);
5632 		return err;
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 = bitmap_load(mddev);
5717 	if (err) {
5718 		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 	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 	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 	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 }
5909 
5910 void md_stop(struct mddev *mddev)
5911 {
5912 	/* stop the array and free an attached data structures.
5913 	 * This is called from dm-raid
5914 	 */
5915 	__md_stop(mddev);
5916 	if (mddev->flush_bio_pool) {
5917 		mempool_destroy(mddev->flush_bio_pool);
5918 		mddev->flush_bio_pool = NULL;
5919 	}
5920 	if (mddev->flush_pool) {
5921 		mempool_destroy(mddev->flush_pool);
5922 		mddev->flush_pool = NULL;
5923 	}
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 = bitmap_create(mddev, -1);
6715 			mddev_suspend(mddev);
6716 			if (!IS_ERR(bitmap)) {
6717 				mddev->bitmap = bitmap;
6718 				err = bitmap_load(mddev);
6719 			} else
6720 				err = PTR_ERR(bitmap);
6721 			if (err) {
6722 				bitmap_destroy(mddev);
6723 				fd = -1;
6724 			}
6725 			mddev_resume(mddev);
6726 		} else if (fd < 0) {
6727 			mddev_suspend(mddev);
6728 			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 = bitmap_create(mddev, -1);
7015 			mddev_suspend(mddev);
7016 			if (!IS_ERR(bitmap)) {
7017 				mddev->bitmap = bitmap;
7018 				rv = bitmap_load(mddev);
7019 			} else
7020 				rv = PTR_ERR(bitmap);
7021 			if (rv)
7022 				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 			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 (mddev->recovery_cp < MaxSector) {
7682 			seq_printf(seq, "\tresync=PENDING");
7683 			return 1;
7684 		}
7685 		return 0;
7686 	}
7687 	if (resync < 3) {
7688 		seq_printf(seq, "\tresync=DELAYED");
7689 		return 1;
7690 	}
7691 
7692 	WARN_ON(max_sectors == 0);
7693 	/* Pick 'scale' such that (resync>>scale)*1000 will fit
7694 	 * in a sector_t, and (max_sectors>>scale) will fit in a
7695 	 * u32, as those are the requirements for sector_div.
7696 	 * Thus 'scale' must be at least 10
7697 	 */
7698 	scale = 10;
7699 	if (sizeof(sector_t) > sizeof(unsigned long)) {
7700 		while ( max_sectors/2 > (1ULL<<(scale+32)))
7701 			scale++;
7702 	}
7703 	res = (resync>>scale)*1000;
7704 	sector_div(res, (u32)((max_sectors>>scale)+1));
7705 
7706 	per_milli = res;
7707 	{
7708 		int i, x = per_milli/50, y = 20-x;
7709 		seq_printf(seq, "[");
7710 		for (i = 0; i < x; i++)
7711 			seq_printf(seq, "=");
7712 		seq_printf(seq, ">");
7713 		for (i = 0; i < y; i++)
7714 			seq_printf(seq, ".");
7715 		seq_printf(seq, "] ");
7716 	}
7717 	seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
7718 		   (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
7719 		    "reshape" :
7720 		    (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
7721 		     "check" :
7722 		     (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
7723 		      "resync" : "recovery"))),
7724 		   per_milli/10, per_milli % 10,
7725 		   (unsigned long long) resync/2,
7726 		   (unsigned long long) max_sectors/2);
7727 
7728 	/*
7729 	 * dt: time from mark until now
7730 	 * db: blocks written from mark until now
7731 	 * rt: remaining time
7732 	 *
7733 	 * rt is a sector_t, so could be 32bit or 64bit.
7734 	 * So we divide before multiply in case it is 32bit and close
7735 	 * to the limit.
7736 	 * We scale the divisor (db) by 32 to avoid losing precision
7737 	 * near the end of resync when the number of remaining sectors
7738 	 * is close to 'db'.
7739 	 * We then divide rt by 32 after multiplying by db to compensate.
7740 	 * The '+1' avoids division by zero if db is very small.
7741 	 */
7742 	dt = ((jiffies - mddev->resync_mark) / HZ);
7743 	if (!dt) dt++;
7744 	db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
7745 		- mddev->resync_mark_cnt;
7746 
7747 	rt = max_sectors - resync;    /* number of remaining sectors */
7748 	sector_div(rt, db/32+1);
7749 	rt *= dt;
7750 	rt >>= 5;
7751 
7752 	seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
7753 		   ((unsigned long)rt % 60)/6);
7754 
7755 	seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7756 	return 1;
7757 }
7758 
7759 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7760 {
7761 	struct list_head *tmp;
7762 	loff_t l = *pos;
7763 	struct mddev *mddev;
7764 
7765 	if (l >= 0x10000)
7766 		return NULL;
7767 	if (!l--)
7768 		/* header */
7769 		return (void*)1;
7770 
7771 	spin_lock(&all_mddevs_lock);
7772 	list_for_each(tmp,&all_mddevs)
7773 		if (!l--) {
7774 			mddev = list_entry(tmp, struct mddev, all_mddevs);
7775 			mddev_get(mddev);
7776 			spin_unlock(&all_mddevs_lock);
7777 			return mddev;
7778 		}
7779 	spin_unlock(&all_mddevs_lock);
7780 	if (!l--)
7781 		return (void*)2;/* tail */
7782 	return NULL;
7783 }
7784 
7785 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7786 {
7787 	struct list_head *tmp;
7788 	struct mddev *next_mddev, *mddev = v;
7789 
7790 	++*pos;
7791 	if (v == (void*)2)
7792 		return NULL;
7793 
7794 	spin_lock(&all_mddevs_lock);
7795 	if (v == (void*)1)
7796 		tmp = all_mddevs.next;
7797 	else
7798 		tmp = mddev->all_mddevs.next;
7799 	if (tmp != &all_mddevs)
7800 		next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7801 	else {
7802 		next_mddev = (void*)2;
7803 		*pos = 0x10000;
7804 	}
7805 	spin_unlock(&all_mddevs_lock);
7806 
7807 	if (v != (void*)1)
7808 		mddev_put(mddev);
7809 	return next_mddev;
7810 
7811 }
7812 
7813 static void md_seq_stop(struct seq_file *seq, void *v)
7814 {
7815 	struct mddev *mddev = v;
7816 
7817 	if (mddev && v != (void*)1 && v != (void*)2)
7818 		mddev_put(mddev);
7819 }
7820 
7821 static int md_seq_show(struct seq_file *seq, void *v)
7822 {
7823 	struct mddev *mddev = v;
7824 	sector_t sectors;
7825 	struct md_rdev *rdev;
7826 
7827 	if (v == (void*)1) {
7828 		struct md_personality *pers;
7829 		seq_printf(seq, "Personalities : ");
7830 		spin_lock(&pers_lock);
7831 		list_for_each_entry(pers, &pers_list, list)
7832 			seq_printf(seq, "[%s] ", pers->name);
7833 
7834 		spin_unlock(&pers_lock);
7835 		seq_printf(seq, "\n");
7836 		seq->poll_event = atomic_read(&md_event_count);
7837 		return 0;
7838 	}
7839 	if (v == (void*)2) {
7840 		status_unused(seq);
7841 		return 0;
7842 	}
7843 
7844 	spin_lock(&mddev->lock);
7845 	if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7846 		seq_printf(seq, "%s : %sactive", mdname(mddev),
7847 						mddev->pers ? "" : "in");
7848 		if (mddev->pers) {
7849 			if (mddev->ro==1)
7850 				seq_printf(seq, " (read-only)");
7851 			if (mddev->ro==2)
7852 				seq_printf(seq, " (auto-read-only)");
7853 			seq_printf(seq, " %s", mddev->pers->name);
7854 		}
7855 
7856 		sectors = 0;
7857 		rcu_read_lock();
7858 		rdev_for_each_rcu(rdev, mddev) {
7859 			char b[BDEVNAME_SIZE];
7860 			seq_printf(seq, " %s[%d]",
7861 				bdevname(rdev->bdev,b), rdev->desc_nr);
7862 			if (test_bit(WriteMostly, &rdev->flags))
7863 				seq_printf(seq, "(W)");
7864 			if (test_bit(Journal, &rdev->flags))
7865 				seq_printf(seq, "(J)");
7866 			if (test_bit(Faulty, &rdev->flags)) {
7867 				seq_printf(seq, "(F)");
7868 				continue;
7869 			}
7870 			if (rdev->raid_disk < 0)
7871 				seq_printf(seq, "(S)"); /* spare */
7872 			if (test_bit(Replacement, &rdev->flags))
7873 				seq_printf(seq, "(R)");
7874 			sectors += rdev->sectors;
7875 		}
7876 		rcu_read_unlock();
7877 
7878 		if (!list_empty(&mddev->disks)) {
7879 			if (mddev->pers)
7880 				seq_printf(seq, "\n      %llu blocks",
7881 					   (unsigned long long)
7882 					   mddev->array_sectors / 2);
7883 			else
7884 				seq_printf(seq, "\n      %llu blocks",
7885 					   (unsigned long long)sectors / 2);
7886 		}
7887 		if (mddev->persistent) {
7888 			if (mddev->major_version != 0 ||
7889 			    mddev->minor_version != 90) {
7890 				seq_printf(seq," super %d.%d",
7891 					   mddev->major_version,
7892 					   mddev->minor_version);
7893 			}
7894 		} else if (mddev->external)
7895 			seq_printf(seq, " super external:%s",
7896 				   mddev->metadata_type);
7897 		else
7898 			seq_printf(seq, " super non-persistent");
7899 
7900 		if (mddev->pers) {
7901 			mddev->pers->status(seq, mddev);
7902 			seq_printf(seq, "\n      ");
7903 			if (mddev->pers->sync_request) {
7904 				if (status_resync(seq, mddev))
7905 					seq_printf(seq, "\n      ");
7906 			}
7907 		} else
7908 			seq_printf(seq, "\n       ");
7909 
7910 		bitmap_status(seq, mddev->bitmap);
7911 
7912 		seq_printf(seq, "\n");
7913 	}
7914 	spin_unlock(&mddev->lock);
7915 
7916 	return 0;
7917 }
7918 
7919 static const struct seq_operations md_seq_ops = {
7920 	.start  = md_seq_start,
7921 	.next   = md_seq_next,
7922 	.stop   = md_seq_stop,
7923 	.show   = md_seq_show,
7924 };
7925 
7926 static int md_seq_open(struct inode *inode, struct file *file)
7927 {
7928 	struct seq_file *seq;
7929 	int error;
7930 
7931 	error = seq_open(file, &md_seq_ops);
7932 	if (error)
7933 		return error;
7934 
7935 	seq = file->private_data;
7936 	seq->poll_event = atomic_read(&md_event_count);
7937 	return error;
7938 }
7939 
7940 static int md_unloading;
7941 static __poll_t mdstat_poll(struct file *filp, poll_table *wait)
7942 {
7943 	struct seq_file *seq = filp->private_data;
7944 	__poll_t mask;
7945 
7946 	if (md_unloading)
7947 		return EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
7948 	poll_wait(filp, &md_event_waiters, wait);
7949 
7950 	/* always allow read */
7951 	mask = EPOLLIN | EPOLLRDNORM;
7952 
7953 	if (seq->poll_event != atomic_read(&md_event_count))
7954 		mask |= EPOLLERR | EPOLLPRI;
7955 	return mask;
7956 }
7957 
7958 static const struct file_operations md_seq_fops = {
7959 	.owner		= THIS_MODULE,
7960 	.open           = md_seq_open,
7961 	.read           = seq_read,
7962 	.llseek         = seq_lseek,
7963 	.release	= seq_release,
7964 	.poll		= mdstat_poll,
7965 };
7966 
7967 int register_md_personality(struct md_personality *p)
7968 {
7969 	pr_debug("md: %s personality registered for level %d\n",
7970 		 p->name, p->level);
7971 	spin_lock(&pers_lock);
7972 	list_add_tail(&p->list, &pers_list);
7973 	spin_unlock(&pers_lock);
7974 	return 0;
7975 }
7976 EXPORT_SYMBOL(register_md_personality);
7977 
7978 int unregister_md_personality(struct md_personality *p)
7979 {
7980 	pr_debug("md: %s personality unregistered\n", p->name);
7981 	spin_lock(&pers_lock);
7982 	list_del_init(&p->list);
7983 	spin_unlock(&pers_lock);
7984 	return 0;
7985 }
7986 EXPORT_SYMBOL(unregister_md_personality);
7987 
7988 int register_md_cluster_operations(struct md_cluster_operations *ops,
7989 				   struct module *module)
7990 {
7991 	int ret = 0;
7992 	spin_lock(&pers_lock);
7993 	if (md_cluster_ops != NULL)
7994 		ret = -EALREADY;
7995 	else {
7996 		md_cluster_ops = ops;
7997 		md_cluster_mod = module;
7998 	}
7999 	spin_unlock(&pers_lock);
8000 	return ret;
8001 }
8002 EXPORT_SYMBOL(register_md_cluster_operations);
8003 
8004 int unregister_md_cluster_operations(void)
8005 {
8006 	spin_lock(&pers_lock);
8007 	md_cluster_ops = NULL;
8008 	spin_unlock(&pers_lock);
8009 	return 0;
8010 }
8011 EXPORT_SYMBOL(unregister_md_cluster_operations);
8012 
8013 int md_setup_cluster(struct mddev *mddev, int nodes)
8014 {
8015 	if (!md_cluster_ops)
8016 		request_module("md-cluster");
8017 	spin_lock(&pers_lock);
8018 	/* ensure module won't be unloaded */
8019 	if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
8020 		pr_warn("can't find md-cluster module or get it's reference.\n");
8021 		spin_unlock(&pers_lock);
8022 		return -ENOENT;
8023 	}
8024 	spin_unlock(&pers_lock);
8025 
8026 	return md_cluster_ops->join(mddev, nodes);
8027 }
8028 
8029 void md_cluster_stop(struct mddev *mddev)
8030 {
8031 	if (!md_cluster_ops)
8032 		return;
8033 	md_cluster_ops->leave(mddev);
8034 	module_put(md_cluster_mod);
8035 }
8036 
8037 static int is_mddev_idle(struct mddev *mddev, int init)
8038 {
8039 	struct md_rdev *rdev;
8040 	int idle;
8041 	int curr_events;
8042 
8043 	idle = 1;
8044 	rcu_read_lock();
8045 	rdev_for_each_rcu(rdev, mddev) {
8046 		struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
8047 		curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
8048 			      (int)part_stat_read(&disk->part0, sectors[1]) -
8049 			      atomic_read(&disk->sync_io);
8050 		/* sync IO will cause sync_io to increase before the disk_stats
8051 		 * as sync_io is counted when a request starts, and
8052 		 * disk_stats is counted when it completes.
8053 		 * So resync activity will cause curr_events to be smaller than
8054 		 * when there was no such activity.
8055 		 * non-sync IO will cause disk_stat to increase without
8056 		 * increasing sync_io so curr_events will (eventually)
8057 		 * be larger than it was before.  Once it becomes
8058 		 * substantially larger, the test below will cause
8059 		 * the array to appear non-idle, and resync will slow
8060 		 * down.
8061 		 * If there is a lot of outstanding resync activity when
8062 		 * we set last_event to curr_events, then all that activity
8063 		 * completing might cause the array to appear non-idle
8064 		 * and resync will be slowed down even though there might
8065 		 * not have been non-resync activity.  This will only
8066 		 * happen once though.  'last_events' will soon reflect
8067 		 * the state where there is little or no outstanding
8068 		 * resync requests, and further resync activity will
8069 		 * always make curr_events less than last_events.
8070 		 *
8071 		 */
8072 		if (init || curr_events - rdev->last_events > 64) {
8073 			rdev->last_events = curr_events;
8074 			idle = 0;
8075 		}
8076 	}
8077 	rcu_read_unlock();
8078 	return idle;
8079 }
8080 
8081 void md_done_sync(struct mddev *mddev, int blocks, int ok)
8082 {
8083 	/* another "blocks" (512byte) blocks have been synced */
8084 	atomic_sub(blocks, &mddev->recovery_active);
8085 	wake_up(&mddev->recovery_wait);
8086 	if (!ok) {
8087 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8088 		set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
8089 		md_wakeup_thread(mddev->thread);
8090 		// stop recovery, signal do_sync ....
8091 	}
8092 }
8093 EXPORT_SYMBOL(md_done_sync);
8094 
8095 /* md_write_start(mddev, bi)
8096  * If we need to update some array metadata (e.g. 'active' flag
8097  * in superblock) before writing, schedule a superblock update
8098  * and wait for it to complete.
8099  * A return value of 'false' means that the write wasn't recorded
8100  * and cannot proceed as the array is being suspend.
8101  */
8102 bool md_write_start(struct mddev *mddev, struct bio *bi)
8103 {
8104 	int did_change = 0;
8105 
8106 	if (bio_data_dir(bi) != WRITE)
8107 		return true;
8108 
8109 	BUG_ON(mddev->ro == 1);
8110 	if (mddev->ro == 2) {
8111 		/* need to switch to read/write */
8112 		mddev->ro = 0;
8113 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8114 		md_wakeup_thread(mddev->thread);
8115 		md_wakeup_thread(mddev->sync_thread);
8116 		did_change = 1;
8117 	}
8118 	rcu_read_lock();
8119 	percpu_ref_get(&mddev->writes_pending);
8120 	smp_mb(); /* Match smp_mb in set_in_sync() */
8121 	if (mddev->safemode == 1)
8122 		mddev->safemode = 0;
8123 	/* sync_checkers is always 0 when writes_pending is in per-cpu mode */
8124 	if (mddev->in_sync || mddev->sync_checkers) {
8125 		spin_lock(&mddev->lock);
8126 		if (mddev->in_sync) {
8127 			mddev->in_sync = 0;
8128 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8129 			set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8130 			md_wakeup_thread(mddev->thread);
8131 			did_change = 1;
8132 		}
8133 		spin_unlock(&mddev->lock);
8134 	}
8135 	rcu_read_unlock();
8136 	if (did_change)
8137 		sysfs_notify_dirent_safe(mddev->sysfs_state);
8138 	if (!mddev->has_superblocks)
8139 		return true;
8140 	wait_event(mddev->sb_wait,
8141 		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags) ||
8142 		   mddev->suspended);
8143 	if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
8144 		percpu_ref_put(&mddev->writes_pending);
8145 		return false;
8146 	}
8147 	return true;
8148 }
8149 EXPORT_SYMBOL(md_write_start);
8150 
8151 /* md_write_inc can only be called when md_write_start() has
8152  * already been called at least once of the current request.
8153  * It increments the counter and is useful when a single request
8154  * is split into several parts.  Each part causes an increment and
8155  * so needs a matching md_write_end().
8156  * Unlike md_write_start(), it is safe to call md_write_inc() inside
8157  * a spinlocked region.
8158  */
8159 void md_write_inc(struct mddev *mddev, struct bio *bi)
8160 {
8161 	if (bio_data_dir(bi) != WRITE)
8162 		return;
8163 	WARN_ON_ONCE(mddev->in_sync || mddev->ro);
8164 	percpu_ref_get(&mddev->writes_pending);
8165 }
8166 EXPORT_SYMBOL(md_write_inc);
8167 
8168 void md_write_end(struct mddev *mddev)
8169 {
8170 	percpu_ref_put(&mddev->writes_pending);
8171 
8172 	if (mddev->safemode == 2)
8173 		md_wakeup_thread(mddev->thread);
8174 	else if (mddev->safemode_delay)
8175 		/* The roundup() ensures this only performs locking once
8176 		 * every ->safemode_delay jiffies
8177 		 */
8178 		mod_timer(&mddev->safemode_timer,
8179 			  roundup(jiffies, mddev->safemode_delay) +
8180 			  mddev->safemode_delay);
8181 }
8182 
8183 EXPORT_SYMBOL(md_write_end);
8184 
8185 /* md_allow_write(mddev)
8186  * Calling this ensures that the array is marked 'active' so that writes
8187  * may proceed without blocking.  It is important to call this before
8188  * attempting a GFP_KERNEL allocation while holding the mddev lock.
8189  * Must be called with mddev_lock held.
8190  */
8191 void md_allow_write(struct mddev *mddev)
8192 {
8193 	if (!mddev->pers)
8194 		return;
8195 	if (mddev->ro)
8196 		return;
8197 	if (!mddev->pers->sync_request)
8198 		return;
8199 
8200 	spin_lock(&mddev->lock);
8201 	if (mddev->in_sync) {
8202 		mddev->in_sync = 0;
8203 		set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8204 		set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8205 		if (mddev->safemode_delay &&
8206 		    mddev->safemode == 0)
8207 			mddev->safemode = 1;
8208 		spin_unlock(&mddev->lock);
8209 		md_update_sb(mddev, 0);
8210 		sysfs_notify_dirent_safe(mddev->sysfs_state);
8211 		/* wait for the dirty state to be recorded in the metadata */
8212 		wait_event(mddev->sb_wait,
8213 			   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
8214 	} else
8215 		spin_unlock(&mddev->lock);
8216 }
8217 EXPORT_SYMBOL_GPL(md_allow_write);
8218 
8219 #define SYNC_MARKS	10
8220 #define	SYNC_MARK_STEP	(3*HZ)
8221 #define UPDATE_FREQUENCY (5*60*HZ)
8222 void md_do_sync(struct md_thread *thread)
8223 {
8224 	struct mddev *mddev = thread->mddev;
8225 	struct mddev *mddev2;
8226 	unsigned int currspeed = 0,
8227 		 window;
8228 	sector_t max_sectors,j, io_sectors, recovery_done;
8229 	unsigned long mark[SYNC_MARKS];
8230 	unsigned long update_time;
8231 	sector_t mark_cnt[SYNC_MARKS];
8232 	int last_mark,m;
8233 	struct list_head *tmp;
8234 	sector_t last_check;
8235 	int skipped = 0;
8236 	struct md_rdev *rdev;
8237 	char *desc, *action = NULL;
8238 	struct blk_plug plug;
8239 	int ret;
8240 
8241 	/* just incase thread restarts... */
8242 	if (test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8243 	    test_bit(MD_RECOVERY_WAIT, &mddev->recovery))
8244 		return;
8245 	if (mddev->ro) {/* never try to sync a read-only array */
8246 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8247 		return;
8248 	}
8249 
8250 	if (mddev_is_clustered(mddev)) {
8251 		ret = md_cluster_ops->resync_start(mddev);
8252 		if (ret)
8253 			goto skip;
8254 
8255 		set_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags);
8256 		if (!(test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8257 			test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) ||
8258 			test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
8259 		     && ((unsigned long long)mddev->curr_resync_completed
8260 			 < (unsigned long long)mddev->resync_max_sectors))
8261 			goto skip;
8262 	}
8263 
8264 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8265 		if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
8266 			desc = "data-check";
8267 			action = "check";
8268 		} else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8269 			desc = "requested-resync";
8270 			action = "repair";
8271 		} else
8272 			desc = "resync";
8273 	} else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8274 		desc = "reshape";
8275 	else
8276 		desc = "recovery";
8277 
8278 	mddev->last_sync_action = action ?: desc;
8279 
8280 	/* we overload curr_resync somewhat here.
8281 	 * 0 == not engaged in resync at all
8282 	 * 2 == checking that there is no conflict with another sync
8283 	 * 1 == like 2, but have yielded to allow conflicting resync to
8284 	 *		commense
8285 	 * other == active in resync - this many blocks
8286 	 *
8287 	 * Before starting a resync we must have set curr_resync to
8288 	 * 2, and then checked that every "conflicting" array has curr_resync
8289 	 * less than ours.  When we find one that is the same or higher
8290 	 * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
8291 	 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
8292 	 * This will mean we have to start checking from the beginning again.
8293 	 *
8294 	 */
8295 
8296 	do {
8297 		int mddev2_minor = -1;
8298 		mddev->curr_resync = 2;
8299 
8300 	try_again:
8301 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8302 			goto skip;
8303 		for_each_mddev(mddev2, tmp) {
8304 			if (mddev2 == mddev)
8305 				continue;
8306 			if (!mddev->parallel_resync
8307 			&&  mddev2->curr_resync
8308 			&&  match_mddev_units(mddev, mddev2)) {
8309 				DEFINE_WAIT(wq);
8310 				if (mddev < mddev2 && mddev->curr_resync == 2) {
8311 					/* arbitrarily yield */
8312 					mddev->curr_resync = 1;
8313 					wake_up(&resync_wait);
8314 				}
8315 				if (mddev > mddev2 && mddev->curr_resync == 1)
8316 					/* no need to wait here, we can wait the next
8317 					 * time 'round when curr_resync == 2
8318 					 */
8319 					continue;
8320 				/* We need to wait 'interruptible' so as not to
8321 				 * contribute to the load average, and not to
8322 				 * be caught by 'softlockup'
8323 				 */
8324 				prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
8325 				if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8326 				    mddev2->curr_resync >= mddev->curr_resync) {
8327 					if (mddev2_minor != mddev2->md_minor) {
8328 						mddev2_minor = mddev2->md_minor;
8329 						pr_info("md: delaying %s of %s until %s has finished (they share one or more physical units)\n",
8330 							desc, mdname(mddev),
8331 							mdname(mddev2));
8332 					}
8333 					mddev_put(mddev2);
8334 					if (signal_pending(current))
8335 						flush_signals(current);
8336 					schedule();
8337 					finish_wait(&resync_wait, &wq);
8338 					goto try_again;
8339 				}
8340 				finish_wait(&resync_wait, &wq);
8341 			}
8342 		}
8343 	} while (mddev->curr_resync < 2);
8344 
8345 	j = 0;
8346 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8347 		/* resync follows the size requested by the personality,
8348 		 * which defaults to physical size, but can be virtual size
8349 		 */
8350 		max_sectors = mddev->resync_max_sectors;
8351 		atomic64_set(&mddev->resync_mismatches, 0);
8352 		/* we don't use the checkpoint if there's a bitmap */
8353 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8354 			j = mddev->resync_min;
8355 		else if (!mddev->bitmap)
8356 			j = mddev->recovery_cp;
8357 
8358 	} else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8359 		max_sectors = mddev->resync_max_sectors;
8360 	else {
8361 		/* recovery follows the physical size of devices */
8362 		max_sectors = mddev->dev_sectors;
8363 		j = MaxSector;
8364 		rcu_read_lock();
8365 		rdev_for_each_rcu(rdev, mddev)
8366 			if (rdev->raid_disk >= 0 &&
8367 			    !test_bit(Journal, &rdev->flags) &&
8368 			    !test_bit(Faulty, &rdev->flags) &&
8369 			    !test_bit(In_sync, &rdev->flags) &&
8370 			    rdev->recovery_offset < j)
8371 				j = rdev->recovery_offset;
8372 		rcu_read_unlock();
8373 
8374 		/* If there is a bitmap, we need to make sure all
8375 		 * writes that started before we added a spare
8376 		 * complete before we start doing a recovery.
8377 		 * Otherwise the write might complete and (via
8378 		 * bitmap_endwrite) set a bit in the bitmap after the
8379 		 * recovery has checked that bit and skipped that
8380 		 * region.
8381 		 */
8382 		if (mddev->bitmap) {
8383 			mddev->pers->quiesce(mddev, 1);
8384 			mddev->pers->quiesce(mddev, 0);
8385 		}
8386 	}
8387 
8388 	pr_info("md: %s of RAID array %s\n", desc, mdname(mddev));
8389 	pr_debug("md: minimum _guaranteed_  speed: %d KB/sec/disk.\n", speed_min(mddev));
8390 	pr_debug("md: using maximum available idle IO bandwidth (but not more than %d KB/sec) for %s.\n",
8391 		 speed_max(mddev), desc);
8392 
8393 	is_mddev_idle(mddev, 1); /* this initializes IO event counters */
8394 
8395 	io_sectors = 0;
8396 	for (m = 0; m < SYNC_MARKS; m++) {
8397 		mark[m] = jiffies;
8398 		mark_cnt[m] = io_sectors;
8399 	}
8400 	last_mark = 0;
8401 	mddev->resync_mark = mark[last_mark];
8402 	mddev->resync_mark_cnt = mark_cnt[last_mark];
8403 
8404 	/*
8405 	 * Tune reconstruction:
8406 	 */
8407 	window = 32*(PAGE_SIZE/512);
8408 	pr_debug("md: using %dk window, over a total of %lluk.\n",
8409 		 window/2, (unsigned long long)max_sectors/2);
8410 
8411 	atomic_set(&mddev->recovery_active, 0);
8412 	last_check = 0;
8413 
8414 	if (j>2) {
8415 		pr_debug("md: resuming %s of %s from checkpoint.\n",
8416 			 desc, mdname(mddev));
8417 		mddev->curr_resync = j;
8418 	} else
8419 		mddev->curr_resync = 3; /* no longer delayed */
8420 	mddev->curr_resync_completed = j;
8421 	sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8422 	md_new_event(mddev);
8423 	update_time = jiffies;
8424 
8425 	blk_start_plug(&plug);
8426 	while (j < max_sectors) {
8427 		sector_t sectors;
8428 
8429 		skipped = 0;
8430 
8431 		if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8432 		    ((mddev->curr_resync > mddev->curr_resync_completed &&
8433 		      (mddev->curr_resync - mddev->curr_resync_completed)
8434 		      > (max_sectors >> 4)) ||
8435 		     time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
8436 		     (j - mddev->curr_resync_completed)*2
8437 		     >= mddev->resync_max - mddev->curr_resync_completed ||
8438 		     mddev->curr_resync_completed > mddev->resync_max
8439 			    )) {
8440 			/* time to update curr_resync_completed */
8441 			wait_event(mddev->recovery_wait,
8442 				   atomic_read(&mddev->recovery_active) == 0);
8443 			mddev->curr_resync_completed = j;
8444 			if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
8445 			    j > mddev->recovery_cp)
8446 				mddev->recovery_cp = j;
8447 			update_time = jiffies;
8448 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8449 			sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8450 		}
8451 
8452 		while (j >= mddev->resync_max &&
8453 		       !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8454 			/* As this condition is controlled by user-space,
8455 			 * we can block indefinitely, so use '_interruptible'
8456 			 * to avoid triggering warnings.
8457 			 */
8458 			flush_signals(current); /* just in case */
8459 			wait_event_interruptible(mddev->recovery_wait,
8460 						 mddev->resync_max > j
8461 						 || test_bit(MD_RECOVERY_INTR,
8462 							     &mddev->recovery));
8463 		}
8464 
8465 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8466 			break;
8467 
8468 		sectors = mddev->pers->sync_request(mddev, j, &skipped);
8469 		if (sectors == 0) {
8470 			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8471 			break;
8472 		}
8473 
8474 		if (!skipped) { /* actual IO requested */
8475 			io_sectors += sectors;
8476 			atomic_add(sectors, &mddev->recovery_active);
8477 		}
8478 
8479 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8480 			break;
8481 
8482 		j += sectors;
8483 		if (j > max_sectors)
8484 			/* when skipping, extra large numbers can be returned. */
8485 			j = max_sectors;
8486 		if (j > 2)
8487 			mddev->curr_resync = j;
8488 		mddev->curr_mark_cnt = io_sectors;
8489 		if (last_check == 0)
8490 			/* this is the earliest that rebuild will be
8491 			 * visible in /proc/mdstat
8492 			 */
8493 			md_new_event(mddev);
8494 
8495 		if (last_check + window > io_sectors || j == max_sectors)
8496 			continue;
8497 
8498 		last_check = io_sectors;
8499 	repeat:
8500 		if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
8501 			/* step marks */
8502 			int next = (last_mark+1) % SYNC_MARKS;
8503 
8504 			mddev->resync_mark = mark[next];
8505 			mddev->resync_mark_cnt = mark_cnt[next];
8506 			mark[next] = jiffies;
8507 			mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
8508 			last_mark = next;
8509 		}
8510 
8511 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8512 			break;
8513 
8514 		/*
8515 		 * this loop exits only if either when we are slower than
8516 		 * the 'hard' speed limit, or the system was IO-idle for
8517 		 * a jiffy.
8518 		 * the system might be non-idle CPU-wise, but we only care
8519 		 * about not overloading the IO subsystem. (things like an
8520 		 * e2fsck being done on the RAID array should execute fast)
8521 		 */
8522 		cond_resched();
8523 
8524 		recovery_done = io_sectors - atomic_read(&mddev->recovery_active);
8525 		currspeed = ((unsigned long)(recovery_done - mddev->resync_mark_cnt))/2
8526 			/((jiffies-mddev->resync_mark)/HZ +1) +1;
8527 
8528 		if (currspeed > speed_min(mddev)) {
8529 			if (currspeed > speed_max(mddev)) {
8530 				msleep(500);
8531 				goto repeat;
8532 			}
8533 			if (!is_mddev_idle(mddev, 0)) {
8534 				/*
8535 				 * Give other IO more of a chance.
8536 				 * The faster the devices, the less we wait.
8537 				 */
8538 				wait_event(mddev->recovery_wait,
8539 					   !atomic_read(&mddev->recovery_active));
8540 			}
8541 		}
8542 	}
8543 	pr_info("md: %s: %s %s.\n",mdname(mddev), desc,
8544 		test_bit(MD_RECOVERY_INTR, &mddev->recovery)
8545 		? "interrupted" : "done");
8546 	/*
8547 	 * this also signals 'finished resyncing' to md_stop
8548 	 */
8549 	blk_finish_plug(&plug);
8550 	wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
8551 
8552 	if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8553 	    !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8554 	    mddev->curr_resync > 3) {
8555 		mddev->curr_resync_completed = mddev->curr_resync;
8556 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8557 	}
8558 	mddev->pers->sync_request(mddev, max_sectors, &skipped);
8559 
8560 	if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
8561 	    mddev->curr_resync > 3) {
8562 		if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8563 			if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8564 				if (mddev->curr_resync >= mddev->recovery_cp) {
8565 					pr_debug("md: checkpointing %s of %s.\n",
8566 						 desc, mdname(mddev));
8567 					if (test_bit(MD_RECOVERY_ERROR,
8568 						&mddev->recovery))
8569 						mddev->recovery_cp =
8570 							mddev->curr_resync_completed;
8571 					else
8572 						mddev->recovery_cp =
8573 							mddev->curr_resync;
8574 				}
8575 			} else
8576 				mddev->recovery_cp = MaxSector;
8577 		} else {
8578 			if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8579 				mddev->curr_resync = MaxSector;
8580 			if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8581 			    test_bit(MD_RECOVERY_RECOVER, &mddev->recovery)) {
8582 				rcu_read_lock();
8583 				rdev_for_each_rcu(rdev, mddev)
8584 					if (rdev->raid_disk >= 0 &&
8585 					    mddev->delta_disks >= 0 &&
8586 					    !test_bit(Journal, &rdev->flags) &&
8587 					    !test_bit(Faulty, &rdev->flags) &&
8588 					    !test_bit(In_sync, &rdev->flags) &&
8589 					    rdev->recovery_offset < mddev->curr_resync)
8590 						rdev->recovery_offset = mddev->curr_resync;
8591 				rcu_read_unlock();
8592 			}
8593 		}
8594 	}
8595  skip:
8596 	/* set CHANGE_PENDING here since maybe another update is needed,
8597 	 * so other nodes are informed. It should be harmless for normal
8598 	 * raid */
8599 	set_mask_bits(&mddev->sb_flags, 0,
8600 		      BIT(MD_SB_CHANGE_PENDING) | BIT(MD_SB_CHANGE_DEVS));
8601 
8602 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8603 			!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8604 			mddev->delta_disks > 0 &&
8605 			mddev->pers->finish_reshape &&
8606 			mddev->pers->size &&
8607 			mddev->queue) {
8608 		mddev_lock_nointr(mddev);
8609 		md_set_array_sectors(mddev, mddev->pers->size(mddev, 0, 0));
8610 		mddev_unlock(mddev);
8611 		set_capacity(mddev->gendisk, mddev->array_sectors);
8612 		revalidate_disk(mddev->gendisk);
8613 	}
8614 
8615 	spin_lock(&mddev->lock);
8616 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8617 		/* We completed so min/max setting can be forgotten if used. */
8618 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8619 			mddev->resync_min = 0;
8620 		mddev->resync_max = MaxSector;
8621 	} else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8622 		mddev->resync_min = mddev->curr_resync_completed;
8623 	set_bit(MD_RECOVERY_DONE, &mddev->recovery);
8624 	mddev->curr_resync = 0;
8625 	spin_unlock(&mddev->lock);
8626 
8627 	wake_up(&resync_wait);
8628 	md_wakeup_thread(mddev->thread);
8629 	return;
8630 }
8631 EXPORT_SYMBOL_GPL(md_do_sync);
8632 
8633 static int remove_and_add_spares(struct mddev *mddev,
8634 				 struct md_rdev *this)
8635 {
8636 	struct md_rdev *rdev;
8637 	int spares = 0;
8638 	int removed = 0;
8639 	bool remove_some = false;
8640 
8641 	if (this && test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8642 		/* Mustn't remove devices when resync thread is running */
8643 		return 0;
8644 
8645 	rdev_for_each(rdev, mddev) {
8646 		if ((this == NULL || rdev == this) &&
8647 		    rdev->raid_disk >= 0 &&
8648 		    !test_bit(Blocked, &rdev->flags) &&
8649 		    test_bit(Faulty, &rdev->flags) &&
8650 		    atomic_read(&rdev->nr_pending)==0) {
8651 			/* Faulty non-Blocked devices with nr_pending == 0
8652 			 * never get nr_pending incremented,
8653 			 * never get Faulty cleared, and never get Blocked set.
8654 			 * So we can synchronize_rcu now rather than once per device
8655 			 */
8656 			remove_some = true;
8657 			set_bit(RemoveSynchronized, &rdev->flags);
8658 		}
8659 	}
8660 
8661 	if (remove_some)
8662 		synchronize_rcu();
8663 	rdev_for_each(rdev, mddev) {
8664 		if ((this == NULL || rdev == this) &&
8665 		    rdev->raid_disk >= 0 &&
8666 		    !test_bit(Blocked, &rdev->flags) &&
8667 		    ((test_bit(RemoveSynchronized, &rdev->flags) ||
8668 		     (!test_bit(In_sync, &rdev->flags) &&
8669 		      !test_bit(Journal, &rdev->flags))) &&
8670 		    atomic_read(&rdev->nr_pending)==0)) {
8671 			if (mddev->pers->hot_remove_disk(
8672 				    mddev, rdev) == 0) {
8673 				sysfs_unlink_rdev(mddev, rdev);
8674 				rdev->saved_raid_disk = rdev->raid_disk;
8675 				rdev->raid_disk = -1;
8676 				removed++;
8677 			}
8678 		}
8679 		if (remove_some && test_bit(RemoveSynchronized, &rdev->flags))
8680 			clear_bit(RemoveSynchronized, &rdev->flags);
8681 	}
8682 
8683 	if (removed && mddev->kobj.sd)
8684 		sysfs_notify(&mddev->kobj, NULL, "degraded");
8685 
8686 	if (this && removed)
8687 		goto no_add;
8688 
8689 	rdev_for_each(rdev, mddev) {
8690 		if (this && this != rdev)
8691 			continue;
8692 		if (test_bit(Candidate, &rdev->flags))
8693 			continue;
8694 		if (rdev->raid_disk >= 0 &&
8695 		    !test_bit(In_sync, &rdev->flags) &&
8696 		    !test_bit(Journal, &rdev->flags) &&
8697 		    !test_bit(Faulty, &rdev->flags))
8698 			spares++;
8699 		if (rdev->raid_disk >= 0)
8700 			continue;
8701 		if (test_bit(Faulty, &rdev->flags))
8702 			continue;
8703 		if (!test_bit(Journal, &rdev->flags)) {
8704 			if (mddev->ro &&
8705 			    ! (rdev->saved_raid_disk >= 0 &&
8706 			       !test_bit(Bitmap_sync, &rdev->flags)))
8707 				continue;
8708 
8709 			rdev->recovery_offset = 0;
8710 		}
8711 		if (mddev->pers->
8712 		    hot_add_disk(mddev, rdev) == 0) {
8713 			if (sysfs_link_rdev(mddev, rdev))
8714 				/* failure here is OK */;
8715 			if (!test_bit(Journal, &rdev->flags))
8716 				spares++;
8717 			md_new_event(mddev);
8718 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8719 		}
8720 	}
8721 no_add:
8722 	if (removed)
8723 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8724 	return spares;
8725 }
8726 
8727 static void md_start_sync(struct work_struct *ws)
8728 {
8729 	struct mddev *mddev = container_of(ws, struct mddev, del_work);
8730 
8731 	mddev->sync_thread = md_register_thread(md_do_sync,
8732 						mddev,
8733 						"resync");
8734 	if (!mddev->sync_thread) {
8735 		pr_warn("%s: could not start resync thread...\n",
8736 			mdname(mddev));
8737 		/* leave the spares where they are, it shouldn't hurt */
8738 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8739 		clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8740 		clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8741 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8742 		clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8743 		wake_up(&resync_wait);
8744 		if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8745 				       &mddev->recovery))
8746 			if (mddev->sysfs_action)
8747 				sysfs_notify_dirent_safe(mddev->sysfs_action);
8748 	} else
8749 		md_wakeup_thread(mddev->sync_thread);
8750 	sysfs_notify_dirent_safe(mddev->sysfs_action);
8751 	md_new_event(mddev);
8752 }
8753 
8754 /*
8755  * This routine is regularly called by all per-raid-array threads to
8756  * deal with generic issues like resync and super-block update.
8757  * Raid personalities that don't have a thread (linear/raid0) do not
8758  * need this as they never do any recovery or update the superblock.
8759  *
8760  * It does not do any resync itself, but rather "forks" off other threads
8761  * to do that as needed.
8762  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
8763  * "->recovery" and create a thread at ->sync_thread.
8764  * When the thread finishes it sets MD_RECOVERY_DONE
8765  * and wakeups up this thread which will reap the thread and finish up.
8766  * This thread also removes any faulty devices (with nr_pending == 0).
8767  *
8768  * The overall approach is:
8769  *  1/ if the superblock needs updating, update it.
8770  *  2/ If a recovery thread is running, don't do anything else.
8771  *  3/ If recovery has finished, clean up, possibly marking spares active.
8772  *  4/ If there are any faulty devices, remove them.
8773  *  5/ If array is degraded, try to add spares devices
8774  *  6/ If array has spares or is not in-sync, start a resync thread.
8775  */
8776 void md_check_recovery(struct mddev *mddev)
8777 {
8778 	if (mddev->suspended)
8779 		return;
8780 
8781 	if (mddev->bitmap)
8782 		bitmap_daemon_work(mddev);
8783 
8784 	if (signal_pending(current)) {
8785 		if (mddev->pers->sync_request && !mddev->external) {
8786 			pr_debug("md: %s in immediate safe mode\n",
8787 				 mdname(mddev));
8788 			mddev->safemode = 2;
8789 		}
8790 		flush_signals(current);
8791 	}
8792 
8793 	if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
8794 		return;
8795 	if ( ! (
8796 		(mddev->sb_flags & ~ (1<<MD_SB_CHANGE_PENDING)) ||
8797 		test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8798 		test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8799 		(mddev->external == 0 && mddev->safemode == 1) ||
8800 		(mddev->safemode == 2
8801 		 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
8802 		))
8803 		return;
8804 
8805 	if (mddev_trylock(mddev)) {
8806 		int spares = 0;
8807 
8808 		if (!mddev->external && mddev->safemode == 1)
8809 			mddev->safemode = 0;
8810 
8811 		if (mddev->ro) {
8812 			struct md_rdev *rdev;
8813 			if (!mddev->external && mddev->in_sync)
8814 				/* 'Blocked' flag not needed as failed devices
8815 				 * will be recorded if array switched to read/write.
8816 				 * Leaving it set will prevent the device
8817 				 * from being removed.
8818 				 */
8819 				rdev_for_each(rdev, mddev)
8820 					clear_bit(Blocked, &rdev->flags);
8821 			/* On a read-only array we can:
8822 			 * - remove failed devices
8823 			 * - add already-in_sync devices if the array itself
8824 			 *   is in-sync.
8825 			 * As we only add devices that are already in-sync,
8826 			 * we can activate the spares immediately.
8827 			 */
8828 			remove_and_add_spares(mddev, NULL);
8829 			/* There is no thread, but we need to call
8830 			 * ->spare_active and clear saved_raid_disk
8831 			 */
8832 			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8833 			md_reap_sync_thread(mddev);
8834 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8835 			clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8836 			clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8837 			goto unlock;
8838 		}
8839 
8840 		if (mddev_is_clustered(mddev)) {
8841 			struct md_rdev *rdev;
8842 			/* kick the device if another node issued a
8843 			 * remove disk.
8844 			 */
8845 			rdev_for_each(rdev, mddev) {
8846 				if (test_and_clear_bit(ClusterRemove, &rdev->flags) &&
8847 						rdev->raid_disk < 0)
8848 					md_kick_rdev_from_array(rdev);
8849 			}
8850 		}
8851 
8852 		if (!mddev->external && !mddev->in_sync) {
8853 			spin_lock(&mddev->lock);
8854 			set_in_sync(mddev);
8855 			spin_unlock(&mddev->lock);
8856 		}
8857 
8858 		if (mddev->sb_flags)
8859 			md_update_sb(mddev, 0);
8860 
8861 		if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
8862 		    !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
8863 			/* resync/recovery still happening */
8864 			clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8865 			goto unlock;
8866 		}
8867 		if (mddev->sync_thread) {
8868 			md_reap_sync_thread(mddev);
8869 			goto unlock;
8870 		}
8871 		/* Set RUNNING before clearing NEEDED to avoid
8872 		 * any transients in the value of "sync_action".
8873 		 */
8874 		mddev->curr_resync_completed = 0;
8875 		spin_lock(&mddev->lock);
8876 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8877 		spin_unlock(&mddev->lock);
8878 		/* Clear some bits that don't mean anything, but
8879 		 * might be left set
8880 		 */
8881 		clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
8882 		clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8883 
8884 		if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8885 		    test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
8886 			goto not_running;
8887 		/* no recovery is running.
8888 		 * remove any failed drives, then
8889 		 * add spares if possible.
8890 		 * Spares are also removed and re-added, to allow
8891 		 * the personality to fail the re-add.
8892 		 */
8893 
8894 		if (mddev->reshape_position != MaxSector) {
8895 			if (mddev->pers->check_reshape == NULL ||
8896 			    mddev->pers->check_reshape(mddev) != 0)
8897 				/* Cannot proceed */
8898 				goto not_running;
8899 			set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8900 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8901 		} else if ((spares = remove_and_add_spares(mddev, NULL))) {
8902 			clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8903 			clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8904 			clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8905 			set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8906 		} else if (mddev->recovery_cp < MaxSector) {
8907 			set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8908 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8909 		} else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
8910 			/* nothing to be done ... */
8911 			goto not_running;
8912 
8913 		if (mddev->pers->sync_request) {
8914 			if (spares) {
8915 				/* We are adding a device or devices to an array
8916 				 * which has the bitmap stored on all devices.
8917 				 * So make sure all bitmap pages get written
8918 				 */
8919 				bitmap_write_all(mddev->bitmap);
8920 			}
8921 			INIT_WORK(&mddev->del_work, md_start_sync);
8922 			queue_work(md_misc_wq, &mddev->del_work);
8923 			goto unlock;
8924 		}
8925 	not_running:
8926 		if (!mddev->sync_thread) {
8927 			clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8928 			wake_up(&resync_wait);
8929 			if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8930 					       &mddev->recovery))
8931 				if (mddev->sysfs_action)
8932 					sysfs_notify_dirent_safe(mddev->sysfs_action);
8933 		}
8934 	unlock:
8935 		wake_up(&mddev->sb_wait);
8936 		mddev_unlock(mddev);
8937 	} else if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags) && mddev->sb_flags) {
8938 		/* Write superblock - thread that called mddev_suspend()
8939 		 * holds reconfig_mutex for us.
8940 		 */
8941 		set_bit(MD_UPDATING_SB, &mddev->flags);
8942 		smp_mb__after_atomic();
8943 		if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags))
8944 			md_update_sb(mddev, 0);
8945 		clear_bit_unlock(MD_UPDATING_SB, &mddev->flags);
8946 		wake_up(&mddev->sb_wait);
8947 	}
8948 }
8949 EXPORT_SYMBOL(md_check_recovery);
8950 
8951 void md_reap_sync_thread(struct mddev *mddev)
8952 {
8953 	struct md_rdev *rdev;
8954 
8955 	/* resync has finished, collect result */
8956 	md_unregister_thread(&mddev->sync_thread);
8957 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8958 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8959 		/* success...*/
8960 		/* activate any spares */
8961 		if (mddev->pers->spare_active(mddev)) {
8962 			sysfs_notify(&mddev->kobj, NULL,
8963 				     "degraded");
8964 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8965 		}
8966 	}
8967 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8968 	    mddev->pers->finish_reshape)
8969 		mddev->pers->finish_reshape(mddev);
8970 
8971 	/* If array is no-longer degraded, then any saved_raid_disk
8972 	 * information must be scrapped.
8973 	 */
8974 	if (!mddev->degraded)
8975 		rdev_for_each(rdev, mddev)
8976 			rdev->saved_raid_disk = -1;
8977 
8978 	md_update_sb(mddev, 1);
8979 	/* MD_SB_CHANGE_PENDING should be cleared by md_update_sb, so we can
8980 	 * call resync_finish here if MD_CLUSTER_RESYNC_LOCKED is set by
8981 	 * clustered raid */
8982 	if (test_and_clear_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags))
8983 		md_cluster_ops->resync_finish(mddev);
8984 	clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8985 	clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8986 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8987 	clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8988 	clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8989 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8990 	wake_up(&resync_wait);
8991 	/* flag recovery needed just to double check */
8992 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8993 	sysfs_notify_dirent_safe(mddev->sysfs_action);
8994 	md_new_event(mddev);
8995 	if (mddev->event_work.func)
8996 		queue_work(md_misc_wq, &mddev->event_work);
8997 }
8998 EXPORT_SYMBOL(md_reap_sync_thread);
8999 
9000 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
9001 {
9002 	sysfs_notify_dirent_safe(rdev->sysfs_state);
9003 	wait_event_timeout(rdev->blocked_wait,
9004 			   !test_bit(Blocked, &rdev->flags) &&
9005 			   !test_bit(BlockedBadBlocks, &rdev->flags),
9006 			   msecs_to_jiffies(5000));
9007 	rdev_dec_pending(rdev, mddev);
9008 }
9009 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
9010 
9011 void md_finish_reshape(struct mddev *mddev)
9012 {
9013 	/* called be personality module when reshape completes. */
9014 	struct md_rdev *rdev;
9015 
9016 	rdev_for_each(rdev, mddev) {
9017 		if (rdev->data_offset > rdev->new_data_offset)
9018 			rdev->sectors += rdev->data_offset - rdev->new_data_offset;
9019 		else
9020 			rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
9021 		rdev->data_offset = rdev->new_data_offset;
9022 	}
9023 }
9024 EXPORT_SYMBOL(md_finish_reshape);
9025 
9026 /* Bad block management */
9027 
9028 /* Returns 1 on success, 0 on failure */
9029 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9030 		       int is_new)
9031 {
9032 	struct mddev *mddev = rdev->mddev;
9033 	int rv;
9034 	if (is_new)
9035 		s += rdev->new_data_offset;
9036 	else
9037 		s += rdev->data_offset;
9038 	rv = badblocks_set(&rdev->badblocks, s, sectors, 0);
9039 	if (rv == 0) {
9040 		/* Make sure they get written out promptly */
9041 		if (test_bit(ExternalBbl, &rdev->flags))
9042 			sysfs_notify(&rdev->kobj, NULL,
9043 				     "unacknowledged_bad_blocks");
9044 		sysfs_notify_dirent_safe(rdev->sysfs_state);
9045 		set_mask_bits(&mddev->sb_flags, 0,
9046 			      BIT(MD_SB_CHANGE_CLEAN) | BIT(MD_SB_CHANGE_PENDING));
9047 		md_wakeup_thread(rdev->mddev->thread);
9048 		return 1;
9049 	} else
9050 		return 0;
9051 }
9052 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
9053 
9054 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9055 			 int is_new)
9056 {
9057 	int rv;
9058 	if (is_new)
9059 		s += rdev->new_data_offset;
9060 	else
9061 		s += rdev->data_offset;
9062 	rv = badblocks_clear(&rdev->badblocks, s, sectors);
9063 	if ((rv == 0) && test_bit(ExternalBbl, &rdev->flags))
9064 		sysfs_notify(&rdev->kobj, NULL, "bad_blocks");
9065 	return rv;
9066 }
9067 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
9068 
9069 static int md_notify_reboot(struct notifier_block *this,
9070 			    unsigned long code, void *x)
9071 {
9072 	struct list_head *tmp;
9073 	struct mddev *mddev;
9074 	int need_delay = 0;
9075 
9076 	for_each_mddev(mddev, tmp) {
9077 		if (mddev_trylock(mddev)) {
9078 			if (mddev->pers)
9079 				__md_stop_writes(mddev);
9080 			if (mddev->persistent)
9081 				mddev->safemode = 2;
9082 			mddev_unlock(mddev);
9083 		}
9084 		need_delay = 1;
9085 	}
9086 	/*
9087 	 * certain more exotic SCSI devices are known to be
9088 	 * volatile wrt too early system reboots. While the
9089 	 * right place to handle this issue is the given
9090 	 * driver, we do want to have a safe RAID driver ...
9091 	 */
9092 	if (need_delay)
9093 		mdelay(1000*1);
9094 
9095 	return NOTIFY_DONE;
9096 }
9097 
9098 static struct notifier_block md_notifier = {
9099 	.notifier_call	= md_notify_reboot,
9100 	.next		= NULL,
9101 	.priority	= INT_MAX, /* before any real devices */
9102 };
9103 
9104 static void md_geninit(void)
9105 {
9106 	pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
9107 
9108 	proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
9109 }
9110 
9111 static int __init md_init(void)
9112 {
9113 	int ret = -ENOMEM;
9114 
9115 	md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
9116 	if (!md_wq)
9117 		goto err_wq;
9118 
9119 	md_misc_wq = alloc_workqueue("md_misc", 0, 0);
9120 	if (!md_misc_wq)
9121 		goto err_misc_wq;
9122 
9123 	if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
9124 		goto err_md;
9125 
9126 	if ((ret = register_blkdev(0, "mdp")) < 0)
9127 		goto err_mdp;
9128 	mdp_major = ret;
9129 
9130 	blk_register_region(MKDEV(MD_MAJOR, 0), 512, THIS_MODULE,
9131 			    md_probe, NULL, NULL);
9132 	blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
9133 			    md_probe, NULL, NULL);
9134 
9135 	register_reboot_notifier(&md_notifier);
9136 	raid_table_header = register_sysctl_table(raid_root_table);
9137 
9138 	md_geninit();
9139 	return 0;
9140 
9141 err_mdp:
9142 	unregister_blkdev(MD_MAJOR, "md");
9143 err_md:
9144 	destroy_workqueue(md_misc_wq);
9145 err_misc_wq:
9146 	destroy_workqueue(md_wq);
9147 err_wq:
9148 	return ret;
9149 }
9150 
9151 static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
9152 {
9153 	struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
9154 	struct md_rdev *rdev2;
9155 	int role, ret;
9156 	char b[BDEVNAME_SIZE];
9157 
9158 	/*
9159 	 * If size is changed in another node then we need to
9160 	 * do resize as well.
9161 	 */
9162 	if (mddev->dev_sectors != le64_to_cpu(sb->size)) {
9163 		ret = mddev->pers->resize(mddev, le64_to_cpu(sb->size));
9164 		if (ret)
9165 			pr_info("md-cluster: resize failed\n");
9166 		else
9167 			bitmap_update_sb(mddev->bitmap);
9168 	}
9169 
9170 	/* Check for change of roles in the active devices */
9171 	rdev_for_each(rdev2, mddev) {
9172 		if (test_bit(Faulty, &rdev2->flags))
9173 			continue;
9174 
9175 		/* Check if the roles changed */
9176 		role = le16_to_cpu(sb->dev_roles[rdev2->desc_nr]);
9177 
9178 		if (test_bit(Candidate, &rdev2->flags)) {
9179 			if (role == 0xfffe) {
9180 				pr_info("md: Removing Candidate device %s because add failed\n", bdevname(rdev2->bdev,b));
9181 				md_kick_rdev_from_array(rdev2);
9182 				continue;
9183 			}
9184 			else
9185 				clear_bit(Candidate, &rdev2->flags);
9186 		}
9187 
9188 		if (role != rdev2->raid_disk) {
9189 			/* got activated */
9190 			if (rdev2->raid_disk == -1 && role != 0xffff) {
9191 				rdev2->saved_raid_disk = role;
9192 				ret = remove_and_add_spares(mddev, rdev2);
9193 				pr_info("Activated spare: %s\n",
9194 					bdevname(rdev2->bdev,b));
9195 				/* wakeup mddev->thread here, so array could
9196 				 * perform resync with the new activated disk */
9197 				set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9198 				md_wakeup_thread(mddev->thread);
9199 
9200 			}
9201 			/* device faulty
9202 			 * We just want to do the minimum to mark the disk
9203 			 * as faulty. The recovery is performed by the
9204 			 * one who initiated the error.
9205 			 */
9206 			if ((role == 0xfffe) || (role == 0xfffd)) {
9207 				md_error(mddev, rdev2);
9208 				clear_bit(Blocked, &rdev2->flags);
9209 			}
9210 		}
9211 	}
9212 
9213 	if (mddev->raid_disks != le32_to_cpu(sb->raid_disks))
9214 		update_raid_disks(mddev, le32_to_cpu(sb->raid_disks));
9215 
9216 	/* Finally set the event to be up to date */
9217 	mddev->events = le64_to_cpu(sb->events);
9218 }
9219 
9220 static int read_rdev(struct mddev *mddev, struct md_rdev *rdev)
9221 {
9222 	int err;
9223 	struct page *swapout = rdev->sb_page;
9224 	struct mdp_superblock_1 *sb;
9225 
9226 	/* Store the sb page of the rdev in the swapout temporary
9227 	 * variable in case we err in the future
9228 	 */
9229 	rdev->sb_page = NULL;
9230 	err = alloc_disk_sb(rdev);
9231 	if (err == 0) {
9232 		ClearPageUptodate(rdev->sb_page);
9233 		rdev->sb_loaded = 0;
9234 		err = super_types[mddev->major_version].
9235 			load_super(rdev, NULL, mddev->minor_version);
9236 	}
9237 	if (err < 0) {
9238 		pr_warn("%s: %d Could not reload rdev(%d) err: %d. Restoring old values\n",
9239 				__func__, __LINE__, rdev->desc_nr, err);
9240 		if (rdev->sb_page)
9241 			put_page(rdev->sb_page);
9242 		rdev->sb_page = swapout;
9243 		rdev->sb_loaded = 1;
9244 		return err;
9245 	}
9246 
9247 	sb = page_address(rdev->sb_page);
9248 	/* Read the offset unconditionally, even if MD_FEATURE_RECOVERY_OFFSET
9249 	 * is not set
9250 	 */
9251 
9252 	if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET))
9253 		rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
9254 
9255 	/* The other node finished recovery, call spare_active to set
9256 	 * device In_sync and mddev->degraded
9257 	 */
9258 	if (rdev->recovery_offset == MaxSector &&
9259 	    !test_bit(In_sync, &rdev->flags) &&
9260 	    mddev->pers->spare_active(mddev))
9261 		sysfs_notify(&mddev->kobj, NULL, "degraded");
9262 
9263 	put_page(swapout);
9264 	return 0;
9265 }
9266 
9267 void md_reload_sb(struct mddev *mddev, int nr)
9268 {
9269 	struct md_rdev *rdev;
9270 	int err;
9271 
9272 	/* Find the rdev */
9273 	rdev_for_each_rcu(rdev, mddev) {
9274 		if (rdev->desc_nr == nr)
9275 			break;
9276 	}
9277 
9278 	if (!rdev || rdev->desc_nr != nr) {
9279 		pr_warn("%s: %d Could not find rdev with nr %d\n", __func__, __LINE__, nr);
9280 		return;
9281 	}
9282 
9283 	err = read_rdev(mddev, rdev);
9284 	if (err < 0)
9285 		return;
9286 
9287 	check_sb_changes(mddev, rdev);
9288 
9289 	/* Read all rdev's to update recovery_offset */
9290 	rdev_for_each_rcu(rdev, mddev) {
9291 		if (!test_bit(Faulty, &rdev->flags))
9292 			read_rdev(mddev, rdev);
9293 	}
9294 }
9295 EXPORT_SYMBOL(md_reload_sb);
9296 
9297 #ifndef MODULE
9298 
9299 /*
9300  * Searches all registered partitions for autorun RAID arrays
9301  * at boot time.
9302  */
9303 
9304 static DEFINE_MUTEX(detected_devices_mutex);
9305 static LIST_HEAD(all_detected_devices);
9306 struct detected_devices_node {
9307 	struct list_head list;
9308 	dev_t dev;
9309 };
9310 
9311 void md_autodetect_dev(dev_t dev)
9312 {
9313 	struct detected_devices_node *node_detected_dev;
9314 
9315 	node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
9316 	if (node_detected_dev) {
9317 		node_detected_dev->dev = dev;
9318 		mutex_lock(&detected_devices_mutex);
9319 		list_add_tail(&node_detected_dev->list, &all_detected_devices);
9320 		mutex_unlock(&detected_devices_mutex);
9321 	}
9322 }
9323 
9324 static void autostart_arrays(int part)
9325 {
9326 	struct md_rdev *rdev;
9327 	struct detected_devices_node *node_detected_dev;
9328 	dev_t dev;
9329 	int i_scanned, i_passed;
9330 
9331 	i_scanned = 0;
9332 	i_passed = 0;
9333 
9334 	pr_info("md: Autodetecting RAID arrays.\n");
9335 
9336 	mutex_lock(&detected_devices_mutex);
9337 	while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
9338 		i_scanned++;
9339 		node_detected_dev = list_entry(all_detected_devices.next,
9340 					struct detected_devices_node, list);
9341 		list_del(&node_detected_dev->list);
9342 		dev = node_detected_dev->dev;
9343 		kfree(node_detected_dev);
9344 		mutex_unlock(&detected_devices_mutex);
9345 		rdev = md_import_device(dev,0, 90);
9346 		mutex_lock(&detected_devices_mutex);
9347 		if (IS_ERR(rdev))
9348 			continue;
9349 
9350 		if (test_bit(Faulty, &rdev->flags))
9351 			continue;
9352 
9353 		set_bit(AutoDetected, &rdev->flags);
9354 		list_add(&rdev->same_set, &pending_raid_disks);
9355 		i_passed++;
9356 	}
9357 	mutex_unlock(&detected_devices_mutex);
9358 
9359 	pr_debug("md: Scanned %d and added %d devices.\n", i_scanned, i_passed);
9360 
9361 	autorun_devices(part);
9362 }
9363 
9364 #endif /* !MODULE */
9365 
9366 static __exit void md_exit(void)
9367 {
9368 	struct mddev *mddev;
9369 	struct list_head *tmp;
9370 	int delay = 1;
9371 
9372 	blk_unregister_region(MKDEV(MD_MAJOR,0), 512);
9373 	blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
9374 
9375 	unregister_blkdev(MD_MAJOR,"md");
9376 	unregister_blkdev(mdp_major, "mdp");
9377 	unregister_reboot_notifier(&md_notifier);
9378 	unregister_sysctl_table(raid_table_header);
9379 
9380 	/* We cannot unload the modules while some process is
9381 	 * waiting for us in select() or poll() - wake them up
9382 	 */
9383 	md_unloading = 1;
9384 	while (waitqueue_active(&md_event_waiters)) {
9385 		/* not safe to leave yet */
9386 		wake_up(&md_event_waiters);
9387 		msleep(delay);
9388 		delay += delay;
9389 	}
9390 	remove_proc_entry("mdstat", NULL);
9391 
9392 	for_each_mddev(mddev, tmp) {
9393 		export_array(mddev);
9394 		mddev->ctime = 0;
9395 		mddev->hold_active = 0;
9396 		/*
9397 		 * for_each_mddev() will call mddev_put() at the end of each
9398 		 * iteration.  As the mddev is now fully clear, this will
9399 		 * schedule the mddev for destruction by a workqueue, and the
9400 		 * destroy_workqueue() below will wait for that to complete.
9401 		 */
9402 	}
9403 	destroy_workqueue(md_misc_wq);
9404 	destroy_workqueue(md_wq);
9405 }
9406 
9407 subsys_initcall(md_init);
9408 module_exit(md_exit)
9409 
9410 static int get_ro(char *buffer, const struct kernel_param *kp)
9411 {
9412 	return sprintf(buffer, "%d", start_readonly);
9413 }
9414 static int set_ro(const char *val, const struct kernel_param *kp)
9415 {
9416 	return kstrtouint(val, 10, (unsigned int *)&start_readonly);
9417 }
9418 
9419 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
9420 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
9421 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
9422 module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
9423 
9424 MODULE_LICENSE("GPL");
9425 MODULE_DESCRIPTION("MD RAID framework");
9426 MODULE_ALIAS("md");
9427 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);
9428