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