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