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