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