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