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