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