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