xref: /linux/drivers/md/md.c (revision f79e4d5f92a129a1159c973735007d4ddc8541f3)
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 		err = -EINVAL;
5551 		goto abort;
5552 	}
5553 	spin_unlock(&pers_lock);
5554 	if (mddev->level != pers->level) {
5555 		mddev->level = pers->level;
5556 		mddev->new_level = pers->level;
5557 	}
5558 	strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5559 
5560 	if (mddev->reshape_position != MaxSector &&
5561 	    pers->start_reshape == NULL) {
5562 		/* This personality cannot handle reshaping... */
5563 		module_put(pers->owner);
5564 		err = -EINVAL;
5565 		goto abort;
5566 	}
5567 
5568 	if (pers->sync_request) {
5569 		/* Warn if this is a potentially silly
5570 		 * configuration.
5571 		 */
5572 		char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5573 		struct md_rdev *rdev2;
5574 		int warned = 0;
5575 
5576 		rdev_for_each(rdev, mddev)
5577 			rdev_for_each(rdev2, mddev) {
5578 				if (rdev < rdev2 &&
5579 				    rdev->bdev->bd_contains ==
5580 				    rdev2->bdev->bd_contains) {
5581 					pr_warn("%s: WARNING: %s appears to be on the same physical disk as %s.\n",
5582 						mdname(mddev),
5583 						bdevname(rdev->bdev,b),
5584 						bdevname(rdev2->bdev,b2));
5585 					warned = 1;
5586 				}
5587 			}
5588 
5589 		if (warned)
5590 			pr_warn("True protection against single-disk failure might be compromised.\n");
5591 	}
5592 
5593 	mddev->recovery = 0;
5594 	/* may be over-ridden by personality */
5595 	mddev->resync_max_sectors = mddev->dev_sectors;
5596 
5597 	mddev->ok_start_degraded = start_dirty_degraded;
5598 
5599 	if (start_readonly && mddev->ro == 0)
5600 		mddev->ro = 2; /* read-only, but switch on first write */
5601 
5602 	err = pers->run(mddev);
5603 	if (err)
5604 		pr_warn("md: pers->run() failed ...\n");
5605 	else if (pers->size(mddev, 0, 0) < mddev->array_sectors) {
5606 		WARN_ONCE(!mddev->external_size,
5607 			  "%s: default size too small, but 'external_size' not in effect?\n",
5608 			  __func__);
5609 		pr_warn("md: invalid array_size %llu > default size %llu\n",
5610 			(unsigned long long)mddev->array_sectors / 2,
5611 			(unsigned long long)pers->size(mddev, 0, 0) / 2);
5612 		err = -EINVAL;
5613 	}
5614 	if (err == 0 && pers->sync_request &&
5615 	    (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5616 		struct bitmap *bitmap;
5617 
5618 		bitmap = bitmap_create(mddev, -1);
5619 		if (IS_ERR(bitmap)) {
5620 			err = PTR_ERR(bitmap);
5621 			pr_warn("%s: failed to create bitmap (%d)\n",
5622 				mdname(mddev), err);
5623 		} else
5624 			mddev->bitmap = bitmap;
5625 
5626 	}
5627 	if (err) {
5628 		mddev_detach(mddev);
5629 		if (mddev->private)
5630 			pers->free(mddev, mddev->private);
5631 		mddev->private = NULL;
5632 		module_put(pers->owner);
5633 		bitmap_destroy(mddev);
5634 		goto abort;
5635 	}
5636 	if (mddev->queue) {
5637 		bool nonrot = true;
5638 
5639 		rdev_for_each(rdev, mddev) {
5640 			if (rdev->raid_disk >= 0 &&
5641 			    !blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
5642 				nonrot = false;
5643 				break;
5644 			}
5645 		}
5646 		if (mddev->degraded)
5647 			nonrot = false;
5648 		if (nonrot)
5649 			blk_queue_flag_set(QUEUE_FLAG_NONROT, mddev->queue);
5650 		else
5651 			blk_queue_flag_clear(QUEUE_FLAG_NONROT, mddev->queue);
5652 		mddev->queue->backing_dev_info->congested_data = mddev;
5653 		mddev->queue->backing_dev_info->congested_fn = md_congested;
5654 	}
5655 	if (pers->sync_request) {
5656 		if (mddev->kobj.sd &&
5657 		    sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5658 			pr_warn("md: cannot register extra attributes for %s\n",
5659 				mdname(mddev));
5660 		mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5661 	} else if (mddev->ro == 2) /* auto-readonly not meaningful */
5662 		mddev->ro = 0;
5663 
5664 	atomic_set(&mddev->max_corr_read_errors,
5665 		   MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5666 	mddev->safemode = 0;
5667 	if (mddev_is_clustered(mddev))
5668 		mddev->safemode_delay = 0;
5669 	else
5670 		mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5671 	mddev->in_sync = 1;
5672 	smp_wmb();
5673 	spin_lock(&mddev->lock);
5674 	mddev->pers = pers;
5675 	spin_unlock(&mddev->lock);
5676 	rdev_for_each(rdev, mddev)
5677 		if (rdev->raid_disk >= 0)
5678 			if (sysfs_link_rdev(mddev, rdev))
5679 				/* failure here is OK */;
5680 
5681 	if (mddev->degraded && !mddev->ro)
5682 		/* This ensures that recovering status is reported immediately
5683 		 * via sysfs - until a lack of spares is confirmed.
5684 		 */
5685 		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5686 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5687 
5688 	if (mddev->sb_flags)
5689 		md_update_sb(mddev, 0);
5690 
5691 	md_new_event(mddev);
5692 	sysfs_notify_dirent_safe(mddev->sysfs_state);
5693 	sysfs_notify_dirent_safe(mddev->sysfs_action);
5694 	sysfs_notify(&mddev->kobj, NULL, "degraded");
5695 	return 0;
5696 
5697 abort:
5698 	if (mddev->flush_bio_pool) {
5699 		mempool_destroy(mddev->flush_bio_pool);
5700 		mddev->flush_bio_pool = NULL;
5701 	}
5702 	if (mddev->flush_pool){
5703 		mempool_destroy(mddev->flush_pool);
5704 		mddev->flush_pool = NULL;
5705 	}
5706 
5707 	return err;
5708 }
5709 EXPORT_SYMBOL_GPL(md_run);
5710 
5711 static int do_md_run(struct mddev *mddev)
5712 {
5713 	int err;
5714 
5715 	err = md_run(mddev);
5716 	if (err)
5717 		goto out;
5718 	err = bitmap_load(mddev);
5719 	if (err) {
5720 		bitmap_destroy(mddev);
5721 		goto out;
5722 	}
5723 
5724 	if (mddev_is_clustered(mddev))
5725 		md_allow_write(mddev);
5726 
5727 	/* run start up tasks that require md_thread */
5728 	md_start(mddev);
5729 
5730 	md_wakeup_thread(mddev->thread);
5731 	md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5732 
5733 	set_capacity(mddev->gendisk, mddev->array_sectors);
5734 	revalidate_disk(mddev->gendisk);
5735 	mddev->changed = 1;
5736 	kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5737 out:
5738 	return err;
5739 }
5740 
5741 int md_start(struct mddev *mddev)
5742 {
5743 	int ret = 0;
5744 
5745 	if (mddev->pers->start) {
5746 		set_bit(MD_RECOVERY_WAIT, &mddev->recovery);
5747 		md_wakeup_thread(mddev->thread);
5748 		ret = mddev->pers->start(mddev);
5749 		clear_bit(MD_RECOVERY_WAIT, &mddev->recovery);
5750 		md_wakeup_thread(mddev->sync_thread);
5751 	}
5752 	return ret;
5753 }
5754 EXPORT_SYMBOL_GPL(md_start);
5755 
5756 static int restart_array(struct mddev *mddev)
5757 {
5758 	struct gendisk *disk = mddev->gendisk;
5759 	struct md_rdev *rdev;
5760 	bool has_journal = false;
5761 	bool has_readonly = false;
5762 
5763 	/* Complain if it has no devices */
5764 	if (list_empty(&mddev->disks))
5765 		return -ENXIO;
5766 	if (!mddev->pers)
5767 		return -EINVAL;
5768 	if (!mddev->ro)
5769 		return -EBUSY;
5770 
5771 	rcu_read_lock();
5772 	rdev_for_each_rcu(rdev, mddev) {
5773 		if (test_bit(Journal, &rdev->flags) &&
5774 		    !test_bit(Faulty, &rdev->flags))
5775 			has_journal = true;
5776 		if (bdev_read_only(rdev->bdev))
5777 			has_readonly = true;
5778 	}
5779 	rcu_read_unlock();
5780 	if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !has_journal)
5781 		/* Don't restart rw with journal missing/faulty */
5782 			return -EINVAL;
5783 	if (has_readonly)
5784 		return -EROFS;
5785 
5786 	mddev->safemode = 0;
5787 	mddev->ro = 0;
5788 	set_disk_ro(disk, 0);
5789 	pr_debug("md: %s switched to read-write mode.\n", mdname(mddev));
5790 	/* Kick recovery or resync if necessary */
5791 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5792 	md_wakeup_thread(mddev->thread);
5793 	md_wakeup_thread(mddev->sync_thread);
5794 	sysfs_notify_dirent_safe(mddev->sysfs_state);
5795 	return 0;
5796 }
5797 
5798 static void md_clean(struct mddev *mddev)
5799 {
5800 	mddev->array_sectors = 0;
5801 	mddev->external_size = 0;
5802 	mddev->dev_sectors = 0;
5803 	mddev->raid_disks = 0;
5804 	mddev->recovery_cp = 0;
5805 	mddev->resync_min = 0;
5806 	mddev->resync_max = MaxSector;
5807 	mddev->reshape_position = MaxSector;
5808 	mddev->external = 0;
5809 	mddev->persistent = 0;
5810 	mddev->level = LEVEL_NONE;
5811 	mddev->clevel[0] = 0;
5812 	mddev->flags = 0;
5813 	mddev->sb_flags = 0;
5814 	mddev->ro = 0;
5815 	mddev->metadata_type[0] = 0;
5816 	mddev->chunk_sectors = 0;
5817 	mddev->ctime = mddev->utime = 0;
5818 	mddev->layout = 0;
5819 	mddev->max_disks = 0;
5820 	mddev->events = 0;
5821 	mddev->can_decrease_events = 0;
5822 	mddev->delta_disks = 0;
5823 	mddev->reshape_backwards = 0;
5824 	mddev->new_level = LEVEL_NONE;
5825 	mddev->new_layout = 0;
5826 	mddev->new_chunk_sectors = 0;
5827 	mddev->curr_resync = 0;
5828 	atomic64_set(&mddev->resync_mismatches, 0);
5829 	mddev->suspend_lo = mddev->suspend_hi = 0;
5830 	mddev->sync_speed_min = mddev->sync_speed_max = 0;
5831 	mddev->recovery = 0;
5832 	mddev->in_sync = 0;
5833 	mddev->changed = 0;
5834 	mddev->degraded = 0;
5835 	mddev->safemode = 0;
5836 	mddev->private = NULL;
5837 	mddev->cluster_info = NULL;
5838 	mddev->bitmap_info.offset = 0;
5839 	mddev->bitmap_info.default_offset = 0;
5840 	mddev->bitmap_info.default_space = 0;
5841 	mddev->bitmap_info.chunksize = 0;
5842 	mddev->bitmap_info.daemon_sleep = 0;
5843 	mddev->bitmap_info.max_write_behind = 0;
5844 	mddev->bitmap_info.nodes = 0;
5845 }
5846 
5847 static void __md_stop_writes(struct mddev *mddev)
5848 {
5849 	set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5850 	flush_workqueue(md_misc_wq);
5851 	if (mddev->sync_thread) {
5852 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5853 		md_reap_sync_thread(mddev);
5854 	}
5855 
5856 	del_timer_sync(&mddev->safemode_timer);
5857 
5858 	if (mddev->pers && mddev->pers->quiesce) {
5859 		mddev->pers->quiesce(mddev, 1);
5860 		mddev->pers->quiesce(mddev, 0);
5861 	}
5862 	bitmap_flush(mddev);
5863 
5864 	if (mddev->ro == 0 &&
5865 	    ((!mddev->in_sync && !mddev_is_clustered(mddev)) ||
5866 	     mddev->sb_flags)) {
5867 		/* mark array as shutdown cleanly */
5868 		if (!mddev_is_clustered(mddev))
5869 			mddev->in_sync = 1;
5870 		md_update_sb(mddev, 1);
5871 	}
5872 }
5873 
5874 void md_stop_writes(struct mddev *mddev)
5875 {
5876 	mddev_lock_nointr(mddev);
5877 	__md_stop_writes(mddev);
5878 	mddev_unlock(mddev);
5879 }
5880 EXPORT_SYMBOL_GPL(md_stop_writes);
5881 
5882 static void mddev_detach(struct mddev *mddev)
5883 {
5884 	bitmap_wait_behind_writes(mddev);
5885 	if (mddev->pers && mddev->pers->quiesce) {
5886 		mddev->pers->quiesce(mddev, 1);
5887 		mddev->pers->quiesce(mddev, 0);
5888 	}
5889 	md_unregister_thread(&mddev->thread);
5890 	if (mddev->queue)
5891 		blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
5892 }
5893 
5894 static void __md_stop(struct mddev *mddev)
5895 {
5896 	struct md_personality *pers = mddev->pers;
5897 	bitmap_destroy(mddev);
5898 	mddev_detach(mddev);
5899 	/* Ensure ->event_work is done */
5900 	flush_workqueue(md_misc_wq);
5901 	spin_lock(&mddev->lock);
5902 	mddev->pers = NULL;
5903 	spin_unlock(&mddev->lock);
5904 	pers->free(mddev, mddev->private);
5905 	mddev->private = NULL;
5906 	if (pers->sync_request && mddev->to_remove == NULL)
5907 		mddev->to_remove = &md_redundancy_group;
5908 	module_put(pers->owner);
5909 	clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5910 }
5911 
5912 void md_stop(struct mddev *mddev)
5913 {
5914 	/* stop the array and free an attached data structures.
5915 	 * This is called from dm-raid
5916 	 */
5917 	__md_stop(mddev);
5918 	if (mddev->flush_bio_pool) {
5919 		mempool_destroy(mddev->flush_bio_pool);
5920 		mddev->flush_bio_pool = NULL;
5921 	}
5922 	if (mddev->flush_pool) {
5923 		mempool_destroy(mddev->flush_pool);
5924 		mddev->flush_pool = NULL;
5925 	}
5926 	bioset_exit(&mddev->bio_set);
5927 	bioset_exit(&mddev->sync_set);
5928 }
5929 
5930 EXPORT_SYMBOL_GPL(md_stop);
5931 
5932 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5933 {
5934 	int err = 0;
5935 	int did_freeze = 0;
5936 
5937 	if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5938 		did_freeze = 1;
5939 		set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5940 		md_wakeup_thread(mddev->thread);
5941 	}
5942 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5943 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5944 	if (mddev->sync_thread)
5945 		/* Thread might be blocked waiting for metadata update
5946 		 * which will now never happen */
5947 		wake_up_process(mddev->sync_thread->tsk);
5948 
5949 	if (mddev->external && test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
5950 		return -EBUSY;
5951 	mddev_unlock(mddev);
5952 	wait_event(resync_wait, !test_bit(MD_RECOVERY_RUNNING,
5953 					  &mddev->recovery));
5954 	wait_event(mddev->sb_wait,
5955 		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
5956 	mddev_lock_nointr(mddev);
5957 
5958 	mutex_lock(&mddev->open_mutex);
5959 	if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5960 	    mddev->sync_thread ||
5961 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
5962 		pr_warn("md: %s still in use.\n",mdname(mddev));
5963 		if (did_freeze) {
5964 			clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5965 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5966 			md_wakeup_thread(mddev->thread);
5967 		}
5968 		err = -EBUSY;
5969 		goto out;
5970 	}
5971 	if (mddev->pers) {
5972 		__md_stop_writes(mddev);
5973 
5974 		err  = -ENXIO;
5975 		if (mddev->ro==1)
5976 			goto out;
5977 		mddev->ro = 1;
5978 		set_disk_ro(mddev->gendisk, 1);
5979 		clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5980 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5981 		md_wakeup_thread(mddev->thread);
5982 		sysfs_notify_dirent_safe(mddev->sysfs_state);
5983 		err = 0;
5984 	}
5985 out:
5986 	mutex_unlock(&mddev->open_mutex);
5987 	return err;
5988 }
5989 
5990 /* mode:
5991  *   0 - completely stop and dis-assemble array
5992  *   2 - stop but do not disassemble array
5993  */
5994 static int do_md_stop(struct mddev *mddev, int mode,
5995 		      struct block_device *bdev)
5996 {
5997 	struct gendisk *disk = mddev->gendisk;
5998 	struct md_rdev *rdev;
5999 	int did_freeze = 0;
6000 
6001 	if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
6002 		did_freeze = 1;
6003 		set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6004 		md_wakeup_thread(mddev->thread);
6005 	}
6006 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
6007 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6008 	if (mddev->sync_thread)
6009 		/* Thread might be blocked waiting for metadata update
6010 		 * which will now never happen */
6011 		wake_up_process(mddev->sync_thread->tsk);
6012 
6013 	mddev_unlock(mddev);
6014 	wait_event(resync_wait, (mddev->sync_thread == NULL &&
6015 				 !test_bit(MD_RECOVERY_RUNNING,
6016 					   &mddev->recovery)));
6017 	mddev_lock_nointr(mddev);
6018 
6019 	mutex_lock(&mddev->open_mutex);
6020 	if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
6021 	    mddev->sysfs_active ||
6022 	    mddev->sync_thread ||
6023 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
6024 		pr_warn("md: %s still in use.\n",mdname(mddev));
6025 		mutex_unlock(&mddev->open_mutex);
6026 		if (did_freeze) {
6027 			clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
6028 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6029 			md_wakeup_thread(mddev->thread);
6030 		}
6031 		return -EBUSY;
6032 	}
6033 	if (mddev->pers) {
6034 		if (mddev->ro)
6035 			set_disk_ro(disk, 0);
6036 
6037 		__md_stop_writes(mddev);
6038 		__md_stop(mddev);
6039 		mddev->queue->backing_dev_info->congested_fn = NULL;
6040 
6041 		/* tell userspace to handle 'inactive' */
6042 		sysfs_notify_dirent_safe(mddev->sysfs_state);
6043 
6044 		rdev_for_each(rdev, mddev)
6045 			if (rdev->raid_disk >= 0)
6046 				sysfs_unlink_rdev(mddev, rdev);
6047 
6048 		set_capacity(disk, 0);
6049 		mutex_unlock(&mddev->open_mutex);
6050 		mddev->changed = 1;
6051 		revalidate_disk(disk);
6052 
6053 		if (mddev->ro)
6054 			mddev->ro = 0;
6055 	} else
6056 		mutex_unlock(&mddev->open_mutex);
6057 	/*
6058 	 * Free resources if final stop
6059 	 */
6060 	if (mode == 0) {
6061 		pr_info("md: %s stopped.\n", mdname(mddev));
6062 
6063 		if (mddev->bitmap_info.file) {
6064 			struct file *f = mddev->bitmap_info.file;
6065 			spin_lock(&mddev->lock);
6066 			mddev->bitmap_info.file = NULL;
6067 			spin_unlock(&mddev->lock);
6068 			fput(f);
6069 		}
6070 		mddev->bitmap_info.offset = 0;
6071 
6072 		export_array(mddev);
6073 
6074 		md_clean(mddev);
6075 		if (mddev->hold_active == UNTIL_STOP)
6076 			mddev->hold_active = 0;
6077 	}
6078 	md_new_event(mddev);
6079 	sysfs_notify_dirent_safe(mddev->sysfs_state);
6080 	return 0;
6081 }
6082 
6083 #ifndef MODULE
6084 static void autorun_array(struct mddev *mddev)
6085 {
6086 	struct md_rdev *rdev;
6087 	int err;
6088 
6089 	if (list_empty(&mddev->disks))
6090 		return;
6091 
6092 	pr_info("md: running: ");
6093 
6094 	rdev_for_each(rdev, mddev) {
6095 		char b[BDEVNAME_SIZE];
6096 		pr_cont("<%s>", bdevname(rdev->bdev,b));
6097 	}
6098 	pr_cont("\n");
6099 
6100 	err = do_md_run(mddev);
6101 	if (err) {
6102 		pr_warn("md: do_md_run() returned %d\n", err);
6103 		do_md_stop(mddev, 0, NULL);
6104 	}
6105 }
6106 
6107 /*
6108  * lets try to run arrays based on all disks that have arrived
6109  * until now. (those are in pending_raid_disks)
6110  *
6111  * the method: pick the first pending disk, collect all disks with
6112  * the same UUID, remove all from the pending list and put them into
6113  * the 'same_array' list. Then order this list based on superblock
6114  * update time (freshest comes first), kick out 'old' disks and
6115  * compare superblocks. If everything's fine then run it.
6116  *
6117  * If "unit" is allocated, then bump its reference count
6118  */
6119 static void autorun_devices(int part)
6120 {
6121 	struct md_rdev *rdev0, *rdev, *tmp;
6122 	struct mddev *mddev;
6123 	char b[BDEVNAME_SIZE];
6124 
6125 	pr_info("md: autorun ...\n");
6126 	while (!list_empty(&pending_raid_disks)) {
6127 		int unit;
6128 		dev_t dev;
6129 		LIST_HEAD(candidates);
6130 		rdev0 = list_entry(pending_raid_disks.next,
6131 					 struct md_rdev, same_set);
6132 
6133 		pr_debug("md: considering %s ...\n", bdevname(rdev0->bdev,b));
6134 		INIT_LIST_HEAD(&candidates);
6135 		rdev_for_each_list(rdev, tmp, &pending_raid_disks)
6136 			if (super_90_load(rdev, rdev0, 0) >= 0) {
6137 				pr_debug("md:  adding %s ...\n",
6138 					 bdevname(rdev->bdev,b));
6139 				list_move(&rdev->same_set, &candidates);
6140 			}
6141 		/*
6142 		 * now we have a set of devices, with all of them having
6143 		 * mostly sane superblocks. It's time to allocate the
6144 		 * mddev.
6145 		 */
6146 		if (part) {
6147 			dev = MKDEV(mdp_major,
6148 				    rdev0->preferred_minor << MdpMinorShift);
6149 			unit = MINOR(dev) >> MdpMinorShift;
6150 		} else {
6151 			dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
6152 			unit = MINOR(dev);
6153 		}
6154 		if (rdev0->preferred_minor != unit) {
6155 			pr_warn("md: unit number in %s is bad: %d\n",
6156 				bdevname(rdev0->bdev, b), rdev0->preferred_minor);
6157 			break;
6158 		}
6159 
6160 		md_probe(dev, NULL, NULL);
6161 		mddev = mddev_find(dev);
6162 		if (!mddev || !mddev->gendisk) {
6163 			if (mddev)
6164 				mddev_put(mddev);
6165 			break;
6166 		}
6167 		if (mddev_lock(mddev))
6168 			pr_warn("md: %s locked, cannot run\n", mdname(mddev));
6169 		else if (mddev->raid_disks || mddev->major_version
6170 			 || !list_empty(&mddev->disks)) {
6171 			pr_warn("md: %s already running, cannot run %s\n",
6172 				mdname(mddev), bdevname(rdev0->bdev,b));
6173 			mddev_unlock(mddev);
6174 		} else {
6175 			pr_debug("md: created %s\n", mdname(mddev));
6176 			mddev->persistent = 1;
6177 			rdev_for_each_list(rdev, tmp, &candidates) {
6178 				list_del_init(&rdev->same_set);
6179 				if (bind_rdev_to_array(rdev, mddev))
6180 					export_rdev(rdev);
6181 			}
6182 			autorun_array(mddev);
6183 			mddev_unlock(mddev);
6184 		}
6185 		/* on success, candidates will be empty, on error
6186 		 * it won't...
6187 		 */
6188 		rdev_for_each_list(rdev, tmp, &candidates) {
6189 			list_del_init(&rdev->same_set);
6190 			export_rdev(rdev);
6191 		}
6192 		mddev_put(mddev);
6193 	}
6194 	pr_info("md: ... autorun DONE.\n");
6195 }
6196 #endif /* !MODULE */
6197 
6198 static int get_version(void __user *arg)
6199 {
6200 	mdu_version_t ver;
6201 
6202 	ver.major = MD_MAJOR_VERSION;
6203 	ver.minor = MD_MINOR_VERSION;
6204 	ver.patchlevel = MD_PATCHLEVEL_VERSION;
6205 
6206 	if (copy_to_user(arg, &ver, sizeof(ver)))
6207 		return -EFAULT;
6208 
6209 	return 0;
6210 }
6211 
6212 static int get_array_info(struct mddev *mddev, void __user *arg)
6213 {
6214 	mdu_array_info_t info;
6215 	int nr,working,insync,failed,spare;
6216 	struct md_rdev *rdev;
6217 
6218 	nr = working = insync = failed = spare = 0;
6219 	rcu_read_lock();
6220 	rdev_for_each_rcu(rdev, mddev) {
6221 		nr++;
6222 		if (test_bit(Faulty, &rdev->flags))
6223 			failed++;
6224 		else {
6225 			working++;
6226 			if (test_bit(In_sync, &rdev->flags))
6227 				insync++;
6228 			else if (test_bit(Journal, &rdev->flags))
6229 				/* TODO: add journal count to md_u.h */
6230 				;
6231 			else
6232 				spare++;
6233 		}
6234 	}
6235 	rcu_read_unlock();
6236 
6237 	info.major_version = mddev->major_version;
6238 	info.minor_version = mddev->minor_version;
6239 	info.patch_version = MD_PATCHLEVEL_VERSION;
6240 	info.ctime         = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
6241 	info.level         = mddev->level;
6242 	info.size          = mddev->dev_sectors / 2;
6243 	if (info.size != mddev->dev_sectors / 2) /* overflow */
6244 		info.size = -1;
6245 	info.nr_disks      = nr;
6246 	info.raid_disks    = mddev->raid_disks;
6247 	info.md_minor      = mddev->md_minor;
6248 	info.not_persistent= !mddev->persistent;
6249 
6250 	info.utime         = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
6251 	info.state         = 0;
6252 	if (mddev->in_sync)
6253 		info.state = (1<<MD_SB_CLEAN);
6254 	if (mddev->bitmap && mddev->bitmap_info.offset)
6255 		info.state |= (1<<MD_SB_BITMAP_PRESENT);
6256 	if (mddev_is_clustered(mddev))
6257 		info.state |= (1<<MD_SB_CLUSTERED);
6258 	info.active_disks  = insync;
6259 	info.working_disks = working;
6260 	info.failed_disks  = failed;
6261 	info.spare_disks   = spare;
6262 
6263 	info.layout        = mddev->layout;
6264 	info.chunk_size    = mddev->chunk_sectors << 9;
6265 
6266 	if (copy_to_user(arg, &info, sizeof(info)))
6267 		return -EFAULT;
6268 
6269 	return 0;
6270 }
6271 
6272 static int get_bitmap_file(struct mddev *mddev, void __user * arg)
6273 {
6274 	mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
6275 	char *ptr;
6276 	int err;
6277 
6278 	file = kzalloc(sizeof(*file), GFP_NOIO);
6279 	if (!file)
6280 		return -ENOMEM;
6281 
6282 	err = 0;
6283 	spin_lock(&mddev->lock);
6284 	/* bitmap enabled */
6285 	if (mddev->bitmap_info.file) {
6286 		ptr = file_path(mddev->bitmap_info.file, file->pathname,
6287 				sizeof(file->pathname));
6288 		if (IS_ERR(ptr))
6289 			err = PTR_ERR(ptr);
6290 		else
6291 			memmove(file->pathname, ptr,
6292 				sizeof(file->pathname)-(ptr-file->pathname));
6293 	}
6294 	spin_unlock(&mddev->lock);
6295 
6296 	if (err == 0 &&
6297 	    copy_to_user(arg, file, sizeof(*file)))
6298 		err = -EFAULT;
6299 
6300 	kfree(file);
6301 	return err;
6302 }
6303 
6304 static int get_disk_info(struct mddev *mddev, void __user * arg)
6305 {
6306 	mdu_disk_info_t info;
6307 	struct md_rdev *rdev;
6308 
6309 	if (copy_from_user(&info, arg, sizeof(info)))
6310 		return -EFAULT;
6311 
6312 	rcu_read_lock();
6313 	rdev = md_find_rdev_nr_rcu(mddev, info.number);
6314 	if (rdev) {
6315 		info.major = MAJOR(rdev->bdev->bd_dev);
6316 		info.minor = MINOR(rdev->bdev->bd_dev);
6317 		info.raid_disk = rdev->raid_disk;
6318 		info.state = 0;
6319 		if (test_bit(Faulty, &rdev->flags))
6320 			info.state |= (1<<MD_DISK_FAULTY);
6321 		else if (test_bit(In_sync, &rdev->flags)) {
6322 			info.state |= (1<<MD_DISK_ACTIVE);
6323 			info.state |= (1<<MD_DISK_SYNC);
6324 		}
6325 		if (test_bit(Journal, &rdev->flags))
6326 			info.state |= (1<<MD_DISK_JOURNAL);
6327 		if (test_bit(WriteMostly, &rdev->flags))
6328 			info.state |= (1<<MD_DISK_WRITEMOSTLY);
6329 		if (test_bit(FailFast, &rdev->flags))
6330 			info.state |= (1<<MD_DISK_FAILFAST);
6331 	} else {
6332 		info.major = info.minor = 0;
6333 		info.raid_disk = -1;
6334 		info.state = (1<<MD_DISK_REMOVED);
6335 	}
6336 	rcu_read_unlock();
6337 
6338 	if (copy_to_user(arg, &info, sizeof(info)))
6339 		return -EFAULT;
6340 
6341 	return 0;
6342 }
6343 
6344 static int add_new_disk(struct mddev *mddev, mdu_disk_info_t *info)
6345 {
6346 	char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
6347 	struct md_rdev *rdev;
6348 	dev_t dev = MKDEV(info->major,info->minor);
6349 
6350 	if (mddev_is_clustered(mddev) &&
6351 		!(info->state & ((1 << MD_DISK_CLUSTER_ADD) | (1 << MD_DISK_CANDIDATE)))) {
6352 		pr_warn("%s: Cannot add to clustered mddev.\n",
6353 			mdname(mddev));
6354 		return -EINVAL;
6355 	}
6356 
6357 	if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
6358 		return -EOVERFLOW;
6359 
6360 	if (!mddev->raid_disks) {
6361 		int err;
6362 		/* expecting a device which has a superblock */
6363 		rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
6364 		if (IS_ERR(rdev)) {
6365 			pr_warn("md: md_import_device returned %ld\n",
6366 				PTR_ERR(rdev));
6367 			return PTR_ERR(rdev);
6368 		}
6369 		if (!list_empty(&mddev->disks)) {
6370 			struct md_rdev *rdev0
6371 				= list_entry(mddev->disks.next,
6372 					     struct md_rdev, same_set);
6373 			err = super_types[mddev->major_version]
6374 				.load_super(rdev, rdev0, mddev->minor_version);
6375 			if (err < 0) {
6376 				pr_warn("md: %s has different UUID to %s\n",
6377 					bdevname(rdev->bdev,b),
6378 					bdevname(rdev0->bdev,b2));
6379 				export_rdev(rdev);
6380 				return -EINVAL;
6381 			}
6382 		}
6383 		err = bind_rdev_to_array(rdev, mddev);
6384 		if (err)
6385 			export_rdev(rdev);
6386 		return err;
6387 	}
6388 
6389 	/*
6390 	 * add_new_disk can be used once the array is assembled
6391 	 * to add "hot spares".  They must already have a superblock
6392 	 * written
6393 	 */
6394 	if (mddev->pers) {
6395 		int err;
6396 		if (!mddev->pers->hot_add_disk) {
6397 			pr_warn("%s: personality does not support diskops!\n",
6398 				mdname(mddev));
6399 			return -EINVAL;
6400 		}
6401 		if (mddev->persistent)
6402 			rdev = md_import_device(dev, mddev->major_version,
6403 						mddev->minor_version);
6404 		else
6405 			rdev = md_import_device(dev, -1, -1);
6406 		if (IS_ERR(rdev)) {
6407 			pr_warn("md: md_import_device returned %ld\n",
6408 				PTR_ERR(rdev));
6409 			return PTR_ERR(rdev);
6410 		}
6411 		/* set saved_raid_disk if appropriate */
6412 		if (!mddev->persistent) {
6413 			if (info->state & (1<<MD_DISK_SYNC)  &&
6414 			    info->raid_disk < mddev->raid_disks) {
6415 				rdev->raid_disk = info->raid_disk;
6416 				set_bit(In_sync, &rdev->flags);
6417 				clear_bit(Bitmap_sync, &rdev->flags);
6418 			} else
6419 				rdev->raid_disk = -1;
6420 			rdev->saved_raid_disk = rdev->raid_disk;
6421 		} else
6422 			super_types[mddev->major_version].
6423 				validate_super(mddev, rdev);
6424 		if ((info->state & (1<<MD_DISK_SYNC)) &&
6425 		     rdev->raid_disk != info->raid_disk) {
6426 			/* This was a hot-add request, but events doesn't
6427 			 * match, so reject it.
6428 			 */
6429 			export_rdev(rdev);
6430 			return -EINVAL;
6431 		}
6432 
6433 		clear_bit(In_sync, &rdev->flags); /* just to be sure */
6434 		if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6435 			set_bit(WriteMostly, &rdev->flags);
6436 		else
6437 			clear_bit(WriteMostly, &rdev->flags);
6438 		if (info->state & (1<<MD_DISK_FAILFAST))
6439 			set_bit(FailFast, &rdev->flags);
6440 		else
6441 			clear_bit(FailFast, &rdev->flags);
6442 
6443 		if (info->state & (1<<MD_DISK_JOURNAL)) {
6444 			struct md_rdev *rdev2;
6445 			bool has_journal = false;
6446 
6447 			/* make sure no existing journal disk */
6448 			rdev_for_each(rdev2, mddev) {
6449 				if (test_bit(Journal, &rdev2->flags)) {
6450 					has_journal = true;
6451 					break;
6452 				}
6453 			}
6454 			if (has_journal || mddev->bitmap) {
6455 				export_rdev(rdev);
6456 				return -EBUSY;
6457 			}
6458 			set_bit(Journal, &rdev->flags);
6459 		}
6460 		/*
6461 		 * check whether the device shows up in other nodes
6462 		 */
6463 		if (mddev_is_clustered(mddev)) {
6464 			if (info->state & (1 << MD_DISK_CANDIDATE))
6465 				set_bit(Candidate, &rdev->flags);
6466 			else if (info->state & (1 << MD_DISK_CLUSTER_ADD)) {
6467 				/* --add initiated by this node */
6468 				err = md_cluster_ops->add_new_disk(mddev, rdev);
6469 				if (err) {
6470 					export_rdev(rdev);
6471 					return err;
6472 				}
6473 			}
6474 		}
6475 
6476 		rdev->raid_disk = -1;
6477 		err = bind_rdev_to_array(rdev, mddev);
6478 
6479 		if (err)
6480 			export_rdev(rdev);
6481 
6482 		if (mddev_is_clustered(mddev)) {
6483 			if (info->state & (1 << MD_DISK_CANDIDATE)) {
6484 				if (!err) {
6485 					err = md_cluster_ops->new_disk_ack(mddev,
6486 						err == 0);
6487 					if (err)
6488 						md_kick_rdev_from_array(rdev);
6489 				}
6490 			} else {
6491 				if (err)
6492 					md_cluster_ops->add_new_disk_cancel(mddev);
6493 				else
6494 					err = add_bound_rdev(rdev);
6495 			}
6496 
6497 		} else if (!err)
6498 			err = add_bound_rdev(rdev);
6499 
6500 		return err;
6501 	}
6502 
6503 	/* otherwise, add_new_disk is only allowed
6504 	 * for major_version==0 superblocks
6505 	 */
6506 	if (mddev->major_version != 0) {
6507 		pr_warn("%s: ADD_NEW_DISK not supported\n", mdname(mddev));
6508 		return -EINVAL;
6509 	}
6510 
6511 	if (!(info->state & (1<<MD_DISK_FAULTY))) {
6512 		int err;
6513 		rdev = md_import_device(dev, -1, 0);
6514 		if (IS_ERR(rdev)) {
6515 			pr_warn("md: error, md_import_device() returned %ld\n",
6516 				PTR_ERR(rdev));
6517 			return PTR_ERR(rdev);
6518 		}
6519 		rdev->desc_nr = info->number;
6520 		if (info->raid_disk < mddev->raid_disks)
6521 			rdev->raid_disk = info->raid_disk;
6522 		else
6523 			rdev->raid_disk = -1;
6524 
6525 		if (rdev->raid_disk < mddev->raid_disks)
6526 			if (info->state & (1<<MD_DISK_SYNC))
6527 				set_bit(In_sync, &rdev->flags);
6528 
6529 		if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6530 			set_bit(WriteMostly, &rdev->flags);
6531 		if (info->state & (1<<MD_DISK_FAILFAST))
6532 			set_bit(FailFast, &rdev->flags);
6533 
6534 		if (!mddev->persistent) {
6535 			pr_debug("md: nonpersistent superblock ...\n");
6536 			rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6537 		} else
6538 			rdev->sb_start = calc_dev_sboffset(rdev);
6539 		rdev->sectors = rdev->sb_start;
6540 
6541 		err = bind_rdev_to_array(rdev, mddev);
6542 		if (err) {
6543 			export_rdev(rdev);
6544 			return err;
6545 		}
6546 	}
6547 
6548 	return 0;
6549 }
6550 
6551 static int hot_remove_disk(struct mddev *mddev, dev_t dev)
6552 {
6553 	char b[BDEVNAME_SIZE];
6554 	struct md_rdev *rdev;
6555 
6556 	if (!mddev->pers)
6557 		return -ENODEV;
6558 
6559 	rdev = find_rdev(mddev, dev);
6560 	if (!rdev)
6561 		return -ENXIO;
6562 
6563 	if (rdev->raid_disk < 0)
6564 		goto kick_rdev;
6565 
6566 	clear_bit(Blocked, &rdev->flags);
6567 	remove_and_add_spares(mddev, rdev);
6568 
6569 	if (rdev->raid_disk >= 0)
6570 		goto busy;
6571 
6572 kick_rdev:
6573 	if (mddev_is_clustered(mddev))
6574 		md_cluster_ops->remove_disk(mddev, rdev);
6575 
6576 	md_kick_rdev_from_array(rdev);
6577 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6578 	if (mddev->thread)
6579 		md_wakeup_thread(mddev->thread);
6580 	else
6581 		md_update_sb(mddev, 1);
6582 	md_new_event(mddev);
6583 
6584 	return 0;
6585 busy:
6586 	pr_debug("md: cannot remove active disk %s from %s ...\n",
6587 		 bdevname(rdev->bdev,b), mdname(mddev));
6588 	return -EBUSY;
6589 }
6590 
6591 static int hot_add_disk(struct mddev *mddev, dev_t dev)
6592 {
6593 	char b[BDEVNAME_SIZE];
6594 	int err;
6595 	struct md_rdev *rdev;
6596 
6597 	if (!mddev->pers)
6598 		return -ENODEV;
6599 
6600 	if (mddev->major_version != 0) {
6601 		pr_warn("%s: HOT_ADD may only be used with version-0 superblocks.\n",
6602 			mdname(mddev));
6603 		return -EINVAL;
6604 	}
6605 	if (!mddev->pers->hot_add_disk) {
6606 		pr_warn("%s: personality does not support diskops!\n",
6607 			mdname(mddev));
6608 		return -EINVAL;
6609 	}
6610 
6611 	rdev = md_import_device(dev, -1, 0);
6612 	if (IS_ERR(rdev)) {
6613 		pr_warn("md: error, md_import_device() returned %ld\n",
6614 			PTR_ERR(rdev));
6615 		return -EINVAL;
6616 	}
6617 
6618 	if (mddev->persistent)
6619 		rdev->sb_start = calc_dev_sboffset(rdev);
6620 	else
6621 		rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6622 
6623 	rdev->sectors = rdev->sb_start;
6624 
6625 	if (test_bit(Faulty, &rdev->flags)) {
6626 		pr_warn("md: can not hot-add faulty %s disk to %s!\n",
6627 			bdevname(rdev->bdev,b), mdname(mddev));
6628 		err = -EINVAL;
6629 		goto abort_export;
6630 	}
6631 
6632 	clear_bit(In_sync, &rdev->flags);
6633 	rdev->desc_nr = -1;
6634 	rdev->saved_raid_disk = -1;
6635 	err = bind_rdev_to_array(rdev, mddev);
6636 	if (err)
6637 		goto abort_export;
6638 
6639 	/*
6640 	 * The rest should better be atomic, we can have disk failures
6641 	 * noticed in interrupt contexts ...
6642 	 */
6643 
6644 	rdev->raid_disk = -1;
6645 
6646 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6647 	if (!mddev->thread)
6648 		md_update_sb(mddev, 1);
6649 	/*
6650 	 * Kick recovery, maybe this spare has to be added to the
6651 	 * array immediately.
6652 	 */
6653 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6654 	md_wakeup_thread(mddev->thread);
6655 	md_new_event(mddev);
6656 	return 0;
6657 
6658 abort_export:
6659 	export_rdev(rdev);
6660 	return err;
6661 }
6662 
6663 static int set_bitmap_file(struct mddev *mddev, int fd)
6664 {
6665 	int err = 0;
6666 
6667 	if (mddev->pers) {
6668 		if (!mddev->pers->quiesce || !mddev->thread)
6669 			return -EBUSY;
6670 		if (mddev->recovery || mddev->sync_thread)
6671 			return -EBUSY;
6672 		/* we should be able to change the bitmap.. */
6673 	}
6674 
6675 	if (fd >= 0) {
6676 		struct inode *inode;
6677 		struct file *f;
6678 
6679 		if (mddev->bitmap || mddev->bitmap_info.file)
6680 			return -EEXIST; /* cannot add when bitmap is present */
6681 		f = fget(fd);
6682 
6683 		if (f == NULL) {
6684 			pr_warn("%s: error: failed to get bitmap file\n",
6685 				mdname(mddev));
6686 			return -EBADF;
6687 		}
6688 
6689 		inode = f->f_mapping->host;
6690 		if (!S_ISREG(inode->i_mode)) {
6691 			pr_warn("%s: error: bitmap file must be a regular file\n",
6692 				mdname(mddev));
6693 			err = -EBADF;
6694 		} else if (!(f->f_mode & FMODE_WRITE)) {
6695 			pr_warn("%s: error: bitmap file must open for write\n",
6696 				mdname(mddev));
6697 			err = -EBADF;
6698 		} else if (atomic_read(&inode->i_writecount) != 1) {
6699 			pr_warn("%s: error: bitmap file is already in use\n",
6700 				mdname(mddev));
6701 			err = -EBUSY;
6702 		}
6703 		if (err) {
6704 			fput(f);
6705 			return err;
6706 		}
6707 		mddev->bitmap_info.file = f;
6708 		mddev->bitmap_info.offset = 0; /* file overrides offset */
6709 	} else if (mddev->bitmap == NULL)
6710 		return -ENOENT; /* cannot remove what isn't there */
6711 	err = 0;
6712 	if (mddev->pers) {
6713 		if (fd >= 0) {
6714 			struct bitmap *bitmap;
6715 
6716 			bitmap = bitmap_create(mddev, -1);
6717 			mddev_suspend(mddev);
6718 			if (!IS_ERR(bitmap)) {
6719 				mddev->bitmap = bitmap;
6720 				err = bitmap_load(mddev);
6721 			} else
6722 				err = PTR_ERR(bitmap);
6723 			if (err) {
6724 				bitmap_destroy(mddev);
6725 				fd = -1;
6726 			}
6727 			mddev_resume(mddev);
6728 		} else if (fd < 0) {
6729 			mddev_suspend(mddev);
6730 			bitmap_destroy(mddev);
6731 			mddev_resume(mddev);
6732 		}
6733 	}
6734 	if (fd < 0) {
6735 		struct file *f = mddev->bitmap_info.file;
6736 		if (f) {
6737 			spin_lock(&mddev->lock);
6738 			mddev->bitmap_info.file = NULL;
6739 			spin_unlock(&mddev->lock);
6740 			fput(f);
6741 		}
6742 	}
6743 
6744 	return err;
6745 }
6746 
6747 /*
6748  * set_array_info is used two different ways
6749  * The original usage is when creating a new array.
6750  * In this usage, raid_disks is > 0 and it together with
6751  *  level, size, not_persistent,layout,chunksize determine the
6752  *  shape of the array.
6753  *  This will always create an array with a type-0.90.0 superblock.
6754  * The newer usage is when assembling an array.
6755  *  In this case raid_disks will be 0, and the major_version field is
6756  *  use to determine which style super-blocks are to be found on the devices.
6757  *  The minor and patch _version numbers are also kept incase the
6758  *  super_block handler wishes to interpret them.
6759  */
6760 static int set_array_info(struct mddev *mddev, mdu_array_info_t *info)
6761 {
6762 
6763 	if (info->raid_disks == 0) {
6764 		/* just setting version number for superblock loading */
6765 		if (info->major_version < 0 ||
6766 		    info->major_version >= ARRAY_SIZE(super_types) ||
6767 		    super_types[info->major_version].name == NULL) {
6768 			/* maybe try to auto-load a module? */
6769 			pr_warn("md: superblock version %d not known\n",
6770 				info->major_version);
6771 			return -EINVAL;
6772 		}
6773 		mddev->major_version = info->major_version;
6774 		mddev->minor_version = info->minor_version;
6775 		mddev->patch_version = info->patch_version;
6776 		mddev->persistent = !info->not_persistent;
6777 		/* ensure mddev_put doesn't delete this now that there
6778 		 * is some minimal configuration.
6779 		 */
6780 		mddev->ctime         = ktime_get_real_seconds();
6781 		return 0;
6782 	}
6783 	mddev->major_version = MD_MAJOR_VERSION;
6784 	mddev->minor_version = MD_MINOR_VERSION;
6785 	mddev->patch_version = MD_PATCHLEVEL_VERSION;
6786 	mddev->ctime         = ktime_get_real_seconds();
6787 
6788 	mddev->level         = info->level;
6789 	mddev->clevel[0]     = 0;
6790 	mddev->dev_sectors   = 2 * (sector_t)info->size;
6791 	mddev->raid_disks    = info->raid_disks;
6792 	/* don't set md_minor, it is determined by which /dev/md* was
6793 	 * openned
6794 	 */
6795 	if (info->state & (1<<MD_SB_CLEAN))
6796 		mddev->recovery_cp = MaxSector;
6797 	else
6798 		mddev->recovery_cp = 0;
6799 	mddev->persistent    = ! info->not_persistent;
6800 	mddev->external	     = 0;
6801 
6802 	mddev->layout        = info->layout;
6803 	mddev->chunk_sectors = info->chunk_size >> 9;
6804 
6805 	if (mddev->persistent) {
6806 		mddev->max_disks = MD_SB_DISKS;
6807 		mddev->flags = 0;
6808 		mddev->sb_flags = 0;
6809 	}
6810 	set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6811 
6812 	mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6813 	mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6814 	mddev->bitmap_info.offset = 0;
6815 
6816 	mddev->reshape_position = MaxSector;
6817 
6818 	/*
6819 	 * Generate a 128 bit UUID
6820 	 */
6821 	get_random_bytes(mddev->uuid, 16);
6822 
6823 	mddev->new_level = mddev->level;
6824 	mddev->new_chunk_sectors = mddev->chunk_sectors;
6825 	mddev->new_layout = mddev->layout;
6826 	mddev->delta_disks = 0;
6827 	mddev->reshape_backwards = 0;
6828 
6829 	return 0;
6830 }
6831 
6832 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6833 {
6834 	lockdep_assert_held(&mddev->reconfig_mutex);
6835 
6836 	if (mddev->external_size)
6837 		return;
6838 
6839 	mddev->array_sectors = array_sectors;
6840 }
6841 EXPORT_SYMBOL(md_set_array_sectors);
6842 
6843 static int update_size(struct mddev *mddev, sector_t num_sectors)
6844 {
6845 	struct md_rdev *rdev;
6846 	int rv;
6847 	int fit = (num_sectors == 0);
6848 	sector_t old_dev_sectors = mddev->dev_sectors;
6849 
6850 	if (mddev->pers->resize == NULL)
6851 		return -EINVAL;
6852 	/* The "num_sectors" is the number of sectors of each device that
6853 	 * is used.  This can only make sense for arrays with redundancy.
6854 	 * linear and raid0 always use whatever space is available. We can only
6855 	 * consider changing this number if no resync or reconstruction is
6856 	 * happening, and if the new size is acceptable. It must fit before the
6857 	 * sb_start or, if that is <data_offset, it must fit before the size
6858 	 * of each device.  If num_sectors is zero, we find the largest size
6859 	 * that fits.
6860 	 */
6861 	if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6862 	    mddev->sync_thread)
6863 		return -EBUSY;
6864 	if (mddev->ro)
6865 		return -EROFS;
6866 
6867 	rdev_for_each(rdev, mddev) {
6868 		sector_t avail = rdev->sectors;
6869 
6870 		if (fit && (num_sectors == 0 || num_sectors > avail))
6871 			num_sectors = avail;
6872 		if (avail < num_sectors)
6873 			return -ENOSPC;
6874 	}
6875 	rv = mddev->pers->resize(mddev, num_sectors);
6876 	if (!rv) {
6877 		if (mddev_is_clustered(mddev))
6878 			md_cluster_ops->update_size(mddev, old_dev_sectors);
6879 		else if (mddev->queue) {
6880 			set_capacity(mddev->gendisk, mddev->array_sectors);
6881 			revalidate_disk(mddev->gendisk);
6882 		}
6883 	}
6884 	return rv;
6885 }
6886 
6887 static int update_raid_disks(struct mddev *mddev, int raid_disks)
6888 {
6889 	int rv;
6890 	struct md_rdev *rdev;
6891 	/* change the number of raid disks */
6892 	if (mddev->pers->check_reshape == NULL)
6893 		return -EINVAL;
6894 	if (mddev->ro)
6895 		return -EROFS;
6896 	if (raid_disks <= 0 ||
6897 	    (mddev->max_disks && raid_disks >= mddev->max_disks))
6898 		return -EINVAL;
6899 	if (mddev->sync_thread ||
6900 	    test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6901 	    mddev->reshape_position != MaxSector)
6902 		return -EBUSY;
6903 
6904 	rdev_for_each(rdev, mddev) {
6905 		if (mddev->raid_disks < raid_disks &&
6906 		    rdev->data_offset < rdev->new_data_offset)
6907 			return -EINVAL;
6908 		if (mddev->raid_disks > raid_disks &&
6909 		    rdev->data_offset > rdev->new_data_offset)
6910 			return -EINVAL;
6911 	}
6912 
6913 	mddev->delta_disks = raid_disks - mddev->raid_disks;
6914 	if (mddev->delta_disks < 0)
6915 		mddev->reshape_backwards = 1;
6916 	else if (mddev->delta_disks > 0)
6917 		mddev->reshape_backwards = 0;
6918 
6919 	rv = mddev->pers->check_reshape(mddev);
6920 	if (rv < 0) {
6921 		mddev->delta_disks = 0;
6922 		mddev->reshape_backwards = 0;
6923 	}
6924 	return rv;
6925 }
6926 
6927 /*
6928  * update_array_info is used to change the configuration of an
6929  * on-line array.
6930  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
6931  * fields in the info are checked against the array.
6932  * Any differences that cannot be handled will cause an error.
6933  * Normally, only one change can be managed at a time.
6934  */
6935 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
6936 {
6937 	int rv = 0;
6938 	int cnt = 0;
6939 	int state = 0;
6940 
6941 	/* calculate expected state,ignoring low bits */
6942 	if (mddev->bitmap && mddev->bitmap_info.offset)
6943 		state |= (1 << MD_SB_BITMAP_PRESENT);
6944 
6945 	if (mddev->major_version != info->major_version ||
6946 	    mddev->minor_version != info->minor_version ||
6947 /*	    mddev->patch_version != info->patch_version || */
6948 	    mddev->ctime         != info->ctime         ||
6949 	    mddev->level         != info->level         ||
6950 /*	    mddev->layout        != info->layout        || */
6951 	    mddev->persistent	 != !info->not_persistent ||
6952 	    mddev->chunk_sectors != info->chunk_size >> 9 ||
6953 	    /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6954 	    ((state^info->state) & 0xfffffe00)
6955 		)
6956 		return -EINVAL;
6957 	/* Check there is only one change */
6958 	if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6959 		cnt++;
6960 	if (mddev->raid_disks != info->raid_disks)
6961 		cnt++;
6962 	if (mddev->layout != info->layout)
6963 		cnt++;
6964 	if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6965 		cnt++;
6966 	if (cnt == 0)
6967 		return 0;
6968 	if (cnt > 1)
6969 		return -EINVAL;
6970 
6971 	if (mddev->layout != info->layout) {
6972 		/* Change layout
6973 		 * we don't need to do anything at the md level, the
6974 		 * personality will take care of it all.
6975 		 */
6976 		if (mddev->pers->check_reshape == NULL)
6977 			return -EINVAL;
6978 		else {
6979 			mddev->new_layout = info->layout;
6980 			rv = mddev->pers->check_reshape(mddev);
6981 			if (rv)
6982 				mddev->new_layout = mddev->layout;
6983 			return rv;
6984 		}
6985 	}
6986 	if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6987 		rv = update_size(mddev, (sector_t)info->size * 2);
6988 
6989 	if (mddev->raid_disks    != info->raid_disks)
6990 		rv = update_raid_disks(mddev, info->raid_disks);
6991 
6992 	if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6993 		if (mddev->pers->quiesce == NULL || mddev->thread == NULL) {
6994 			rv = -EINVAL;
6995 			goto err;
6996 		}
6997 		if (mddev->recovery || mddev->sync_thread) {
6998 			rv = -EBUSY;
6999 			goto err;
7000 		}
7001 		if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
7002 			struct bitmap *bitmap;
7003 			/* add the bitmap */
7004 			if (mddev->bitmap) {
7005 				rv = -EEXIST;
7006 				goto err;
7007 			}
7008 			if (mddev->bitmap_info.default_offset == 0) {
7009 				rv = -EINVAL;
7010 				goto err;
7011 			}
7012 			mddev->bitmap_info.offset =
7013 				mddev->bitmap_info.default_offset;
7014 			mddev->bitmap_info.space =
7015 				mddev->bitmap_info.default_space;
7016 			bitmap = bitmap_create(mddev, -1);
7017 			mddev_suspend(mddev);
7018 			if (!IS_ERR(bitmap)) {
7019 				mddev->bitmap = bitmap;
7020 				rv = bitmap_load(mddev);
7021 			} else
7022 				rv = PTR_ERR(bitmap);
7023 			if (rv)
7024 				bitmap_destroy(mddev);
7025 			mddev_resume(mddev);
7026 		} else {
7027 			/* remove the bitmap */
7028 			if (!mddev->bitmap) {
7029 				rv = -ENOENT;
7030 				goto err;
7031 			}
7032 			if (mddev->bitmap->storage.file) {
7033 				rv = -EINVAL;
7034 				goto err;
7035 			}
7036 			if (mddev->bitmap_info.nodes) {
7037 				/* hold PW on all the bitmap lock */
7038 				if (md_cluster_ops->lock_all_bitmaps(mddev) <= 0) {
7039 					pr_warn("md: can't change bitmap to none since the array is in use by more than one node\n");
7040 					rv = -EPERM;
7041 					md_cluster_ops->unlock_all_bitmaps(mddev);
7042 					goto err;
7043 				}
7044 
7045 				mddev->bitmap_info.nodes = 0;
7046 				md_cluster_ops->leave(mddev);
7047 			}
7048 			mddev_suspend(mddev);
7049 			bitmap_destroy(mddev);
7050 			mddev_resume(mddev);
7051 			mddev->bitmap_info.offset = 0;
7052 		}
7053 	}
7054 	md_update_sb(mddev, 1);
7055 	return rv;
7056 err:
7057 	return rv;
7058 }
7059 
7060 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
7061 {
7062 	struct md_rdev *rdev;
7063 	int err = 0;
7064 
7065 	if (mddev->pers == NULL)
7066 		return -ENODEV;
7067 
7068 	rcu_read_lock();
7069 	rdev = md_find_rdev_rcu(mddev, dev);
7070 	if (!rdev)
7071 		err =  -ENODEV;
7072 	else {
7073 		md_error(mddev, rdev);
7074 		if (!test_bit(Faulty, &rdev->flags))
7075 			err = -EBUSY;
7076 	}
7077 	rcu_read_unlock();
7078 	return err;
7079 }
7080 
7081 /*
7082  * We have a problem here : there is no easy way to give a CHS
7083  * virtual geometry. We currently pretend that we have a 2 heads
7084  * 4 sectors (with a BIG number of cylinders...). This drives
7085  * dosfs just mad... ;-)
7086  */
7087 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
7088 {
7089 	struct mddev *mddev = bdev->bd_disk->private_data;
7090 
7091 	geo->heads = 2;
7092 	geo->sectors = 4;
7093 	geo->cylinders = mddev->array_sectors / 8;
7094 	return 0;
7095 }
7096 
7097 static inline bool md_ioctl_valid(unsigned int cmd)
7098 {
7099 	switch (cmd) {
7100 	case ADD_NEW_DISK:
7101 	case BLKROSET:
7102 	case GET_ARRAY_INFO:
7103 	case GET_BITMAP_FILE:
7104 	case GET_DISK_INFO:
7105 	case HOT_ADD_DISK:
7106 	case HOT_REMOVE_DISK:
7107 	case RAID_AUTORUN:
7108 	case RAID_VERSION:
7109 	case RESTART_ARRAY_RW:
7110 	case RUN_ARRAY:
7111 	case SET_ARRAY_INFO:
7112 	case SET_BITMAP_FILE:
7113 	case SET_DISK_FAULTY:
7114 	case STOP_ARRAY:
7115 	case STOP_ARRAY_RO:
7116 	case CLUSTERED_DISK_NACK:
7117 		return true;
7118 	default:
7119 		return false;
7120 	}
7121 }
7122 
7123 static int md_ioctl(struct block_device *bdev, fmode_t mode,
7124 			unsigned int cmd, unsigned long arg)
7125 {
7126 	int err = 0;
7127 	void __user *argp = (void __user *)arg;
7128 	struct mddev *mddev = NULL;
7129 	int ro;
7130 	bool did_set_md_closing = false;
7131 
7132 	if (!md_ioctl_valid(cmd))
7133 		return -ENOTTY;
7134 
7135 	switch (cmd) {
7136 	case RAID_VERSION:
7137 	case GET_ARRAY_INFO:
7138 	case GET_DISK_INFO:
7139 		break;
7140 	default:
7141 		if (!capable(CAP_SYS_ADMIN))
7142 			return -EACCES;
7143 	}
7144 
7145 	/*
7146 	 * Commands dealing with the RAID driver but not any
7147 	 * particular array:
7148 	 */
7149 	switch (cmd) {
7150 	case RAID_VERSION:
7151 		err = get_version(argp);
7152 		goto out;
7153 
7154 #ifndef MODULE
7155 	case RAID_AUTORUN:
7156 		err = 0;
7157 		autostart_arrays(arg);
7158 		goto out;
7159 #endif
7160 	default:;
7161 	}
7162 
7163 	/*
7164 	 * Commands creating/starting a new array:
7165 	 */
7166 
7167 	mddev = bdev->bd_disk->private_data;
7168 
7169 	if (!mddev) {
7170 		BUG();
7171 		goto out;
7172 	}
7173 
7174 	/* Some actions do not requires the mutex */
7175 	switch (cmd) {
7176 	case GET_ARRAY_INFO:
7177 		if (!mddev->raid_disks && !mddev->external)
7178 			err = -ENODEV;
7179 		else
7180 			err = get_array_info(mddev, argp);
7181 		goto out;
7182 
7183 	case GET_DISK_INFO:
7184 		if (!mddev->raid_disks && !mddev->external)
7185 			err = -ENODEV;
7186 		else
7187 			err = get_disk_info(mddev, argp);
7188 		goto out;
7189 
7190 	case SET_DISK_FAULTY:
7191 		err = set_disk_faulty(mddev, new_decode_dev(arg));
7192 		goto out;
7193 
7194 	case GET_BITMAP_FILE:
7195 		err = get_bitmap_file(mddev, argp);
7196 		goto out;
7197 
7198 	}
7199 
7200 	if (cmd == ADD_NEW_DISK)
7201 		/* need to ensure md_delayed_delete() has completed */
7202 		flush_workqueue(md_misc_wq);
7203 
7204 	if (cmd == HOT_REMOVE_DISK)
7205 		/* need to ensure recovery thread has run */
7206 		wait_event_interruptible_timeout(mddev->sb_wait,
7207 						 !test_bit(MD_RECOVERY_NEEDED,
7208 							   &mddev->recovery),
7209 						 msecs_to_jiffies(5000));
7210 	if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
7211 		/* Need to flush page cache, and ensure no-one else opens
7212 		 * and writes
7213 		 */
7214 		mutex_lock(&mddev->open_mutex);
7215 		if (mddev->pers && atomic_read(&mddev->openers) > 1) {
7216 			mutex_unlock(&mddev->open_mutex);
7217 			err = -EBUSY;
7218 			goto out;
7219 		}
7220 		WARN_ON_ONCE(test_bit(MD_CLOSING, &mddev->flags));
7221 		set_bit(MD_CLOSING, &mddev->flags);
7222 		did_set_md_closing = true;
7223 		mutex_unlock(&mddev->open_mutex);
7224 		sync_blockdev(bdev);
7225 	}
7226 	err = mddev_lock(mddev);
7227 	if (err) {
7228 		pr_debug("md: ioctl lock interrupted, reason %d, cmd %d\n",
7229 			 err, cmd);
7230 		goto out;
7231 	}
7232 
7233 	if (cmd == SET_ARRAY_INFO) {
7234 		mdu_array_info_t info;
7235 		if (!arg)
7236 			memset(&info, 0, sizeof(info));
7237 		else if (copy_from_user(&info, argp, sizeof(info))) {
7238 			err = -EFAULT;
7239 			goto unlock;
7240 		}
7241 		if (mddev->pers) {
7242 			err = update_array_info(mddev, &info);
7243 			if (err) {
7244 				pr_warn("md: couldn't update array info. %d\n", err);
7245 				goto unlock;
7246 			}
7247 			goto unlock;
7248 		}
7249 		if (!list_empty(&mddev->disks)) {
7250 			pr_warn("md: array %s already has disks!\n", mdname(mddev));
7251 			err = -EBUSY;
7252 			goto unlock;
7253 		}
7254 		if (mddev->raid_disks) {
7255 			pr_warn("md: array %s already initialised!\n", mdname(mddev));
7256 			err = -EBUSY;
7257 			goto unlock;
7258 		}
7259 		err = set_array_info(mddev, &info);
7260 		if (err) {
7261 			pr_warn("md: couldn't set array info. %d\n", err);
7262 			goto unlock;
7263 		}
7264 		goto unlock;
7265 	}
7266 
7267 	/*
7268 	 * Commands querying/configuring an existing array:
7269 	 */
7270 	/* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
7271 	 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
7272 	if ((!mddev->raid_disks && !mddev->external)
7273 	    && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
7274 	    && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
7275 	    && cmd != GET_BITMAP_FILE) {
7276 		err = -ENODEV;
7277 		goto unlock;
7278 	}
7279 
7280 	/*
7281 	 * Commands even a read-only array can execute:
7282 	 */
7283 	switch (cmd) {
7284 	case RESTART_ARRAY_RW:
7285 		err = restart_array(mddev);
7286 		goto unlock;
7287 
7288 	case STOP_ARRAY:
7289 		err = do_md_stop(mddev, 0, bdev);
7290 		goto unlock;
7291 
7292 	case STOP_ARRAY_RO:
7293 		err = md_set_readonly(mddev, bdev);
7294 		goto unlock;
7295 
7296 	case HOT_REMOVE_DISK:
7297 		err = hot_remove_disk(mddev, new_decode_dev(arg));
7298 		goto unlock;
7299 
7300 	case ADD_NEW_DISK:
7301 		/* We can support ADD_NEW_DISK on read-only arrays
7302 		 * only if we are re-adding a preexisting device.
7303 		 * So require mddev->pers and MD_DISK_SYNC.
7304 		 */
7305 		if (mddev->pers) {
7306 			mdu_disk_info_t info;
7307 			if (copy_from_user(&info, argp, sizeof(info)))
7308 				err = -EFAULT;
7309 			else if (!(info.state & (1<<MD_DISK_SYNC)))
7310 				/* Need to clear read-only for this */
7311 				break;
7312 			else
7313 				err = add_new_disk(mddev, &info);
7314 			goto unlock;
7315 		}
7316 		break;
7317 
7318 	case BLKROSET:
7319 		if (get_user(ro, (int __user *)(arg))) {
7320 			err = -EFAULT;
7321 			goto unlock;
7322 		}
7323 		err = -EINVAL;
7324 
7325 		/* if the bdev is going readonly the value of mddev->ro
7326 		 * does not matter, no writes are coming
7327 		 */
7328 		if (ro)
7329 			goto unlock;
7330 
7331 		/* are we are already prepared for writes? */
7332 		if (mddev->ro != 1)
7333 			goto unlock;
7334 
7335 		/* transitioning to readauto need only happen for
7336 		 * arrays that call md_write_start
7337 		 */
7338 		if (mddev->pers) {
7339 			err = restart_array(mddev);
7340 			if (err == 0) {
7341 				mddev->ro = 2;
7342 				set_disk_ro(mddev->gendisk, 0);
7343 			}
7344 		}
7345 		goto unlock;
7346 	}
7347 
7348 	/*
7349 	 * The remaining ioctls are changing the state of the
7350 	 * superblock, so we do not allow them on read-only arrays.
7351 	 */
7352 	if (mddev->ro && mddev->pers) {
7353 		if (mddev->ro == 2) {
7354 			mddev->ro = 0;
7355 			sysfs_notify_dirent_safe(mddev->sysfs_state);
7356 			set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7357 			/* mddev_unlock will wake thread */
7358 			/* If a device failed while we were read-only, we
7359 			 * need to make sure the metadata is updated now.
7360 			 */
7361 			if (test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)) {
7362 				mddev_unlock(mddev);
7363 				wait_event(mddev->sb_wait,
7364 					   !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags) &&
7365 					   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
7366 				mddev_lock_nointr(mddev);
7367 			}
7368 		} else {
7369 			err = -EROFS;
7370 			goto unlock;
7371 		}
7372 	}
7373 
7374 	switch (cmd) {
7375 	case ADD_NEW_DISK:
7376 	{
7377 		mdu_disk_info_t info;
7378 		if (copy_from_user(&info, argp, sizeof(info)))
7379 			err = -EFAULT;
7380 		else
7381 			err = add_new_disk(mddev, &info);
7382 		goto unlock;
7383 	}
7384 
7385 	case CLUSTERED_DISK_NACK:
7386 		if (mddev_is_clustered(mddev))
7387 			md_cluster_ops->new_disk_ack(mddev, false);
7388 		else
7389 			err = -EINVAL;
7390 		goto unlock;
7391 
7392 	case HOT_ADD_DISK:
7393 		err = hot_add_disk(mddev, new_decode_dev(arg));
7394 		goto unlock;
7395 
7396 	case RUN_ARRAY:
7397 		err = do_md_run(mddev);
7398 		goto unlock;
7399 
7400 	case SET_BITMAP_FILE:
7401 		err = set_bitmap_file(mddev, (int)arg);
7402 		goto unlock;
7403 
7404 	default:
7405 		err = -EINVAL;
7406 		goto unlock;
7407 	}
7408 
7409 unlock:
7410 	if (mddev->hold_active == UNTIL_IOCTL &&
7411 	    err != -EINVAL)
7412 		mddev->hold_active = 0;
7413 	mddev_unlock(mddev);
7414 out:
7415 	if(did_set_md_closing)
7416 		clear_bit(MD_CLOSING, &mddev->flags);
7417 	return err;
7418 }
7419 #ifdef CONFIG_COMPAT
7420 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
7421 		    unsigned int cmd, unsigned long arg)
7422 {
7423 	switch (cmd) {
7424 	case HOT_REMOVE_DISK:
7425 	case HOT_ADD_DISK:
7426 	case SET_DISK_FAULTY:
7427 	case SET_BITMAP_FILE:
7428 		/* These take in integer arg, do not convert */
7429 		break;
7430 	default:
7431 		arg = (unsigned long)compat_ptr(arg);
7432 		break;
7433 	}
7434 
7435 	return md_ioctl(bdev, mode, cmd, arg);
7436 }
7437 #endif /* CONFIG_COMPAT */
7438 
7439 static int md_open(struct block_device *bdev, fmode_t mode)
7440 {
7441 	/*
7442 	 * Succeed if we can lock the mddev, which confirms that
7443 	 * it isn't being stopped right now.
7444 	 */
7445 	struct mddev *mddev = mddev_find(bdev->bd_dev);
7446 	int err;
7447 
7448 	if (!mddev)
7449 		return -ENODEV;
7450 
7451 	if (mddev->gendisk != bdev->bd_disk) {
7452 		/* we are racing with mddev_put which is discarding this
7453 		 * bd_disk.
7454 		 */
7455 		mddev_put(mddev);
7456 		/* Wait until bdev->bd_disk is definitely gone */
7457 		flush_workqueue(md_misc_wq);
7458 		/* Then retry the open from the top */
7459 		return -ERESTARTSYS;
7460 	}
7461 	BUG_ON(mddev != bdev->bd_disk->private_data);
7462 
7463 	if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
7464 		goto out;
7465 
7466 	if (test_bit(MD_CLOSING, &mddev->flags)) {
7467 		mutex_unlock(&mddev->open_mutex);
7468 		err = -ENODEV;
7469 		goto out;
7470 	}
7471 
7472 	err = 0;
7473 	atomic_inc(&mddev->openers);
7474 	mutex_unlock(&mddev->open_mutex);
7475 
7476 	check_disk_change(bdev);
7477  out:
7478 	if (err)
7479 		mddev_put(mddev);
7480 	return err;
7481 }
7482 
7483 static void md_release(struct gendisk *disk, fmode_t mode)
7484 {
7485 	struct mddev *mddev = disk->private_data;
7486 
7487 	BUG_ON(!mddev);
7488 	atomic_dec(&mddev->openers);
7489 	mddev_put(mddev);
7490 }
7491 
7492 static int md_media_changed(struct gendisk *disk)
7493 {
7494 	struct mddev *mddev = disk->private_data;
7495 
7496 	return mddev->changed;
7497 }
7498 
7499 static int md_revalidate(struct gendisk *disk)
7500 {
7501 	struct mddev *mddev = disk->private_data;
7502 
7503 	mddev->changed = 0;
7504 	return 0;
7505 }
7506 static const struct block_device_operations md_fops =
7507 {
7508 	.owner		= THIS_MODULE,
7509 	.open		= md_open,
7510 	.release	= md_release,
7511 	.ioctl		= md_ioctl,
7512 #ifdef CONFIG_COMPAT
7513 	.compat_ioctl	= md_compat_ioctl,
7514 #endif
7515 	.getgeo		= md_getgeo,
7516 	.media_changed  = md_media_changed,
7517 	.revalidate_disk= md_revalidate,
7518 };
7519 
7520 static int md_thread(void *arg)
7521 {
7522 	struct md_thread *thread = arg;
7523 
7524 	/*
7525 	 * md_thread is a 'system-thread', it's priority should be very
7526 	 * high. We avoid resource deadlocks individually in each
7527 	 * raid personality. (RAID5 does preallocation) We also use RR and
7528 	 * the very same RT priority as kswapd, thus we will never get
7529 	 * into a priority inversion deadlock.
7530 	 *
7531 	 * we definitely have to have equal or higher priority than
7532 	 * bdflush, otherwise bdflush will deadlock if there are too
7533 	 * many dirty RAID5 blocks.
7534 	 */
7535 
7536 	allow_signal(SIGKILL);
7537 	while (!kthread_should_stop()) {
7538 
7539 		/* We need to wait INTERRUPTIBLE so that
7540 		 * we don't add to the load-average.
7541 		 * That means we need to be sure no signals are
7542 		 * pending
7543 		 */
7544 		if (signal_pending(current))
7545 			flush_signals(current);
7546 
7547 		wait_event_interruptible_timeout
7548 			(thread->wqueue,
7549 			 test_bit(THREAD_WAKEUP, &thread->flags)
7550 			 || kthread_should_stop() || kthread_should_park(),
7551 			 thread->timeout);
7552 
7553 		clear_bit(THREAD_WAKEUP, &thread->flags);
7554 		if (kthread_should_park())
7555 			kthread_parkme();
7556 		if (!kthread_should_stop())
7557 			thread->run(thread);
7558 	}
7559 
7560 	return 0;
7561 }
7562 
7563 void md_wakeup_thread(struct md_thread *thread)
7564 {
7565 	if (thread) {
7566 		pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
7567 		set_bit(THREAD_WAKEUP, &thread->flags);
7568 		wake_up(&thread->wqueue);
7569 	}
7570 }
7571 EXPORT_SYMBOL(md_wakeup_thread);
7572 
7573 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
7574 		struct mddev *mddev, const char *name)
7575 {
7576 	struct md_thread *thread;
7577 
7578 	thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
7579 	if (!thread)
7580 		return NULL;
7581 
7582 	init_waitqueue_head(&thread->wqueue);
7583 
7584 	thread->run = run;
7585 	thread->mddev = mddev;
7586 	thread->timeout = MAX_SCHEDULE_TIMEOUT;
7587 	thread->tsk = kthread_run(md_thread, thread,
7588 				  "%s_%s",
7589 				  mdname(thread->mddev),
7590 				  name);
7591 	if (IS_ERR(thread->tsk)) {
7592 		kfree(thread);
7593 		return NULL;
7594 	}
7595 	return thread;
7596 }
7597 EXPORT_SYMBOL(md_register_thread);
7598 
7599 void md_unregister_thread(struct md_thread **threadp)
7600 {
7601 	struct md_thread *thread = *threadp;
7602 	if (!thread)
7603 		return;
7604 	pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
7605 	/* Locking ensures that mddev_unlock does not wake_up a
7606 	 * non-existent thread
7607 	 */
7608 	spin_lock(&pers_lock);
7609 	*threadp = NULL;
7610 	spin_unlock(&pers_lock);
7611 
7612 	kthread_stop(thread->tsk);
7613 	kfree(thread);
7614 }
7615 EXPORT_SYMBOL(md_unregister_thread);
7616 
7617 void md_error(struct mddev *mddev, struct md_rdev *rdev)
7618 {
7619 	if (!rdev || test_bit(Faulty, &rdev->flags))
7620 		return;
7621 
7622 	if (!mddev->pers || !mddev->pers->error_handler)
7623 		return;
7624 	mddev->pers->error_handler(mddev,rdev);
7625 	if (mddev->degraded)
7626 		set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7627 	sysfs_notify_dirent_safe(rdev->sysfs_state);
7628 	set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7629 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7630 	md_wakeup_thread(mddev->thread);
7631 	if (mddev->event_work.func)
7632 		queue_work(md_misc_wq, &mddev->event_work);
7633 	md_new_event(mddev);
7634 }
7635 EXPORT_SYMBOL(md_error);
7636 
7637 /* seq_file implementation /proc/mdstat */
7638 
7639 static void status_unused(struct seq_file *seq)
7640 {
7641 	int i = 0;
7642 	struct md_rdev *rdev;
7643 
7644 	seq_printf(seq, "unused devices: ");
7645 
7646 	list_for_each_entry(rdev, &pending_raid_disks, same_set) {
7647 		char b[BDEVNAME_SIZE];
7648 		i++;
7649 		seq_printf(seq, "%s ",
7650 			      bdevname(rdev->bdev,b));
7651 	}
7652 	if (!i)
7653 		seq_printf(seq, "<none>");
7654 
7655 	seq_printf(seq, "\n");
7656 }
7657 
7658 static int status_resync(struct seq_file *seq, struct mddev *mddev)
7659 {
7660 	sector_t max_sectors, resync, res;
7661 	unsigned long dt, db;
7662 	sector_t rt;
7663 	int scale;
7664 	unsigned int per_milli;
7665 
7666 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
7667 	    test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7668 		max_sectors = mddev->resync_max_sectors;
7669 	else
7670 		max_sectors = mddev->dev_sectors;
7671 
7672 	resync = mddev->curr_resync;
7673 	if (resync <= 3) {
7674 		if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7675 			/* Still cleaning up */
7676 			resync = max_sectors;
7677 	} else if (resync > max_sectors)
7678 		resync = max_sectors;
7679 	else
7680 		resync -= atomic_read(&mddev->recovery_active);
7681 
7682 	if (resync == 0) {
7683 		if (mddev->recovery_cp < MaxSector) {
7684 			seq_printf(seq, "\tresync=PENDING");
7685 			return 1;
7686 		}
7687 		return 0;
7688 	}
7689 	if (resync < 3) {
7690 		seq_printf(seq, "\tresync=DELAYED");
7691 		return 1;
7692 	}
7693 
7694 	WARN_ON(max_sectors == 0);
7695 	/* Pick 'scale' such that (resync>>scale)*1000 will fit
7696 	 * in a sector_t, and (max_sectors>>scale) will fit in a
7697 	 * u32, as those are the requirements for sector_div.
7698 	 * Thus 'scale' must be at least 10
7699 	 */
7700 	scale = 10;
7701 	if (sizeof(sector_t) > sizeof(unsigned long)) {
7702 		while ( max_sectors/2 > (1ULL<<(scale+32)))
7703 			scale++;
7704 	}
7705 	res = (resync>>scale)*1000;
7706 	sector_div(res, (u32)((max_sectors>>scale)+1));
7707 
7708 	per_milli = res;
7709 	{
7710 		int i, x = per_milli/50, y = 20-x;
7711 		seq_printf(seq, "[");
7712 		for (i = 0; i < x; i++)
7713 			seq_printf(seq, "=");
7714 		seq_printf(seq, ">");
7715 		for (i = 0; i < y; i++)
7716 			seq_printf(seq, ".");
7717 		seq_printf(seq, "] ");
7718 	}
7719 	seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
7720 		   (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
7721 		    "reshape" :
7722 		    (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
7723 		     "check" :
7724 		     (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
7725 		      "resync" : "recovery"))),
7726 		   per_milli/10, per_milli % 10,
7727 		   (unsigned long long) resync/2,
7728 		   (unsigned long long) max_sectors/2);
7729 
7730 	/*
7731 	 * dt: time from mark until now
7732 	 * db: blocks written from mark until now
7733 	 * rt: remaining time
7734 	 *
7735 	 * rt is a sector_t, so could be 32bit or 64bit.
7736 	 * So we divide before multiply in case it is 32bit and close
7737 	 * to the limit.
7738 	 * We scale the divisor (db) by 32 to avoid losing precision
7739 	 * near the end of resync when the number of remaining sectors
7740 	 * is close to 'db'.
7741 	 * We then divide rt by 32 after multiplying by db to compensate.
7742 	 * The '+1' avoids division by zero if db is very small.
7743 	 */
7744 	dt = ((jiffies - mddev->resync_mark) / HZ);
7745 	if (!dt) dt++;
7746 	db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
7747 		- mddev->resync_mark_cnt;
7748 
7749 	rt = max_sectors - resync;    /* number of remaining sectors */
7750 	sector_div(rt, db/32+1);
7751 	rt *= dt;
7752 	rt >>= 5;
7753 
7754 	seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
7755 		   ((unsigned long)rt % 60)/6);
7756 
7757 	seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7758 	return 1;
7759 }
7760 
7761 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7762 {
7763 	struct list_head *tmp;
7764 	loff_t l = *pos;
7765 	struct mddev *mddev;
7766 
7767 	if (l >= 0x10000)
7768 		return NULL;
7769 	if (!l--)
7770 		/* header */
7771 		return (void*)1;
7772 
7773 	spin_lock(&all_mddevs_lock);
7774 	list_for_each(tmp,&all_mddevs)
7775 		if (!l--) {
7776 			mddev = list_entry(tmp, struct mddev, all_mddevs);
7777 			mddev_get(mddev);
7778 			spin_unlock(&all_mddevs_lock);
7779 			return mddev;
7780 		}
7781 	spin_unlock(&all_mddevs_lock);
7782 	if (!l--)
7783 		return (void*)2;/* tail */
7784 	return NULL;
7785 }
7786 
7787 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7788 {
7789 	struct list_head *tmp;
7790 	struct mddev *next_mddev, *mddev = v;
7791 
7792 	++*pos;
7793 	if (v == (void*)2)
7794 		return NULL;
7795 
7796 	spin_lock(&all_mddevs_lock);
7797 	if (v == (void*)1)
7798 		tmp = all_mddevs.next;
7799 	else
7800 		tmp = mddev->all_mddevs.next;
7801 	if (tmp != &all_mddevs)
7802 		next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7803 	else {
7804 		next_mddev = (void*)2;
7805 		*pos = 0x10000;
7806 	}
7807 	spin_unlock(&all_mddevs_lock);
7808 
7809 	if (v != (void*)1)
7810 		mddev_put(mddev);
7811 	return next_mddev;
7812 
7813 }
7814 
7815 static void md_seq_stop(struct seq_file *seq, void *v)
7816 {
7817 	struct mddev *mddev = v;
7818 
7819 	if (mddev && v != (void*)1 && v != (void*)2)
7820 		mddev_put(mddev);
7821 }
7822 
7823 static int md_seq_show(struct seq_file *seq, void *v)
7824 {
7825 	struct mddev *mddev = v;
7826 	sector_t sectors;
7827 	struct md_rdev *rdev;
7828 
7829 	if (v == (void*)1) {
7830 		struct md_personality *pers;
7831 		seq_printf(seq, "Personalities : ");
7832 		spin_lock(&pers_lock);
7833 		list_for_each_entry(pers, &pers_list, list)
7834 			seq_printf(seq, "[%s] ", pers->name);
7835 
7836 		spin_unlock(&pers_lock);
7837 		seq_printf(seq, "\n");
7838 		seq->poll_event = atomic_read(&md_event_count);
7839 		return 0;
7840 	}
7841 	if (v == (void*)2) {
7842 		status_unused(seq);
7843 		return 0;
7844 	}
7845 
7846 	spin_lock(&mddev->lock);
7847 	if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7848 		seq_printf(seq, "%s : %sactive", mdname(mddev),
7849 						mddev->pers ? "" : "in");
7850 		if (mddev->pers) {
7851 			if (mddev->ro==1)
7852 				seq_printf(seq, " (read-only)");
7853 			if (mddev->ro==2)
7854 				seq_printf(seq, " (auto-read-only)");
7855 			seq_printf(seq, " %s", mddev->pers->name);
7856 		}
7857 
7858 		sectors = 0;
7859 		rcu_read_lock();
7860 		rdev_for_each_rcu(rdev, mddev) {
7861 			char b[BDEVNAME_SIZE];
7862 			seq_printf(seq, " %s[%d]",
7863 				bdevname(rdev->bdev,b), rdev->desc_nr);
7864 			if (test_bit(WriteMostly, &rdev->flags))
7865 				seq_printf(seq, "(W)");
7866 			if (test_bit(Journal, &rdev->flags))
7867 				seq_printf(seq, "(J)");
7868 			if (test_bit(Faulty, &rdev->flags)) {
7869 				seq_printf(seq, "(F)");
7870 				continue;
7871 			}
7872 			if (rdev->raid_disk < 0)
7873 				seq_printf(seq, "(S)"); /* spare */
7874 			if (test_bit(Replacement, &rdev->flags))
7875 				seq_printf(seq, "(R)");
7876 			sectors += rdev->sectors;
7877 		}
7878 		rcu_read_unlock();
7879 
7880 		if (!list_empty(&mddev->disks)) {
7881 			if (mddev->pers)
7882 				seq_printf(seq, "\n      %llu blocks",
7883 					   (unsigned long long)
7884 					   mddev->array_sectors / 2);
7885 			else
7886 				seq_printf(seq, "\n      %llu blocks",
7887 					   (unsigned long long)sectors / 2);
7888 		}
7889 		if (mddev->persistent) {
7890 			if (mddev->major_version != 0 ||
7891 			    mddev->minor_version != 90) {
7892 				seq_printf(seq," super %d.%d",
7893 					   mddev->major_version,
7894 					   mddev->minor_version);
7895 			}
7896 		} else if (mddev->external)
7897 			seq_printf(seq, " super external:%s",
7898 				   mddev->metadata_type);
7899 		else
7900 			seq_printf(seq, " super non-persistent");
7901 
7902 		if (mddev->pers) {
7903 			mddev->pers->status(seq, mddev);
7904 			seq_printf(seq, "\n      ");
7905 			if (mddev->pers->sync_request) {
7906 				if (status_resync(seq, mddev))
7907 					seq_printf(seq, "\n      ");
7908 			}
7909 		} else
7910 			seq_printf(seq, "\n       ");
7911 
7912 		bitmap_status(seq, mddev->bitmap);
7913 
7914 		seq_printf(seq, "\n");
7915 	}
7916 	spin_unlock(&mddev->lock);
7917 
7918 	return 0;
7919 }
7920 
7921 static const struct seq_operations md_seq_ops = {
7922 	.start  = md_seq_start,
7923 	.next   = md_seq_next,
7924 	.stop   = md_seq_stop,
7925 	.show   = md_seq_show,
7926 };
7927 
7928 static int md_seq_open(struct inode *inode, struct file *file)
7929 {
7930 	struct seq_file *seq;
7931 	int error;
7932 
7933 	error = seq_open(file, &md_seq_ops);
7934 	if (error)
7935 		return error;
7936 
7937 	seq = file->private_data;
7938 	seq->poll_event = atomic_read(&md_event_count);
7939 	return error;
7940 }
7941 
7942 static int md_unloading;
7943 static __poll_t mdstat_poll(struct file *filp, poll_table *wait)
7944 {
7945 	struct seq_file *seq = filp->private_data;
7946 	__poll_t mask;
7947 
7948 	if (md_unloading)
7949 		return EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
7950 	poll_wait(filp, &md_event_waiters, wait);
7951 
7952 	/* always allow read */
7953 	mask = EPOLLIN | EPOLLRDNORM;
7954 
7955 	if (seq->poll_event != atomic_read(&md_event_count))
7956 		mask |= EPOLLERR | EPOLLPRI;
7957 	return mask;
7958 }
7959 
7960 static const struct file_operations md_seq_fops = {
7961 	.owner		= THIS_MODULE,
7962 	.open           = md_seq_open,
7963 	.read           = seq_read,
7964 	.llseek         = seq_lseek,
7965 	.release	= seq_release,
7966 	.poll		= mdstat_poll,
7967 };
7968 
7969 int register_md_personality(struct md_personality *p)
7970 {
7971 	pr_debug("md: %s personality registered for level %d\n",
7972 		 p->name, p->level);
7973 	spin_lock(&pers_lock);
7974 	list_add_tail(&p->list, &pers_list);
7975 	spin_unlock(&pers_lock);
7976 	return 0;
7977 }
7978 EXPORT_SYMBOL(register_md_personality);
7979 
7980 int unregister_md_personality(struct md_personality *p)
7981 {
7982 	pr_debug("md: %s personality unregistered\n", p->name);
7983 	spin_lock(&pers_lock);
7984 	list_del_init(&p->list);
7985 	spin_unlock(&pers_lock);
7986 	return 0;
7987 }
7988 EXPORT_SYMBOL(unregister_md_personality);
7989 
7990 int register_md_cluster_operations(struct md_cluster_operations *ops,
7991 				   struct module *module)
7992 {
7993 	int ret = 0;
7994 	spin_lock(&pers_lock);
7995 	if (md_cluster_ops != NULL)
7996 		ret = -EALREADY;
7997 	else {
7998 		md_cluster_ops = ops;
7999 		md_cluster_mod = module;
8000 	}
8001 	spin_unlock(&pers_lock);
8002 	return ret;
8003 }
8004 EXPORT_SYMBOL(register_md_cluster_operations);
8005 
8006 int unregister_md_cluster_operations(void)
8007 {
8008 	spin_lock(&pers_lock);
8009 	md_cluster_ops = NULL;
8010 	spin_unlock(&pers_lock);
8011 	return 0;
8012 }
8013 EXPORT_SYMBOL(unregister_md_cluster_operations);
8014 
8015 int md_setup_cluster(struct mddev *mddev, int nodes)
8016 {
8017 	if (!md_cluster_ops)
8018 		request_module("md-cluster");
8019 	spin_lock(&pers_lock);
8020 	/* ensure module won't be unloaded */
8021 	if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
8022 		pr_warn("can't find md-cluster module or get it's reference.\n");
8023 		spin_unlock(&pers_lock);
8024 		return -ENOENT;
8025 	}
8026 	spin_unlock(&pers_lock);
8027 
8028 	return md_cluster_ops->join(mddev, nodes);
8029 }
8030 
8031 void md_cluster_stop(struct mddev *mddev)
8032 {
8033 	if (!md_cluster_ops)
8034 		return;
8035 	md_cluster_ops->leave(mddev);
8036 	module_put(md_cluster_mod);
8037 }
8038 
8039 static int is_mddev_idle(struct mddev *mddev, int init)
8040 {
8041 	struct md_rdev *rdev;
8042 	int idle;
8043 	int curr_events;
8044 
8045 	idle = 1;
8046 	rcu_read_lock();
8047 	rdev_for_each_rcu(rdev, mddev) {
8048 		struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
8049 		curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
8050 			      (int)part_stat_read(&disk->part0, sectors[1]) -
8051 			      atomic_read(&disk->sync_io);
8052 		/* sync IO will cause sync_io to increase before the disk_stats
8053 		 * as sync_io is counted when a request starts, and
8054 		 * disk_stats is counted when it completes.
8055 		 * So resync activity will cause curr_events to be smaller than
8056 		 * when there was no such activity.
8057 		 * non-sync IO will cause disk_stat to increase without
8058 		 * increasing sync_io so curr_events will (eventually)
8059 		 * be larger than it was before.  Once it becomes
8060 		 * substantially larger, the test below will cause
8061 		 * the array to appear non-idle, and resync will slow
8062 		 * down.
8063 		 * If there is a lot of outstanding resync activity when
8064 		 * we set last_event to curr_events, then all that activity
8065 		 * completing might cause the array to appear non-idle
8066 		 * and resync will be slowed down even though there might
8067 		 * not have been non-resync activity.  This will only
8068 		 * happen once though.  'last_events' will soon reflect
8069 		 * the state where there is little or no outstanding
8070 		 * resync requests, and further resync activity will
8071 		 * always make curr_events less than last_events.
8072 		 *
8073 		 */
8074 		if (init || curr_events - rdev->last_events > 64) {
8075 			rdev->last_events = curr_events;
8076 			idle = 0;
8077 		}
8078 	}
8079 	rcu_read_unlock();
8080 	return idle;
8081 }
8082 
8083 void md_done_sync(struct mddev *mddev, int blocks, int ok)
8084 {
8085 	/* another "blocks" (512byte) blocks have been synced */
8086 	atomic_sub(blocks, &mddev->recovery_active);
8087 	wake_up(&mddev->recovery_wait);
8088 	if (!ok) {
8089 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8090 		set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
8091 		md_wakeup_thread(mddev->thread);
8092 		// stop recovery, signal do_sync ....
8093 	}
8094 }
8095 EXPORT_SYMBOL(md_done_sync);
8096 
8097 /* md_write_start(mddev, bi)
8098  * If we need to update some array metadata (e.g. 'active' flag
8099  * in superblock) before writing, schedule a superblock update
8100  * and wait for it to complete.
8101  * A return value of 'false' means that the write wasn't recorded
8102  * and cannot proceed as the array is being suspend.
8103  */
8104 bool md_write_start(struct mddev *mddev, struct bio *bi)
8105 {
8106 	int did_change = 0;
8107 
8108 	if (bio_data_dir(bi) != WRITE)
8109 		return true;
8110 
8111 	BUG_ON(mddev->ro == 1);
8112 	if (mddev->ro == 2) {
8113 		/* need to switch to read/write */
8114 		mddev->ro = 0;
8115 		set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8116 		md_wakeup_thread(mddev->thread);
8117 		md_wakeup_thread(mddev->sync_thread);
8118 		did_change = 1;
8119 	}
8120 	rcu_read_lock();
8121 	percpu_ref_get(&mddev->writes_pending);
8122 	smp_mb(); /* Match smp_mb in set_in_sync() */
8123 	if (mddev->safemode == 1)
8124 		mddev->safemode = 0;
8125 	/* sync_checkers is always 0 when writes_pending is in per-cpu mode */
8126 	if (mddev->in_sync || mddev->sync_checkers) {
8127 		spin_lock(&mddev->lock);
8128 		if (mddev->in_sync) {
8129 			mddev->in_sync = 0;
8130 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8131 			set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8132 			md_wakeup_thread(mddev->thread);
8133 			did_change = 1;
8134 		}
8135 		spin_unlock(&mddev->lock);
8136 	}
8137 	rcu_read_unlock();
8138 	if (did_change)
8139 		sysfs_notify_dirent_safe(mddev->sysfs_state);
8140 	if (!mddev->has_superblocks)
8141 		return true;
8142 	wait_event(mddev->sb_wait,
8143 		   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags) ||
8144 		   mddev->suspended);
8145 	if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
8146 		percpu_ref_put(&mddev->writes_pending);
8147 		return false;
8148 	}
8149 	return true;
8150 }
8151 EXPORT_SYMBOL(md_write_start);
8152 
8153 /* md_write_inc can only be called when md_write_start() has
8154  * already been called at least once of the current request.
8155  * It increments the counter and is useful when a single request
8156  * is split into several parts.  Each part causes an increment and
8157  * so needs a matching md_write_end().
8158  * Unlike md_write_start(), it is safe to call md_write_inc() inside
8159  * a spinlocked region.
8160  */
8161 void md_write_inc(struct mddev *mddev, struct bio *bi)
8162 {
8163 	if (bio_data_dir(bi) != WRITE)
8164 		return;
8165 	WARN_ON_ONCE(mddev->in_sync || mddev->ro);
8166 	percpu_ref_get(&mddev->writes_pending);
8167 }
8168 EXPORT_SYMBOL(md_write_inc);
8169 
8170 void md_write_end(struct mddev *mddev)
8171 {
8172 	percpu_ref_put(&mddev->writes_pending);
8173 
8174 	if (mddev->safemode == 2)
8175 		md_wakeup_thread(mddev->thread);
8176 	else if (mddev->safemode_delay)
8177 		/* The roundup() ensures this only performs locking once
8178 		 * every ->safemode_delay jiffies
8179 		 */
8180 		mod_timer(&mddev->safemode_timer,
8181 			  roundup(jiffies, mddev->safemode_delay) +
8182 			  mddev->safemode_delay);
8183 }
8184 
8185 EXPORT_SYMBOL(md_write_end);
8186 
8187 /* md_allow_write(mddev)
8188  * Calling this ensures that the array is marked 'active' so that writes
8189  * may proceed without blocking.  It is important to call this before
8190  * attempting a GFP_KERNEL allocation while holding the mddev lock.
8191  * Must be called with mddev_lock held.
8192  */
8193 void md_allow_write(struct mddev *mddev)
8194 {
8195 	if (!mddev->pers)
8196 		return;
8197 	if (mddev->ro)
8198 		return;
8199 	if (!mddev->pers->sync_request)
8200 		return;
8201 
8202 	spin_lock(&mddev->lock);
8203 	if (mddev->in_sync) {
8204 		mddev->in_sync = 0;
8205 		set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8206 		set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8207 		if (mddev->safemode_delay &&
8208 		    mddev->safemode == 0)
8209 			mddev->safemode = 1;
8210 		spin_unlock(&mddev->lock);
8211 		md_update_sb(mddev, 0);
8212 		sysfs_notify_dirent_safe(mddev->sysfs_state);
8213 		/* wait for the dirty state to be recorded in the metadata */
8214 		wait_event(mddev->sb_wait,
8215 			   !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
8216 	} else
8217 		spin_unlock(&mddev->lock);
8218 }
8219 EXPORT_SYMBOL_GPL(md_allow_write);
8220 
8221 #define SYNC_MARKS	10
8222 #define	SYNC_MARK_STEP	(3*HZ)
8223 #define UPDATE_FREQUENCY (5*60*HZ)
8224 void md_do_sync(struct md_thread *thread)
8225 {
8226 	struct mddev *mddev = thread->mddev;
8227 	struct mddev *mddev2;
8228 	unsigned int currspeed = 0,
8229 		 window;
8230 	sector_t max_sectors,j, io_sectors, recovery_done;
8231 	unsigned long mark[SYNC_MARKS];
8232 	unsigned long update_time;
8233 	sector_t mark_cnt[SYNC_MARKS];
8234 	int last_mark,m;
8235 	struct list_head *tmp;
8236 	sector_t last_check;
8237 	int skipped = 0;
8238 	struct md_rdev *rdev;
8239 	char *desc, *action = NULL;
8240 	struct blk_plug plug;
8241 	int ret;
8242 
8243 	/* just incase thread restarts... */
8244 	if (test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8245 	    test_bit(MD_RECOVERY_WAIT, &mddev->recovery))
8246 		return;
8247 	if (mddev->ro) {/* never try to sync a read-only array */
8248 		set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8249 		return;
8250 	}
8251 
8252 	if (mddev_is_clustered(mddev)) {
8253 		ret = md_cluster_ops->resync_start(mddev);
8254 		if (ret)
8255 			goto skip;
8256 
8257 		set_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags);
8258 		if (!(test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8259 			test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) ||
8260 			test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
8261 		     && ((unsigned long long)mddev->curr_resync_completed
8262 			 < (unsigned long long)mddev->resync_max_sectors))
8263 			goto skip;
8264 	}
8265 
8266 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8267 		if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
8268 			desc = "data-check";
8269 			action = "check";
8270 		} else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8271 			desc = "requested-resync";
8272 			action = "repair";
8273 		} else
8274 			desc = "resync";
8275 	} else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8276 		desc = "reshape";
8277 	else
8278 		desc = "recovery";
8279 
8280 	mddev->last_sync_action = action ?: desc;
8281 
8282 	/* we overload curr_resync somewhat here.
8283 	 * 0 == not engaged in resync at all
8284 	 * 2 == checking that there is no conflict with another sync
8285 	 * 1 == like 2, but have yielded to allow conflicting resync to
8286 	 *		commense
8287 	 * other == active in resync - this many blocks
8288 	 *
8289 	 * Before starting a resync we must have set curr_resync to
8290 	 * 2, and then checked that every "conflicting" array has curr_resync
8291 	 * less than ours.  When we find one that is the same or higher
8292 	 * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
8293 	 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
8294 	 * This will mean we have to start checking from the beginning again.
8295 	 *
8296 	 */
8297 
8298 	do {
8299 		int mddev2_minor = -1;
8300 		mddev->curr_resync = 2;
8301 
8302 	try_again:
8303 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8304 			goto skip;
8305 		for_each_mddev(mddev2, tmp) {
8306 			if (mddev2 == mddev)
8307 				continue;
8308 			if (!mddev->parallel_resync
8309 			&&  mddev2->curr_resync
8310 			&&  match_mddev_units(mddev, mddev2)) {
8311 				DEFINE_WAIT(wq);
8312 				if (mddev < mddev2 && mddev->curr_resync == 2) {
8313 					/* arbitrarily yield */
8314 					mddev->curr_resync = 1;
8315 					wake_up(&resync_wait);
8316 				}
8317 				if (mddev > mddev2 && mddev->curr_resync == 1)
8318 					/* no need to wait here, we can wait the next
8319 					 * time 'round when curr_resync == 2
8320 					 */
8321 					continue;
8322 				/* We need to wait 'interruptible' so as not to
8323 				 * contribute to the load average, and not to
8324 				 * be caught by 'softlockup'
8325 				 */
8326 				prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
8327 				if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8328 				    mddev2->curr_resync >= mddev->curr_resync) {
8329 					if (mddev2_minor != mddev2->md_minor) {
8330 						mddev2_minor = mddev2->md_minor;
8331 						pr_info("md: delaying %s of %s until %s has finished (they share one or more physical units)\n",
8332 							desc, mdname(mddev),
8333 							mdname(mddev2));
8334 					}
8335 					mddev_put(mddev2);
8336 					if (signal_pending(current))
8337 						flush_signals(current);
8338 					schedule();
8339 					finish_wait(&resync_wait, &wq);
8340 					goto try_again;
8341 				}
8342 				finish_wait(&resync_wait, &wq);
8343 			}
8344 		}
8345 	} while (mddev->curr_resync < 2);
8346 
8347 	j = 0;
8348 	if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8349 		/* resync follows the size requested by the personality,
8350 		 * which defaults to physical size, but can be virtual size
8351 		 */
8352 		max_sectors = mddev->resync_max_sectors;
8353 		atomic64_set(&mddev->resync_mismatches, 0);
8354 		/* we don't use the checkpoint if there's a bitmap */
8355 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8356 			j = mddev->resync_min;
8357 		else if (!mddev->bitmap)
8358 			j = mddev->recovery_cp;
8359 
8360 	} else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8361 		max_sectors = mddev->resync_max_sectors;
8362 	else {
8363 		/* recovery follows the physical size of devices */
8364 		max_sectors = mddev->dev_sectors;
8365 		j = MaxSector;
8366 		rcu_read_lock();
8367 		rdev_for_each_rcu(rdev, mddev)
8368 			if (rdev->raid_disk >= 0 &&
8369 			    !test_bit(Journal, &rdev->flags) &&
8370 			    !test_bit(Faulty, &rdev->flags) &&
8371 			    !test_bit(In_sync, &rdev->flags) &&
8372 			    rdev->recovery_offset < j)
8373 				j = rdev->recovery_offset;
8374 		rcu_read_unlock();
8375 
8376 		/* If there is a bitmap, we need to make sure all
8377 		 * writes that started before we added a spare
8378 		 * complete before we start doing a recovery.
8379 		 * Otherwise the write might complete and (via
8380 		 * bitmap_endwrite) set a bit in the bitmap after the
8381 		 * recovery has checked that bit and skipped that
8382 		 * region.
8383 		 */
8384 		if (mddev->bitmap) {
8385 			mddev->pers->quiesce(mddev, 1);
8386 			mddev->pers->quiesce(mddev, 0);
8387 		}
8388 	}
8389 
8390 	pr_info("md: %s of RAID array %s\n", desc, mdname(mddev));
8391 	pr_debug("md: minimum _guaranteed_  speed: %d KB/sec/disk.\n", speed_min(mddev));
8392 	pr_debug("md: using maximum available idle IO bandwidth (but not more than %d KB/sec) for %s.\n",
8393 		 speed_max(mddev), desc);
8394 
8395 	is_mddev_idle(mddev, 1); /* this initializes IO event counters */
8396 
8397 	io_sectors = 0;
8398 	for (m = 0; m < SYNC_MARKS; m++) {
8399 		mark[m] = jiffies;
8400 		mark_cnt[m] = io_sectors;
8401 	}
8402 	last_mark = 0;
8403 	mddev->resync_mark = mark[last_mark];
8404 	mddev->resync_mark_cnt = mark_cnt[last_mark];
8405 
8406 	/*
8407 	 * Tune reconstruction:
8408 	 */
8409 	window = 32*(PAGE_SIZE/512);
8410 	pr_debug("md: using %dk window, over a total of %lluk.\n",
8411 		 window/2, (unsigned long long)max_sectors/2);
8412 
8413 	atomic_set(&mddev->recovery_active, 0);
8414 	last_check = 0;
8415 
8416 	if (j>2) {
8417 		pr_debug("md: resuming %s of %s from checkpoint.\n",
8418 			 desc, mdname(mddev));
8419 		mddev->curr_resync = j;
8420 	} else
8421 		mddev->curr_resync = 3; /* no longer delayed */
8422 	mddev->curr_resync_completed = j;
8423 	sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8424 	md_new_event(mddev);
8425 	update_time = jiffies;
8426 
8427 	blk_start_plug(&plug);
8428 	while (j < max_sectors) {
8429 		sector_t sectors;
8430 
8431 		skipped = 0;
8432 
8433 		if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8434 		    ((mddev->curr_resync > mddev->curr_resync_completed &&
8435 		      (mddev->curr_resync - mddev->curr_resync_completed)
8436 		      > (max_sectors >> 4)) ||
8437 		     time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
8438 		     (j - mddev->curr_resync_completed)*2
8439 		     >= mddev->resync_max - mddev->curr_resync_completed ||
8440 		     mddev->curr_resync_completed > mddev->resync_max
8441 			    )) {
8442 			/* time to update curr_resync_completed */
8443 			wait_event(mddev->recovery_wait,
8444 				   atomic_read(&mddev->recovery_active) == 0);
8445 			mddev->curr_resync_completed = j;
8446 			if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
8447 			    j > mddev->recovery_cp)
8448 				mddev->recovery_cp = j;
8449 			update_time = jiffies;
8450 			set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8451 			sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8452 		}
8453 
8454 		while (j >= mddev->resync_max &&
8455 		       !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8456 			/* As this condition is controlled by user-space,
8457 			 * we can block indefinitely, so use '_interruptible'
8458 			 * to avoid triggering warnings.
8459 			 */
8460 			flush_signals(current); /* just in case */
8461 			wait_event_interruptible(mddev->recovery_wait,
8462 						 mddev->resync_max > j
8463 						 || test_bit(MD_RECOVERY_INTR,
8464 							     &mddev->recovery));
8465 		}
8466 
8467 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8468 			break;
8469 
8470 		sectors = mddev->pers->sync_request(mddev, j, &skipped);
8471 		if (sectors == 0) {
8472 			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8473 			break;
8474 		}
8475 
8476 		if (!skipped) { /* actual IO requested */
8477 			io_sectors += sectors;
8478 			atomic_add(sectors, &mddev->recovery_active);
8479 		}
8480 
8481 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8482 			break;
8483 
8484 		j += sectors;
8485 		if (j > max_sectors)
8486 			/* when skipping, extra large numbers can be returned. */
8487 			j = max_sectors;
8488 		if (j > 2)
8489 			mddev->curr_resync = j;
8490 		mddev->curr_mark_cnt = io_sectors;
8491 		if (last_check == 0)
8492 			/* this is the earliest that rebuild will be
8493 			 * visible in /proc/mdstat
8494 			 */
8495 			md_new_event(mddev);
8496 
8497 		if (last_check + window > io_sectors || j == max_sectors)
8498 			continue;
8499 
8500 		last_check = io_sectors;
8501 	repeat:
8502 		if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
8503 			/* step marks */
8504 			int next = (last_mark+1) % SYNC_MARKS;
8505 
8506 			mddev->resync_mark = mark[next];
8507 			mddev->resync_mark_cnt = mark_cnt[next];
8508 			mark[next] = jiffies;
8509 			mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
8510 			last_mark = next;
8511 		}
8512 
8513 		if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8514 			break;
8515 
8516 		/*
8517 		 * this loop exits only if either when we are slower than
8518 		 * the 'hard' speed limit, or the system was IO-idle for
8519 		 * a jiffy.
8520 		 * the system might be non-idle CPU-wise, but we only care
8521 		 * about not overloading the IO subsystem. (things like an
8522 		 * e2fsck being done on the RAID array should execute fast)
8523 		 */
8524 		cond_resched();
8525 
8526 		recovery_done = io_sectors - atomic_read(&mddev->recovery_active);
8527 		currspeed = ((unsigned long)(recovery_done - mddev->resync_mark_cnt))/2
8528 			/((jiffies-mddev->resync_mark)/HZ +1) +1;
8529 
8530 		if (currspeed > speed_min(mddev)) {
8531 			if (currspeed > speed_max(mddev)) {
8532 				msleep(500);
8533 				goto repeat;
8534 			}
8535 			if (!is_mddev_idle(mddev, 0)) {
8536 				/*
8537 				 * Give other IO more of a chance.
8538 				 * The faster the devices, the less we wait.
8539 				 */
8540 				wait_event(mddev->recovery_wait,
8541 					   !atomic_read(&mddev->recovery_active));
8542 			}
8543 		}
8544 	}
8545 	pr_info("md: %s: %s %s.\n",mdname(mddev), desc,
8546 		test_bit(MD_RECOVERY_INTR, &mddev->recovery)
8547 		? "interrupted" : "done");
8548 	/*
8549 	 * this also signals 'finished resyncing' to md_stop
8550 	 */
8551 	blk_finish_plug(&plug);
8552 	wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
8553 
8554 	if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8555 	    !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8556 	    mddev->curr_resync > 3) {
8557 		mddev->curr_resync_completed = mddev->curr_resync;
8558 		sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8559 	}
8560 	mddev->pers->sync_request(mddev, max_sectors, &skipped);
8561 
8562 	if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
8563 	    mddev->curr_resync > 3) {
8564 		if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8565 			if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8566 				if (mddev->curr_resync >= mddev->recovery_cp) {
8567 					pr_debug("md: checkpointing %s of %s.\n",
8568 						 desc, mdname(mddev));
8569 					if (test_bit(MD_RECOVERY_ERROR,
8570 						&mddev->recovery))
8571 						mddev->recovery_cp =
8572 							mddev->curr_resync_completed;
8573 					else
8574 						mddev->recovery_cp =
8575 							mddev->curr_resync;
8576 				}
8577 			} else
8578 				mddev->recovery_cp = MaxSector;
8579 		} else {
8580 			if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8581 				mddev->curr_resync = MaxSector;
8582 			if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8583 			    test_bit(MD_RECOVERY_RECOVER, &mddev->recovery)) {
8584 				rcu_read_lock();
8585 				rdev_for_each_rcu(rdev, mddev)
8586 					if (rdev->raid_disk >= 0 &&
8587 					    mddev->delta_disks >= 0 &&
8588 					    !test_bit(Journal, &rdev->flags) &&
8589 					    !test_bit(Faulty, &rdev->flags) &&
8590 					    !test_bit(In_sync, &rdev->flags) &&
8591 					    rdev->recovery_offset < mddev->curr_resync)
8592 						rdev->recovery_offset = mddev->curr_resync;
8593 				rcu_read_unlock();
8594 			}
8595 		}
8596 	}
8597  skip:
8598 	/* set CHANGE_PENDING here since maybe another update is needed,
8599 	 * so other nodes are informed. It should be harmless for normal
8600 	 * raid */
8601 	set_mask_bits(&mddev->sb_flags, 0,
8602 		      BIT(MD_SB_CHANGE_PENDING) | BIT(MD_SB_CHANGE_DEVS));
8603 
8604 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8605 			!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8606 			mddev->delta_disks > 0 &&
8607 			mddev->pers->finish_reshape &&
8608 			mddev->pers->size &&
8609 			mddev->queue) {
8610 		mddev_lock_nointr(mddev);
8611 		md_set_array_sectors(mddev, mddev->pers->size(mddev, 0, 0));
8612 		mddev_unlock(mddev);
8613 		set_capacity(mddev->gendisk, mddev->array_sectors);
8614 		revalidate_disk(mddev->gendisk);
8615 	}
8616 
8617 	spin_lock(&mddev->lock);
8618 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8619 		/* We completed so min/max setting can be forgotten if used. */
8620 		if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8621 			mddev->resync_min = 0;
8622 		mddev->resync_max = MaxSector;
8623 	} else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8624 		mddev->resync_min = mddev->curr_resync_completed;
8625 	set_bit(MD_RECOVERY_DONE, &mddev->recovery);
8626 	mddev->curr_resync = 0;
8627 	spin_unlock(&mddev->lock);
8628 
8629 	wake_up(&resync_wait);
8630 	md_wakeup_thread(mddev->thread);
8631 	return;
8632 }
8633 EXPORT_SYMBOL_GPL(md_do_sync);
8634 
8635 static int remove_and_add_spares(struct mddev *mddev,
8636 				 struct md_rdev *this)
8637 {
8638 	struct md_rdev *rdev;
8639 	int spares = 0;
8640 	int removed = 0;
8641 	bool remove_some = false;
8642 
8643 	if (this && test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8644 		/* Mustn't remove devices when resync thread is running */
8645 		return 0;
8646 
8647 	rdev_for_each(rdev, mddev) {
8648 		if ((this == NULL || rdev == this) &&
8649 		    rdev->raid_disk >= 0 &&
8650 		    !test_bit(Blocked, &rdev->flags) &&
8651 		    test_bit(Faulty, &rdev->flags) &&
8652 		    atomic_read(&rdev->nr_pending)==0) {
8653 			/* Faulty non-Blocked devices with nr_pending == 0
8654 			 * never get nr_pending incremented,
8655 			 * never get Faulty cleared, and never get Blocked set.
8656 			 * So we can synchronize_rcu now rather than once per device
8657 			 */
8658 			remove_some = true;
8659 			set_bit(RemoveSynchronized, &rdev->flags);
8660 		}
8661 	}
8662 
8663 	if (remove_some)
8664 		synchronize_rcu();
8665 	rdev_for_each(rdev, mddev) {
8666 		if ((this == NULL || rdev == this) &&
8667 		    rdev->raid_disk >= 0 &&
8668 		    !test_bit(Blocked, &rdev->flags) &&
8669 		    ((test_bit(RemoveSynchronized, &rdev->flags) ||
8670 		     (!test_bit(In_sync, &rdev->flags) &&
8671 		      !test_bit(Journal, &rdev->flags))) &&
8672 		    atomic_read(&rdev->nr_pending)==0)) {
8673 			if (mddev->pers->hot_remove_disk(
8674 				    mddev, rdev) == 0) {
8675 				sysfs_unlink_rdev(mddev, rdev);
8676 				rdev->saved_raid_disk = rdev->raid_disk;
8677 				rdev->raid_disk = -1;
8678 				removed++;
8679 			}
8680 		}
8681 		if (remove_some && test_bit(RemoveSynchronized, &rdev->flags))
8682 			clear_bit(RemoveSynchronized, &rdev->flags);
8683 	}
8684 
8685 	if (removed && mddev->kobj.sd)
8686 		sysfs_notify(&mddev->kobj, NULL, "degraded");
8687 
8688 	if (this && removed)
8689 		goto no_add;
8690 
8691 	rdev_for_each(rdev, mddev) {
8692 		if (this && this != rdev)
8693 			continue;
8694 		if (test_bit(Candidate, &rdev->flags))
8695 			continue;
8696 		if (rdev->raid_disk >= 0 &&
8697 		    !test_bit(In_sync, &rdev->flags) &&
8698 		    !test_bit(Journal, &rdev->flags) &&
8699 		    !test_bit(Faulty, &rdev->flags))
8700 			spares++;
8701 		if (rdev->raid_disk >= 0)
8702 			continue;
8703 		if (test_bit(Faulty, &rdev->flags))
8704 			continue;
8705 		if (!test_bit(Journal, &rdev->flags)) {
8706 			if (mddev->ro &&
8707 			    ! (rdev->saved_raid_disk >= 0 &&
8708 			       !test_bit(Bitmap_sync, &rdev->flags)))
8709 				continue;
8710 
8711 			rdev->recovery_offset = 0;
8712 		}
8713 		if (mddev->pers->
8714 		    hot_add_disk(mddev, rdev) == 0) {
8715 			if (sysfs_link_rdev(mddev, rdev))
8716 				/* failure here is OK */;
8717 			if (!test_bit(Journal, &rdev->flags))
8718 				spares++;
8719 			md_new_event(mddev);
8720 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8721 		}
8722 	}
8723 no_add:
8724 	if (removed)
8725 		set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8726 	return spares;
8727 }
8728 
8729 static void md_start_sync(struct work_struct *ws)
8730 {
8731 	struct mddev *mddev = container_of(ws, struct mddev, del_work);
8732 
8733 	mddev->sync_thread = md_register_thread(md_do_sync,
8734 						mddev,
8735 						"resync");
8736 	if (!mddev->sync_thread) {
8737 		pr_warn("%s: could not start resync thread...\n",
8738 			mdname(mddev));
8739 		/* leave the spares where they are, it shouldn't hurt */
8740 		clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8741 		clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8742 		clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8743 		clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8744 		clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8745 		wake_up(&resync_wait);
8746 		if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8747 				       &mddev->recovery))
8748 			if (mddev->sysfs_action)
8749 				sysfs_notify_dirent_safe(mddev->sysfs_action);
8750 	} else
8751 		md_wakeup_thread(mddev->sync_thread);
8752 	sysfs_notify_dirent_safe(mddev->sysfs_action);
8753 	md_new_event(mddev);
8754 }
8755 
8756 /*
8757  * This routine is regularly called by all per-raid-array threads to
8758  * deal with generic issues like resync and super-block update.
8759  * Raid personalities that don't have a thread (linear/raid0) do not
8760  * need this as they never do any recovery or update the superblock.
8761  *
8762  * It does not do any resync itself, but rather "forks" off other threads
8763  * to do that as needed.
8764  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
8765  * "->recovery" and create a thread at ->sync_thread.
8766  * When the thread finishes it sets MD_RECOVERY_DONE
8767  * and wakeups up this thread which will reap the thread and finish up.
8768  * This thread also removes any faulty devices (with nr_pending == 0).
8769  *
8770  * The overall approach is:
8771  *  1/ if the superblock needs updating, update it.
8772  *  2/ If a recovery thread is running, don't do anything else.
8773  *  3/ If recovery has finished, clean up, possibly marking spares active.
8774  *  4/ If there are any faulty devices, remove them.
8775  *  5/ If array is degraded, try to add spares devices
8776  *  6/ If array has spares or is not in-sync, start a resync thread.
8777  */
8778 void md_check_recovery(struct mddev *mddev)
8779 {
8780 	if (mddev->suspended)
8781 		return;
8782 
8783 	if (mddev->bitmap)
8784 		bitmap_daemon_work(mddev);
8785 
8786 	if (signal_pending(current)) {
8787 		if (mddev->pers->sync_request && !mddev->external) {
8788 			pr_debug("md: %s in immediate safe mode\n",
8789 				 mdname(mddev));
8790 			mddev->safemode = 2;
8791 		}
8792 		flush_signals(current);
8793 	}
8794 
8795 	if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
8796 		return;
8797 	if ( ! (
8798 		(mddev->sb_flags & ~ (1<<MD_SB_CHANGE_PENDING)) ||
8799 		test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8800 		test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8801 		(mddev->external == 0 && mddev->safemode == 1) ||
8802 		(mddev->safemode == 2
8803 		 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
8804 		))
8805 		return;
8806 
8807 	if (mddev_trylock(mddev)) {
8808 		int spares = 0;
8809 
8810 		if (!mddev->external && mddev->safemode == 1)
8811 			mddev->safemode = 0;
8812 
8813 		if (mddev->ro) {
8814 			struct md_rdev *rdev;
8815 			if (!mddev->external && mddev->in_sync)
8816 				/* 'Blocked' flag not needed as failed devices
8817 				 * will be recorded if array switched to read/write.
8818 				 * Leaving it set will prevent the device
8819 				 * from being removed.
8820 				 */
8821 				rdev_for_each(rdev, mddev)
8822 					clear_bit(Blocked, &rdev->flags);
8823 			/* On a read-only array we can:
8824 			 * - remove failed devices
8825 			 * - add already-in_sync devices if the array itself
8826 			 *   is in-sync.
8827 			 * As we only add devices that are already in-sync,
8828 			 * we can activate the spares immediately.
8829 			 */
8830 			remove_and_add_spares(mddev, NULL);
8831 			/* There is no thread, but we need to call
8832 			 * ->spare_active and clear saved_raid_disk
8833 			 */
8834 			set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8835 			md_reap_sync_thread(mddev);
8836 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8837 			clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8838 			clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8839 			goto unlock;
8840 		}
8841 
8842 		if (mddev_is_clustered(mddev)) {
8843 			struct md_rdev *rdev;
8844 			/* kick the device if another node issued a
8845 			 * remove disk.
8846 			 */
8847 			rdev_for_each(rdev, mddev) {
8848 				if (test_and_clear_bit(ClusterRemove, &rdev->flags) &&
8849 						rdev->raid_disk < 0)
8850 					md_kick_rdev_from_array(rdev);
8851 			}
8852 		}
8853 
8854 		if (!mddev->external && !mddev->in_sync) {
8855 			spin_lock(&mddev->lock);
8856 			set_in_sync(mddev);
8857 			spin_unlock(&mddev->lock);
8858 		}
8859 
8860 		if (mddev->sb_flags)
8861 			md_update_sb(mddev, 0);
8862 
8863 		if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
8864 		    !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
8865 			/* resync/recovery still happening */
8866 			clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8867 			goto unlock;
8868 		}
8869 		if (mddev->sync_thread) {
8870 			md_reap_sync_thread(mddev);
8871 			goto unlock;
8872 		}
8873 		/* Set RUNNING before clearing NEEDED to avoid
8874 		 * any transients in the value of "sync_action".
8875 		 */
8876 		mddev->curr_resync_completed = 0;
8877 		spin_lock(&mddev->lock);
8878 		set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8879 		spin_unlock(&mddev->lock);
8880 		/* Clear some bits that don't mean anything, but
8881 		 * might be left set
8882 		 */
8883 		clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
8884 		clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8885 
8886 		if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8887 		    test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
8888 			goto not_running;
8889 		/* no recovery is running.
8890 		 * remove any failed drives, then
8891 		 * add spares if possible.
8892 		 * Spares are also removed and re-added, to allow
8893 		 * the personality to fail the re-add.
8894 		 */
8895 
8896 		if (mddev->reshape_position != MaxSector) {
8897 			if (mddev->pers->check_reshape == NULL ||
8898 			    mddev->pers->check_reshape(mddev) != 0)
8899 				/* Cannot proceed */
8900 				goto not_running;
8901 			set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8902 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8903 		} else if ((spares = remove_and_add_spares(mddev, NULL))) {
8904 			clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8905 			clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8906 			clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8907 			set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8908 		} else if (mddev->recovery_cp < MaxSector) {
8909 			set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8910 			clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8911 		} else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
8912 			/* nothing to be done ... */
8913 			goto not_running;
8914 
8915 		if (mddev->pers->sync_request) {
8916 			if (spares) {
8917 				/* We are adding a device or devices to an array
8918 				 * which has the bitmap stored on all devices.
8919 				 * So make sure all bitmap pages get written
8920 				 */
8921 				bitmap_write_all(mddev->bitmap);
8922 			}
8923 			INIT_WORK(&mddev->del_work, md_start_sync);
8924 			queue_work(md_misc_wq, &mddev->del_work);
8925 			goto unlock;
8926 		}
8927 	not_running:
8928 		if (!mddev->sync_thread) {
8929 			clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8930 			wake_up(&resync_wait);
8931 			if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8932 					       &mddev->recovery))
8933 				if (mddev->sysfs_action)
8934 					sysfs_notify_dirent_safe(mddev->sysfs_action);
8935 		}
8936 	unlock:
8937 		wake_up(&mddev->sb_wait);
8938 		mddev_unlock(mddev);
8939 	} else if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags) && mddev->sb_flags) {
8940 		/* Write superblock - thread that called mddev_suspend()
8941 		 * holds reconfig_mutex for us.
8942 		 */
8943 		set_bit(MD_UPDATING_SB, &mddev->flags);
8944 		smp_mb__after_atomic();
8945 		if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags))
8946 			md_update_sb(mddev, 0);
8947 		clear_bit_unlock(MD_UPDATING_SB, &mddev->flags);
8948 		wake_up(&mddev->sb_wait);
8949 	}
8950 }
8951 EXPORT_SYMBOL(md_check_recovery);
8952 
8953 void md_reap_sync_thread(struct mddev *mddev)
8954 {
8955 	struct md_rdev *rdev;
8956 
8957 	/* resync has finished, collect result */
8958 	md_unregister_thread(&mddev->sync_thread);
8959 	if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8960 	    !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8961 		/* success...*/
8962 		/* activate any spares */
8963 		if (mddev->pers->spare_active(mddev)) {
8964 			sysfs_notify(&mddev->kobj, NULL,
8965 				     "degraded");
8966 			set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8967 		}
8968 	}
8969 	if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8970 	    mddev->pers->finish_reshape)
8971 		mddev->pers->finish_reshape(mddev);
8972 
8973 	/* If array is no-longer degraded, then any saved_raid_disk
8974 	 * information must be scrapped.
8975 	 */
8976 	if (!mddev->degraded)
8977 		rdev_for_each(rdev, mddev)
8978 			rdev->saved_raid_disk = -1;
8979 
8980 	md_update_sb(mddev, 1);
8981 	/* MD_SB_CHANGE_PENDING should be cleared by md_update_sb, so we can
8982 	 * call resync_finish here if MD_CLUSTER_RESYNC_LOCKED is set by
8983 	 * clustered raid */
8984 	if (test_and_clear_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags))
8985 		md_cluster_ops->resync_finish(mddev);
8986 	clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8987 	clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8988 	clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8989 	clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8990 	clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8991 	clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8992 	wake_up(&resync_wait);
8993 	/* flag recovery needed just to double check */
8994 	set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8995 	sysfs_notify_dirent_safe(mddev->sysfs_action);
8996 	md_new_event(mddev);
8997 	if (mddev->event_work.func)
8998 		queue_work(md_misc_wq, &mddev->event_work);
8999 }
9000 EXPORT_SYMBOL(md_reap_sync_thread);
9001 
9002 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
9003 {
9004 	sysfs_notify_dirent_safe(rdev->sysfs_state);
9005 	wait_event_timeout(rdev->blocked_wait,
9006 			   !test_bit(Blocked, &rdev->flags) &&
9007 			   !test_bit(BlockedBadBlocks, &rdev->flags),
9008 			   msecs_to_jiffies(5000));
9009 	rdev_dec_pending(rdev, mddev);
9010 }
9011 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
9012 
9013 void md_finish_reshape(struct mddev *mddev)
9014 {
9015 	/* called be personality module when reshape completes. */
9016 	struct md_rdev *rdev;
9017 
9018 	rdev_for_each(rdev, mddev) {
9019 		if (rdev->data_offset > rdev->new_data_offset)
9020 			rdev->sectors += rdev->data_offset - rdev->new_data_offset;
9021 		else
9022 			rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
9023 		rdev->data_offset = rdev->new_data_offset;
9024 	}
9025 }
9026 EXPORT_SYMBOL(md_finish_reshape);
9027 
9028 /* Bad block management */
9029 
9030 /* Returns 1 on success, 0 on failure */
9031 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9032 		       int is_new)
9033 {
9034 	struct mddev *mddev = rdev->mddev;
9035 	int rv;
9036 	if (is_new)
9037 		s += rdev->new_data_offset;
9038 	else
9039 		s += rdev->data_offset;
9040 	rv = badblocks_set(&rdev->badblocks, s, sectors, 0);
9041 	if (rv == 0) {
9042 		/* Make sure they get written out promptly */
9043 		if (test_bit(ExternalBbl, &rdev->flags))
9044 			sysfs_notify(&rdev->kobj, NULL,
9045 				     "unacknowledged_bad_blocks");
9046 		sysfs_notify_dirent_safe(rdev->sysfs_state);
9047 		set_mask_bits(&mddev->sb_flags, 0,
9048 			      BIT(MD_SB_CHANGE_CLEAN) | BIT(MD_SB_CHANGE_PENDING));
9049 		md_wakeup_thread(rdev->mddev->thread);
9050 		return 1;
9051 	} else
9052 		return 0;
9053 }
9054 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
9055 
9056 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9057 			 int is_new)
9058 {
9059 	int rv;
9060 	if (is_new)
9061 		s += rdev->new_data_offset;
9062 	else
9063 		s += rdev->data_offset;
9064 	rv = badblocks_clear(&rdev->badblocks, s, sectors);
9065 	if ((rv == 0) && test_bit(ExternalBbl, &rdev->flags))
9066 		sysfs_notify(&rdev->kobj, NULL, "bad_blocks");
9067 	return rv;
9068 }
9069 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
9070 
9071 static int md_notify_reboot(struct notifier_block *this,
9072 			    unsigned long code, void *x)
9073 {
9074 	struct list_head *tmp;
9075 	struct mddev *mddev;
9076 	int need_delay = 0;
9077 
9078 	for_each_mddev(mddev, tmp) {
9079 		if (mddev_trylock(mddev)) {
9080 			if (mddev->pers)
9081 				__md_stop_writes(mddev);
9082 			if (mddev->persistent)
9083 				mddev->safemode = 2;
9084 			mddev_unlock(mddev);
9085 		}
9086 		need_delay = 1;
9087 	}
9088 	/*
9089 	 * certain more exotic SCSI devices are known to be
9090 	 * volatile wrt too early system reboots. While the
9091 	 * right place to handle this issue is the given
9092 	 * driver, we do want to have a safe RAID driver ...
9093 	 */
9094 	if (need_delay)
9095 		mdelay(1000*1);
9096 
9097 	return NOTIFY_DONE;
9098 }
9099 
9100 static struct notifier_block md_notifier = {
9101 	.notifier_call	= md_notify_reboot,
9102 	.next		= NULL,
9103 	.priority	= INT_MAX, /* before any real devices */
9104 };
9105 
9106 static void md_geninit(void)
9107 {
9108 	pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
9109 
9110 	proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
9111 }
9112 
9113 static int __init md_init(void)
9114 {
9115 	int ret = -ENOMEM;
9116 
9117 	md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
9118 	if (!md_wq)
9119 		goto err_wq;
9120 
9121 	md_misc_wq = alloc_workqueue("md_misc", 0, 0);
9122 	if (!md_misc_wq)
9123 		goto err_misc_wq;
9124 
9125 	if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
9126 		goto err_md;
9127 
9128 	if ((ret = register_blkdev(0, "mdp")) < 0)
9129 		goto err_mdp;
9130 	mdp_major = ret;
9131 
9132 	blk_register_region(MKDEV(MD_MAJOR, 0), 512, THIS_MODULE,
9133 			    md_probe, NULL, NULL);
9134 	blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
9135 			    md_probe, NULL, NULL);
9136 
9137 	register_reboot_notifier(&md_notifier);
9138 	raid_table_header = register_sysctl_table(raid_root_table);
9139 
9140 	md_geninit();
9141 	return 0;
9142 
9143 err_mdp:
9144 	unregister_blkdev(MD_MAJOR, "md");
9145 err_md:
9146 	destroy_workqueue(md_misc_wq);
9147 err_misc_wq:
9148 	destroy_workqueue(md_wq);
9149 err_wq:
9150 	return ret;
9151 }
9152 
9153 static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
9154 {
9155 	struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
9156 	struct md_rdev *rdev2;
9157 	int role, ret;
9158 	char b[BDEVNAME_SIZE];
9159 
9160 	/*
9161 	 * If size is changed in another node then we need to
9162 	 * do resize as well.
9163 	 */
9164 	if (mddev->dev_sectors != le64_to_cpu(sb->size)) {
9165 		ret = mddev->pers->resize(mddev, le64_to_cpu(sb->size));
9166 		if (ret)
9167 			pr_info("md-cluster: resize failed\n");
9168 		else
9169 			bitmap_update_sb(mddev->bitmap);
9170 	}
9171 
9172 	/* Check for change of roles in the active devices */
9173 	rdev_for_each(rdev2, mddev) {
9174 		if (test_bit(Faulty, &rdev2->flags))
9175 			continue;
9176 
9177 		/* Check if the roles changed */
9178 		role = le16_to_cpu(sb->dev_roles[rdev2->desc_nr]);
9179 
9180 		if (test_bit(Candidate, &rdev2->flags)) {
9181 			if (role == 0xfffe) {
9182 				pr_info("md: Removing Candidate device %s because add failed\n", bdevname(rdev2->bdev,b));
9183 				md_kick_rdev_from_array(rdev2);
9184 				continue;
9185 			}
9186 			else
9187 				clear_bit(Candidate, &rdev2->flags);
9188 		}
9189 
9190 		if (role != rdev2->raid_disk) {
9191 			/* got activated */
9192 			if (rdev2->raid_disk == -1 && role != 0xffff) {
9193 				rdev2->saved_raid_disk = role;
9194 				ret = remove_and_add_spares(mddev, rdev2);
9195 				pr_info("Activated spare: %s\n",
9196 					bdevname(rdev2->bdev,b));
9197 				/* wakeup mddev->thread here, so array could
9198 				 * perform resync with the new activated disk */
9199 				set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9200 				md_wakeup_thread(mddev->thread);
9201 
9202 			}
9203 			/* device faulty
9204 			 * We just want to do the minimum to mark the disk
9205 			 * as faulty. The recovery is performed by the
9206 			 * one who initiated the error.
9207 			 */
9208 			if ((role == 0xfffe) || (role == 0xfffd)) {
9209 				md_error(mddev, rdev2);
9210 				clear_bit(Blocked, &rdev2->flags);
9211 			}
9212 		}
9213 	}
9214 
9215 	if (mddev->raid_disks != le32_to_cpu(sb->raid_disks))
9216 		update_raid_disks(mddev, le32_to_cpu(sb->raid_disks));
9217 
9218 	/* Finally set the event to be up to date */
9219 	mddev->events = le64_to_cpu(sb->events);
9220 }
9221 
9222 static int read_rdev(struct mddev *mddev, struct md_rdev *rdev)
9223 {
9224 	int err;
9225 	struct page *swapout = rdev->sb_page;
9226 	struct mdp_superblock_1 *sb;
9227 
9228 	/* Store the sb page of the rdev in the swapout temporary
9229 	 * variable in case we err in the future
9230 	 */
9231 	rdev->sb_page = NULL;
9232 	err = alloc_disk_sb(rdev);
9233 	if (err == 0) {
9234 		ClearPageUptodate(rdev->sb_page);
9235 		rdev->sb_loaded = 0;
9236 		err = super_types[mddev->major_version].
9237 			load_super(rdev, NULL, mddev->minor_version);
9238 	}
9239 	if (err < 0) {
9240 		pr_warn("%s: %d Could not reload rdev(%d) err: %d. Restoring old values\n",
9241 				__func__, __LINE__, rdev->desc_nr, err);
9242 		if (rdev->sb_page)
9243 			put_page(rdev->sb_page);
9244 		rdev->sb_page = swapout;
9245 		rdev->sb_loaded = 1;
9246 		return err;
9247 	}
9248 
9249 	sb = page_address(rdev->sb_page);
9250 	/* Read the offset unconditionally, even if MD_FEATURE_RECOVERY_OFFSET
9251 	 * is not set
9252 	 */
9253 
9254 	if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET))
9255 		rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
9256 
9257 	/* The other node finished recovery, call spare_active to set
9258 	 * device In_sync and mddev->degraded
9259 	 */
9260 	if (rdev->recovery_offset == MaxSector &&
9261 	    !test_bit(In_sync, &rdev->flags) &&
9262 	    mddev->pers->spare_active(mddev))
9263 		sysfs_notify(&mddev->kobj, NULL, "degraded");
9264 
9265 	put_page(swapout);
9266 	return 0;
9267 }
9268 
9269 void md_reload_sb(struct mddev *mddev, int nr)
9270 {
9271 	struct md_rdev *rdev;
9272 	int err;
9273 
9274 	/* Find the rdev */
9275 	rdev_for_each_rcu(rdev, mddev) {
9276 		if (rdev->desc_nr == nr)
9277 			break;
9278 	}
9279 
9280 	if (!rdev || rdev->desc_nr != nr) {
9281 		pr_warn("%s: %d Could not find rdev with nr %d\n", __func__, __LINE__, nr);
9282 		return;
9283 	}
9284 
9285 	err = read_rdev(mddev, rdev);
9286 	if (err < 0)
9287 		return;
9288 
9289 	check_sb_changes(mddev, rdev);
9290 
9291 	/* Read all rdev's to update recovery_offset */
9292 	rdev_for_each_rcu(rdev, mddev) {
9293 		if (!test_bit(Faulty, &rdev->flags))
9294 			read_rdev(mddev, rdev);
9295 	}
9296 }
9297 EXPORT_SYMBOL(md_reload_sb);
9298 
9299 #ifndef MODULE
9300 
9301 /*
9302  * Searches all registered partitions for autorun RAID arrays
9303  * at boot time.
9304  */
9305 
9306 static DEFINE_MUTEX(detected_devices_mutex);
9307 static LIST_HEAD(all_detected_devices);
9308 struct detected_devices_node {
9309 	struct list_head list;
9310 	dev_t dev;
9311 };
9312 
9313 void md_autodetect_dev(dev_t dev)
9314 {
9315 	struct detected_devices_node *node_detected_dev;
9316 
9317 	node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
9318 	if (node_detected_dev) {
9319 		node_detected_dev->dev = dev;
9320 		mutex_lock(&detected_devices_mutex);
9321 		list_add_tail(&node_detected_dev->list, &all_detected_devices);
9322 		mutex_unlock(&detected_devices_mutex);
9323 	}
9324 }
9325 
9326 static void autostart_arrays(int part)
9327 {
9328 	struct md_rdev *rdev;
9329 	struct detected_devices_node *node_detected_dev;
9330 	dev_t dev;
9331 	int i_scanned, i_passed;
9332 
9333 	i_scanned = 0;
9334 	i_passed = 0;
9335 
9336 	pr_info("md: Autodetecting RAID arrays.\n");
9337 
9338 	mutex_lock(&detected_devices_mutex);
9339 	while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
9340 		i_scanned++;
9341 		node_detected_dev = list_entry(all_detected_devices.next,
9342 					struct detected_devices_node, list);
9343 		list_del(&node_detected_dev->list);
9344 		dev = node_detected_dev->dev;
9345 		kfree(node_detected_dev);
9346 		mutex_unlock(&detected_devices_mutex);
9347 		rdev = md_import_device(dev,0, 90);
9348 		mutex_lock(&detected_devices_mutex);
9349 		if (IS_ERR(rdev))
9350 			continue;
9351 
9352 		if (test_bit(Faulty, &rdev->flags))
9353 			continue;
9354 
9355 		set_bit(AutoDetected, &rdev->flags);
9356 		list_add(&rdev->same_set, &pending_raid_disks);
9357 		i_passed++;
9358 	}
9359 	mutex_unlock(&detected_devices_mutex);
9360 
9361 	pr_debug("md: Scanned %d and added %d devices.\n", i_scanned, i_passed);
9362 
9363 	autorun_devices(part);
9364 }
9365 
9366 #endif /* !MODULE */
9367 
9368 static __exit void md_exit(void)
9369 {
9370 	struct mddev *mddev;
9371 	struct list_head *tmp;
9372 	int delay = 1;
9373 
9374 	blk_unregister_region(MKDEV(MD_MAJOR,0), 512);
9375 	blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
9376 
9377 	unregister_blkdev(MD_MAJOR,"md");
9378 	unregister_blkdev(mdp_major, "mdp");
9379 	unregister_reboot_notifier(&md_notifier);
9380 	unregister_sysctl_table(raid_table_header);
9381 
9382 	/* We cannot unload the modules while some process is
9383 	 * waiting for us in select() or poll() - wake them up
9384 	 */
9385 	md_unloading = 1;
9386 	while (waitqueue_active(&md_event_waiters)) {
9387 		/* not safe to leave yet */
9388 		wake_up(&md_event_waiters);
9389 		msleep(delay);
9390 		delay += delay;
9391 	}
9392 	remove_proc_entry("mdstat", NULL);
9393 
9394 	for_each_mddev(mddev, tmp) {
9395 		export_array(mddev);
9396 		mddev->ctime = 0;
9397 		mddev->hold_active = 0;
9398 		/*
9399 		 * for_each_mddev() will call mddev_put() at the end of each
9400 		 * iteration.  As the mddev is now fully clear, this will
9401 		 * schedule the mddev for destruction by a workqueue, and the
9402 		 * destroy_workqueue() below will wait for that to complete.
9403 		 */
9404 	}
9405 	destroy_workqueue(md_misc_wq);
9406 	destroy_workqueue(md_wq);
9407 }
9408 
9409 subsys_initcall(md_init);
9410 module_exit(md_exit)
9411 
9412 static int get_ro(char *buffer, const struct kernel_param *kp)
9413 {
9414 	return sprintf(buffer, "%d", start_readonly);
9415 }
9416 static int set_ro(const char *val, const struct kernel_param *kp)
9417 {
9418 	return kstrtouint(val, 10, (unsigned int *)&start_readonly);
9419 }
9420 
9421 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
9422 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
9423 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
9424 module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
9425 
9426 MODULE_LICENSE("GPL");
9427 MODULE_DESCRIPTION("MD RAID framework");
9428 MODULE_ALIAS("md");
9429 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);
9430