md: allow metadata update while suspending.
[linux-stable.git] / drivers / md / md.c
blobb74cca273e38e5b12677292fdddfe35b3cdf0c52
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 "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 struct md_cluster_operations *md_cluster_ops;
88 EXPORT_SYMBOL(md_cluster_ops);
89 struct module *md_cluster_mod;
90 EXPORT_SYMBOL(md_cluster_mod);
92 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
93 static struct workqueue_struct *md_wq;
94 static struct workqueue_struct *md_misc_wq;
96 static int remove_and_add_spares(struct mddev *mddev,
97 struct md_rdev *this);
98 static void mddev_detach(struct mddev *mddev);
101 * Default number of read corrections we'll attempt on an rdev
102 * before ejecting it from the array. We divide the read error
103 * count by 2 for every hour elapsed between read errors.
105 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
107 * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
108 * is 1000 KB/sec, so the extra system load does not show up that much.
109 * Increase it if you want to have more _guaranteed_ speed. Note that
110 * the RAID driver will use the maximum available bandwidth if the IO
111 * subsystem is idle. There is also an 'absolute maximum' reconstruction
112 * speed limit - in case reconstruction slows down your system despite
113 * idle IO detection.
115 * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
116 * or /sys/block/mdX/md/sync_speed_{min,max}
119 static int sysctl_speed_limit_min = 1000;
120 static int sysctl_speed_limit_max = 200000;
121 static inline int speed_min(struct mddev *mddev)
123 return mddev->sync_speed_min ?
124 mddev->sync_speed_min : sysctl_speed_limit_min;
127 static inline int speed_max(struct mddev *mddev)
129 return mddev->sync_speed_max ?
130 mddev->sync_speed_max : sysctl_speed_limit_max;
133 static struct ctl_table_header *raid_table_header;
135 static struct ctl_table raid_table[] = {
137 .procname = "speed_limit_min",
138 .data = &sysctl_speed_limit_min,
139 .maxlen = sizeof(int),
140 .mode = S_IRUGO|S_IWUSR,
141 .proc_handler = proc_dointvec,
144 .procname = "speed_limit_max",
145 .data = &sysctl_speed_limit_max,
146 .maxlen = sizeof(int),
147 .mode = S_IRUGO|S_IWUSR,
148 .proc_handler = proc_dointvec,
153 static struct ctl_table raid_dir_table[] = {
155 .procname = "raid",
156 .maxlen = 0,
157 .mode = S_IRUGO|S_IXUGO,
158 .child = raid_table,
163 static struct ctl_table raid_root_table[] = {
165 .procname = "dev",
166 .maxlen = 0,
167 .mode = 0555,
168 .child = raid_dir_table,
173 static const struct block_device_operations md_fops;
175 static int start_readonly;
178 * The original mechanism for creating an md device is to create
179 * a device node in /dev and to open it. This causes races with device-close.
180 * The preferred method is to write to the "new_array" module parameter.
181 * This can avoid races.
182 * Setting create_on_open to false disables the original mechanism
183 * so all the races disappear.
185 static bool create_on_open = true;
187 /* bio_clone_mddev
188 * like bio_clone_bioset, but with a local bio set
191 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
192 struct mddev *mddev)
194 struct bio *b;
196 if (!mddev || !mddev->bio_set)
197 return bio_alloc(gfp_mask, nr_iovecs);
199 b = bio_alloc_bioset(gfp_mask, nr_iovecs, mddev->bio_set);
200 if (!b)
201 return NULL;
202 return b;
204 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
206 static struct bio *md_bio_alloc_sync(struct mddev *mddev)
208 if (!mddev || !mddev->sync_set)
209 return bio_alloc(GFP_NOIO, 1);
211 return bio_alloc_bioset(GFP_NOIO, 1, mddev->sync_set);
215 * We have a system wide 'event count' that is incremented
216 * on any 'interesting' event, and readers of /proc/mdstat
217 * can use 'poll' or 'select' to find out when the event
218 * count increases.
220 * Events are:
221 * start array, stop array, error, add device, remove device,
222 * start build, activate spare
224 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
225 static atomic_t md_event_count;
226 void md_new_event(struct mddev *mddev)
228 atomic_inc(&md_event_count);
229 wake_up(&md_event_waiters);
231 EXPORT_SYMBOL_GPL(md_new_event);
234 * Enables to iterate over all existing md arrays
235 * all_mddevs_lock protects this list.
237 static LIST_HEAD(all_mddevs);
238 static DEFINE_SPINLOCK(all_mddevs_lock);
241 * iterates through all used mddevs in the system.
242 * We take care to grab the all_mddevs_lock whenever navigating
243 * the list, and to always hold a refcount when unlocked.
244 * Any code which breaks out of this loop while own
245 * a reference to the current mddev and must mddev_put it.
247 #define for_each_mddev(_mddev,_tmp) \
249 for (({ spin_lock(&all_mddevs_lock); \
250 _tmp = all_mddevs.next; \
251 _mddev = NULL;}); \
252 ({ if (_tmp != &all_mddevs) \
253 mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
254 spin_unlock(&all_mddevs_lock); \
255 if (_mddev) mddev_put(_mddev); \
256 _mddev = list_entry(_tmp, struct mddev, all_mddevs); \
257 _tmp != &all_mddevs;}); \
258 ({ spin_lock(&all_mddevs_lock); \
259 _tmp = _tmp->next;}) \
262 /* Rather than calling directly into the personality make_request function,
263 * IO requests come here first so that we can check if the device is
264 * being suspended pending a reconfiguration.
265 * We hold a refcount over the call to ->make_request. By the time that
266 * call has finished, the bio has been linked into some internal structure
267 * and so is visible to ->quiesce(), so we don't need the refcount any more.
269 static bool is_suspended(struct mddev *mddev, struct bio *bio)
271 if (mddev->suspended)
272 return true;
273 if (bio_data_dir(bio) != WRITE)
274 return false;
275 if (mddev->suspend_lo >= mddev->suspend_hi)
276 return false;
277 if (bio->bi_iter.bi_sector >= mddev->suspend_hi)
278 return false;
279 if (bio_end_sector(bio) < mddev->suspend_lo)
280 return false;
281 return true;
284 void md_handle_request(struct mddev *mddev, struct bio *bio)
286 check_suspended:
287 rcu_read_lock();
288 if (is_suspended(mddev, bio)) {
289 DEFINE_WAIT(__wait);
290 for (;;) {
291 prepare_to_wait(&mddev->sb_wait, &__wait,
292 TASK_UNINTERRUPTIBLE);
293 if (!is_suspended(mddev, bio))
294 break;
295 rcu_read_unlock();
296 schedule();
297 rcu_read_lock();
299 finish_wait(&mddev->sb_wait, &__wait);
301 atomic_inc(&mddev->active_io);
302 rcu_read_unlock();
304 if (!mddev->pers->make_request(mddev, bio)) {
305 atomic_dec(&mddev->active_io);
306 wake_up(&mddev->sb_wait);
307 goto check_suspended;
310 if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
311 wake_up(&mddev->sb_wait);
313 EXPORT_SYMBOL(md_handle_request);
315 static blk_qc_t md_make_request(struct request_queue *q, struct bio *bio)
317 const int rw = bio_data_dir(bio);
318 struct mddev *mddev = q->queuedata;
319 unsigned int sectors;
320 int cpu;
322 blk_queue_split(q, &bio);
324 if (mddev == NULL || mddev->pers == NULL) {
325 bio_io_error(bio);
326 return BLK_QC_T_NONE;
328 if (mddev->ro == 1 && unlikely(rw == WRITE)) {
329 if (bio_sectors(bio) != 0)
330 bio->bi_status = BLK_STS_IOERR;
331 bio_endio(bio);
332 return BLK_QC_T_NONE;
336 * save the sectors now since our bio can
337 * go away inside make_request
339 sectors = bio_sectors(bio);
340 /* bio could be mergeable after passing to underlayer */
341 bio->bi_opf &= ~REQ_NOMERGE;
343 md_handle_request(mddev, bio);
345 cpu = part_stat_lock();
346 part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
347 part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
348 part_stat_unlock();
350 return BLK_QC_T_NONE;
353 /* mddev_suspend makes sure no new requests are submitted
354 * to the device, and that any requests that have been submitted
355 * are completely handled.
356 * Once mddev_detach() is called and completes, the module will be
357 * completely unused.
359 void mddev_suspend(struct mddev *mddev)
361 WARN_ON_ONCE(mddev->thread && current == mddev->thread->tsk);
362 lockdep_assert_held(&mddev->reconfig_mutex);
363 if (mddev->suspended++)
364 return;
365 synchronize_rcu();
366 wake_up(&mddev->sb_wait);
367 set_bit(MD_ALLOW_SB_UPDATE, &mddev->flags);
368 smp_mb__after_atomic();
369 wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
370 mddev->pers->quiesce(mddev, 1);
371 clear_bit_unlock(MD_ALLOW_SB_UPDATE, &mddev->flags);
372 wait_event(mddev->sb_wait, !test_bit(MD_UPDATING_SB, &mddev->flags));
374 del_timer_sync(&mddev->safemode_timer);
376 EXPORT_SYMBOL_GPL(mddev_suspend);
378 void mddev_resume(struct mddev *mddev)
380 lockdep_assert_held(&mddev->reconfig_mutex);
381 if (--mddev->suspended)
382 return;
383 wake_up(&mddev->sb_wait);
384 mddev->pers->quiesce(mddev, 0);
386 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
387 md_wakeup_thread(mddev->thread);
388 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
390 EXPORT_SYMBOL_GPL(mddev_resume);
392 int mddev_congested(struct mddev *mddev, int bits)
394 struct md_personality *pers = mddev->pers;
395 int ret = 0;
397 rcu_read_lock();
398 if (mddev->suspended)
399 ret = 1;
400 else if (pers && pers->congested)
401 ret = pers->congested(mddev, bits);
402 rcu_read_unlock();
403 return ret;
405 EXPORT_SYMBOL_GPL(mddev_congested);
406 static int md_congested(void *data, int bits)
408 struct mddev *mddev = data;
409 return mddev_congested(mddev, bits);
413 * Generic flush handling for md
416 static void md_end_flush(struct bio *bio)
418 struct md_rdev *rdev = bio->bi_private;
419 struct mddev *mddev = rdev->mddev;
421 rdev_dec_pending(rdev, mddev);
423 if (atomic_dec_and_test(&mddev->flush_pending)) {
424 /* The pre-request flush has finished */
425 queue_work(md_wq, &mddev->flush_work);
427 bio_put(bio);
430 static void md_submit_flush_data(struct work_struct *ws);
432 static void submit_flushes(struct work_struct *ws)
434 struct mddev *mddev = container_of(ws, struct mddev, flush_work);
435 struct md_rdev *rdev;
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->flush_bio = NULL;
478 wake_up(&mddev->sb_wait);
480 if (bio->bi_iter.bi_size == 0)
481 /* an empty barrier - all done */
482 bio_endio(bio);
483 else {
484 bio->bi_opf &= ~REQ_PREFLUSH;
485 md_handle_request(mddev, bio);
489 void md_flush_request(struct mddev *mddev, struct bio *bio)
491 spin_lock_irq(&mddev->lock);
492 wait_event_lock_irq(mddev->sb_wait,
493 !mddev->flush_bio,
494 mddev->lock);
495 mddev->flush_bio = bio;
496 spin_unlock_irq(&mddev->lock);
498 INIT_WORK(&mddev->flush_work, submit_flushes);
499 queue_work(md_wq, &mddev->flush_work);
501 EXPORT_SYMBOL(md_flush_request);
503 static inline struct mddev *mddev_get(struct mddev *mddev)
505 atomic_inc(&mddev->active);
506 return mddev;
509 static void mddev_delayed_delete(struct work_struct *ws);
511 static void mddev_put(struct mddev *mddev)
513 struct bio_set *bs = NULL, *sync_bs = NULL;
515 if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
516 return;
517 if (!mddev->raid_disks && list_empty(&mddev->disks) &&
518 mddev->ctime == 0 && !mddev->hold_active) {
519 /* Array is not configured at all, and not held active,
520 * so destroy it */
521 list_del_init(&mddev->all_mddevs);
522 bs = mddev->bio_set;
523 sync_bs = mddev->sync_set;
524 mddev->bio_set = NULL;
525 mddev->sync_set = NULL;
526 if (mddev->gendisk) {
527 /* We did a probe so need to clean up. Call
528 * queue_work inside the spinlock so that
529 * flush_workqueue() after mddev_find will
530 * succeed in waiting for the work to be done.
532 INIT_WORK(&mddev->del_work, mddev_delayed_delete);
533 queue_work(md_misc_wq, &mddev->del_work);
534 } else
535 kfree(mddev);
537 spin_unlock(&all_mddevs_lock);
538 if (bs)
539 bioset_free(bs);
540 if (sync_bs)
541 bioset_free(sync_bs);
544 static void md_safemode_timeout(unsigned long data);
546 void mddev_init(struct mddev *mddev)
548 mutex_init(&mddev->open_mutex);
549 mutex_init(&mddev->reconfig_mutex);
550 mutex_init(&mddev->bitmap_info.mutex);
551 INIT_LIST_HEAD(&mddev->disks);
552 INIT_LIST_HEAD(&mddev->all_mddevs);
553 setup_timer(&mddev->safemode_timer, md_safemode_timeout,
554 (unsigned long) mddev);
555 atomic_set(&mddev->active, 1);
556 atomic_set(&mddev->openers, 0);
557 atomic_set(&mddev->active_io, 0);
558 spin_lock_init(&mddev->lock);
559 atomic_set(&mddev->flush_pending, 0);
560 init_waitqueue_head(&mddev->sb_wait);
561 init_waitqueue_head(&mddev->recovery_wait);
562 mddev->reshape_position = MaxSector;
563 mddev->reshape_backwards = 0;
564 mddev->last_sync_action = "none";
565 mddev->resync_min = 0;
566 mddev->resync_max = MaxSector;
567 mddev->level = LEVEL_NONE;
569 EXPORT_SYMBOL_GPL(mddev_init);
571 static struct mddev *mddev_find(dev_t unit)
573 struct mddev *mddev, *new = NULL;
575 if (unit && MAJOR(unit) != MD_MAJOR)
576 unit &= ~((1<<MdpMinorShift)-1);
578 retry:
579 spin_lock(&all_mddevs_lock);
581 if (unit) {
582 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
583 if (mddev->unit == unit) {
584 mddev_get(mddev);
585 spin_unlock(&all_mddevs_lock);
586 kfree(new);
587 return mddev;
590 if (new) {
591 list_add(&new->all_mddevs, &all_mddevs);
592 spin_unlock(&all_mddevs_lock);
593 new->hold_active = UNTIL_IOCTL;
594 return new;
596 } else if (new) {
597 /* find an unused unit number */
598 static int next_minor = 512;
599 int start = next_minor;
600 int is_free = 0;
601 int dev = 0;
602 while (!is_free) {
603 dev = MKDEV(MD_MAJOR, next_minor);
604 next_minor++;
605 if (next_minor > MINORMASK)
606 next_minor = 0;
607 if (next_minor == start) {
608 /* Oh dear, all in use. */
609 spin_unlock(&all_mddevs_lock);
610 kfree(new);
611 return NULL;
614 is_free = 1;
615 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
616 if (mddev->unit == dev) {
617 is_free = 0;
618 break;
621 new->unit = dev;
622 new->md_minor = MINOR(dev);
623 new->hold_active = UNTIL_STOP;
624 list_add(&new->all_mddevs, &all_mddevs);
625 spin_unlock(&all_mddevs_lock);
626 return new;
628 spin_unlock(&all_mddevs_lock);
630 new = kzalloc(sizeof(*new), GFP_KERNEL);
631 if (!new)
632 return NULL;
634 new->unit = unit;
635 if (MAJOR(unit) == MD_MAJOR)
636 new->md_minor = MINOR(unit);
637 else
638 new->md_minor = MINOR(unit) >> MdpMinorShift;
640 mddev_init(new);
642 goto retry;
645 static struct attribute_group md_redundancy_group;
647 void mddev_unlock(struct mddev *mddev)
649 if (mddev->to_remove) {
650 /* These cannot be removed under reconfig_mutex as
651 * an access to the files will try to take reconfig_mutex
652 * while holding the file unremovable, which leads to
653 * a deadlock.
654 * So hold set sysfs_active while the remove in happeing,
655 * and anything else which might set ->to_remove or my
656 * otherwise change the sysfs namespace will fail with
657 * -EBUSY if sysfs_active is still set.
658 * We set sysfs_active under reconfig_mutex and elsewhere
659 * test it under the same mutex to ensure its correct value
660 * is seen.
662 struct attribute_group *to_remove = mddev->to_remove;
663 mddev->to_remove = NULL;
664 mddev->sysfs_active = 1;
665 mutex_unlock(&mddev->reconfig_mutex);
667 if (mddev->kobj.sd) {
668 if (to_remove != &md_redundancy_group)
669 sysfs_remove_group(&mddev->kobj, to_remove);
670 if (mddev->pers == NULL ||
671 mddev->pers->sync_request == NULL) {
672 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
673 if (mddev->sysfs_action)
674 sysfs_put(mddev->sysfs_action);
675 mddev->sysfs_action = NULL;
678 mddev->sysfs_active = 0;
679 } else
680 mutex_unlock(&mddev->reconfig_mutex);
682 /* As we've dropped the mutex we need a spinlock to
683 * make sure the thread doesn't disappear
685 spin_lock(&pers_lock);
686 md_wakeup_thread(mddev->thread);
687 wake_up(&mddev->sb_wait);
688 spin_unlock(&pers_lock);
690 EXPORT_SYMBOL_GPL(mddev_unlock);
692 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr)
694 struct md_rdev *rdev;
696 rdev_for_each_rcu(rdev, mddev)
697 if (rdev->desc_nr == nr)
698 return rdev;
700 return NULL;
702 EXPORT_SYMBOL_GPL(md_find_rdev_nr_rcu);
704 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
706 struct md_rdev *rdev;
708 rdev_for_each(rdev, mddev)
709 if (rdev->bdev->bd_dev == dev)
710 return rdev;
712 return NULL;
715 static struct md_rdev *find_rdev_rcu(struct mddev *mddev, dev_t dev)
717 struct md_rdev *rdev;
719 rdev_for_each_rcu(rdev, mddev)
720 if (rdev->bdev->bd_dev == dev)
721 return rdev;
723 return NULL;
726 static struct md_personality *find_pers(int level, char *clevel)
728 struct md_personality *pers;
729 list_for_each_entry(pers, &pers_list, list) {
730 if (level != LEVEL_NONE && pers->level == level)
731 return pers;
732 if (strcmp(pers->name, clevel)==0)
733 return pers;
735 return NULL;
738 /* return the offset of the super block in 512byte sectors */
739 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
741 sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
742 return MD_NEW_SIZE_SECTORS(num_sectors);
745 static int alloc_disk_sb(struct md_rdev *rdev)
747 rdev->sb_page = alloc_page(GFP_KERNEL);
748 if (!rdev->sb_page)
749 return -ENOMEM;
750 return 0;
753 void md_rdev_clear(struct md_rdev *rdev)
755 if (rdev->sb_page) {
756 put_page(rdev->sb_page);
757 rdev->sb_loaded = 0;
758 rdev->sb_page = NULL;
759 rdev->sb_start = 0;
760 rdev->sectors = 0;
762 if (rdev->bb_page) {
763 put_page(rdev->bb_page);
764 rdev->bb_page = NULL;
766 badblocks_exit(&rdev->badblocks);
768 EXPORT_SYMBOL_GPL(md_rdev_clear);
770 static void super_written(struct bio *bio)
772 struct md_rdev *rdev = bio->bi_private;
773 struct mddev *mddev = rdev->mddev;
775 if (bio->bi_status) {
776 pr_err("md: super_written gets error=%d\n", bio->bi_status);
777 md_error(mddev, rdev);
778 if (!test_bit(Faulty, &rdev->flags)
779 && (bio->bi_opf & MD_FAILFAST)) {
780 set_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags);
781 set_bit(LastDev, &rdev->flags);
783 } else
784 clear_bit(LastDev, &rdev->flags);
786 if (atomic_dec_and_test(&mddev->pending_writes))
787 wake_up(&mddev->sb_wait);
788 rdev_dec_pending(rdev, mddev);
789 bio_put(bio);
792 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
793 sector_t sector, int size, struct page *page)
795 /* write first size bytes of page to sector of rdev
796 * Increment mddev->pending_writes before returning
797 * and decrement it on completion, waking up sb_wait
798 * if zero is reached.
799 * If an error occurred, call md_error
801 struct bio *bio;
802 int ff = 0;
804 if (!page)
805 return;
807 if (test_bit(Faulty, &rdev->flags))
808 return;
810 bio = md_bio_alloc_sync(mddev);
812 atomic_inc(&rdev->nr_pending);
814 bio_set_dev(bio, rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev);
815 bio->bi_iter.bi_sector = sector;
816 bio_add_page(bio, page, size, 0);
817 bio->bi_private = rdev;
818 bio->bi_end_io = super_written;
820 if (test_bit(MD_FAILFAST_SUPPORTED, &mddev->flags) &&
821 test_bit(FailFast, &rdev->flags) &&
822 !test_bit(LastDev, &rdev->flags))
823 ff = MD_FAILFAST;
824 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH | REQ_FUA | ff;
826 atomic_inc(&mddev->pending_writes);
827 submit_bio(bio);
830 int md_super_wait(struct mddev *mddev)
832 /* wait for all superblock writes that were scheduled to complete */
833 wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
834 if (test_and_clear_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags))
835 return -EAGAIN;
836 return 0;
839 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
840 struct page *page, int op, int op_flags, bool metadata_op)
842 struct bio *bio = md_bio_alloc_sync(rdev->mddev);
843 int ret;
845 if (metadata_op && rdev->meta_bdev)
846 bio_set_dev(bio, rdev->meta_bdev);
847 else
848 bio_set_dev(bio, rdev->bdev);
849 bio_set_op_attrs(bio, op, op_flags);
850 if (metadata_op)
851 bio->bi_iter.bi_sector = sector + rdev->sb_start;
852 else if (rdev->mddev->reshape_position != MaxSector &&
853 (rdev->mddev->reshape_backwards ==
854 (sector >= rdev->mddev->reshape_position)))
855 bio->bi_iter.bi_sector = sector + rdev->new_data_offset;
856 else
857 bio->bi_iter.bi_sector = sector + rdev->data_offset;
858 bio_add_page(bio, page, size, 0);
860 submit_bio_wait(bio);
862 ret = !bio->bi_status;
863 bio_put(bio);
864 return ret;
866 EXPORT_SYMBOL_GPL(sync_page_io);
868 static int read_disk_sb(struct md_rdev *rdev, int size)
870 char b[BDEVNAME_SIZE];
872 if (rdev->sb_loaded)
873 return 0;
875 if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, true))
876 goto fail;
877 rdev->sb_loaded = 1;
878 return 0;
880 fail:
881 pr_err("md: disabled device %s, could not read superblock.\n",
882 bdevname(rdev->bdev,b));
883 return -EINVAL;
886 static int md_uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
888 return sb1->set_uuid0 == sb2->set_uuid0 &&
889 sb1->set_uuid1 == sb2->set_uuid1 &&
890 sb1->set_uuid2 == sb2->set_uuid2 &&
891 sb1->set_uuid3 == sb2->set_uuid3;
894 static int md_sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
896 int ret;
897 mdp_super_t *tmp1, *tmp2;
899 tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
900 tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
902 if (!tmp1 || !tmp2) {
903 ret = 0;
904 goto abort;
907 *tmp1 = *sb1;
908 *tmp2 = *sb2;
911 * nr_disks is not constant
913 tmp1->nr_disks = 0;
914 tmp2->nr_disks = 0;
916 ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
917 abort:
918 kfree(tmp1);
919 kfree(tmp2);
920 return ret;
923 static u32 md_csum_fold(u32 csum)
925 csum = (csum & 0xffff) + (csum >> 16);
926 return (csum & 0xffff) + (csum >> 16);
929 static unsigned int calc_sb_csum(mdp_super_t *sb)
931 u64 newcsum = 0;
932 u32 *sb32 = (u32*)sb;
933 int i;
934 unsigned int disk_csum, csum;
936 disk_csum = sb->sb_csum;
937 sb->sb_csum = 0;
939 for (i = 0; i < MD_SB_BYTES/4 ; i++)
940 newcsum += sb32[i];
941 csum = (newcsum & 0xffffffff) + (newcsum>>32);
943 #ifdef CONFIG_ALPHA
944 /* This used to use csum_partial, which was wrong for several
945 * reasons including that different results are returned on
946 * different architectures. It isn't critical that we get exactly
947 * the same return value as before (we always csum_fold before
948 * testing, and that removes any differences). However as we
949 * know that csum_partial always returned a 16bit value on
950 * alphas, do a fold to maximise conformity to previous behaviour.
952 sb->sb_csum = md_csum_fold(disk_csum);
953 #else
954 sb->sb_csum = disk_csum;
955 #endif
956 return csum;
960 * Handle superblock details.
961 * We want to be able to handle multiple superblock formats
962 * so we have a common interface to them all, and an array of
963 * different handlers.
964 * We rely on user-space to write the initial superblock, and support
965 * reading and updating of superblocks.
966 * Interface methods are:
967 * int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
968 * loads and validates a superblock on dev.
969 * if refdev != NULL, compare superblocks on both devices
970 * Return:
971 * 0 - dev has a superblock that is compatible with refdev
972 * 1 - dev has a superblock that is compatible and newer than refdev
973 * so dev should be used as the refdev in future
974 * -EINVAL superblock incompatible or invalid
975 * -othererror e.g. -EIO
977 * int validate_super(struct mddev *mddev, struct md_rdev *dev)
978 * Verify that dev is acceptable into mddev.
979 * The first time, mddev->raid_disks will be 0, and data from
980 * dev should be merged in. Subsequent calls check that dev
981 * is new enough. Return 0 or -EINVAL
983 * void sync_super(struct mddev *mddev, struct md_rdev *dev)
984 * Update the superblock for rdev with data in mddev
985 * This does not write to disc.
989 struct super_type {
990 char *name;
991 struct module *owner;
992 int (*load_super)(struct md_rdev *rdev,
993 struct md_rdev *refdev,
994 int minor_version);
995 int (*validate_super)(struct mddev *mddev,
996 struct md_rdev *rdev);
997 void (*sync_super)(struct mddev *mddev,
998 struct md_rdev *rdev);
999 unsigned long long (*rdev_size_change)(struct md_rdev *rdev,
1000 sector_t num_sectors);
1001 int (*allow_new_offset)(struct md_rdev *rdev,
1002 unsigned long long new_offset);
1006 * Check that the given mddev has no bitmap.
1008 * This function is called from the run method of all personalities that do not
1009 * support bitmaps. It prints an error message and returns non-zero if mddev
1010 * has a bitmap. Otherwise, it returns 0.
1013 int md_check_no_bitmap(struct mddev *mddev)
1015 if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1016 return 0;
1017 pr_warn("%s: bitmaps are not supported for %s\n",
1018 mdname(mddev), mddev->pers->name);
1019 return 1;
1021 EXPORT_SYMBOL(md_check_no_bitmap);
1024 * load_super for 0.90.0
1026 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1028 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1029 mdp_super_t *sb;
1030 int ret;
1033 * Calculate the position of the superblock (512byte sectors),
1034 * it's at the end of the disk.
1036 * It also happens to be a multiple of 4Kb.
1038 rdev->sb_start = calc_dev_sboffset(rdev);
1040 ret = read_disk_sb(rdev, MD_SB_BYTES);
1041 if (ret)
1042 return ret;
1044 ret = -EINVAL;
1046 bdevname(rdev->bdev, b);
1047 sb = page_address(rdev->sb_page);
1049 if (sb->md_magic != MD_SB_MAGIC) {
1050 pr_warn("md: invalid raid superblock magic on %s\n", b);
1051 goto abort;
1054 if (sb->major_version != 0 ||
1055 sb->minor_version < 90 ||
1056 sb->minor_version > 91) {
1057 pr_warn("Bad version number %d.%d on %s\n",
1058 sb->major_version, sb->minor_version, b);
1059 goto abort;
1062 if (sb->raid_disks <= 0)
1063 goto abort;
1065 if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1066 pr_warn("md: invalid superblock checksum on %s\n", b);
1067 goto abort;
1070 rdev->preferred_minor = sb->md_minor;
1071 rdev->data_offset = 0;
1072 rdev->new_data_offset = 0;
1073 rdev->sb_size = MD_SB_BYTES;
1074 rdev->badblocks.shift = -1;
1076 if (sb->level == LEVEL_MULTIPATH)
1077 rdev->desc_nr = -1;
1078 else
1079 rdev->desc_nr = sb->this_disk.number;
1081 if (!refdev) {
1082 ret = 1;
1083 } else {
1084 __u64 ev1, ev2;
1085 mdp_super_t *refsb = page_address(refdev->sb_page);
1086 if (!md_uuid_equal(refsb, sb)) {
1087 pr_warn("md: %s has different UUID to %s\n",
1088 b, bdevname(refdev->bdev,b2));
1089 goto abort;
1091 if (!md_sb_equal(refsb, sb)) {
1092 pr_warn("md: %s has same UUID but different superblock to %s\n",
1093 b, bdevname(refdev->bdev, b2));
1094 goto abort;
1096 ev1 = md_event(sb);
1097 ev2 = md_event(refsb);
1098 if (ev1 > ev2)
1099 ret = 1;
1100 else
1101 ret = 0;
1103 rdev->sectors = rdev->sb_start;
1104 /* Limit to 4TB as metadata cannot record more than that.
1105 * (not needed for Linear and RAID0 as metadata doesn't
1106 * record this size)
1108 if (IS_ENABLED(CONFIG_LBDAF) && (u64)rdev->sectors >= (2ULL << 32) &&
1109 sb->level >= 1)
1110 rdev->sectors = (sector_t)(2ULL << 32) - 2;
1112 if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1113 /* "this cannot possibly happen" ... */
1114 ret = -EINVAL;
1116 abort:
1117 return ret;
1121 * validate_super for 0.90.0
1123 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1125 mdp_disk_t *desc;
1126 mdp_super_t *sb = page_address(rdev->sb_page);
1127 __u64 ev1 = md_event(sb);
1129 rdev->raid_disk = -1;
1130 clear_bit(Faulty, &rdev->flags);
1131 clear_bit(In_sync, &rdev->flags);
1132 clear_bit(Bitmap_sync, &rdev->flags);
1133 clear_bit(WriteMostly, &rdev->flags);
1135 if (mddev->raid_disks == 0) {
1136 mddev->major_version = 0;
1137 mddev->minor_version = sb->minor_version;
1138 mddev->patch_version = sb->patch_version;
1139 mddev->external = 0;
1140 mddev->chunk_sectors = sb->chunk_size >> 9;
1141 mddev->ctime = sb->ctime;
1142 mddev->utime = sb->utime;
1143 mddev->level = sb->level;
1144 mddev->clevel[0] = 0;
1145 mddev->layout = sb->layout;
1146 mddev->raid_disks = sb->raid_disks;
1147 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1148 mddev->events = ev1;
1149 mddev->bitmap_info.offset = 0;
1150 mddev->bitmap_info.space = 0;
1151 /* bitmap can use 60 K after the 4K superblocks */
1152 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1153 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1154 mddev->reshape_backwards = 0;
1156 if (mddev->minor_version >= 91) {
1157 mddev->reshape_position = sb->reshape_position;
1158 mddev->delta_disks = sb->delta_disks;
1159 mddev->new_level = sb->new_level;
1160 mddev->new_layout = sb->new_layout;
1161 mddev->new_chunk_sectors = sb->new_chunk >> 9;
1162 if (mddev->delta_disks < 0)
1163 mddev->reshape_backwards = 1;
1164 } else {
1165 mddev->reshape_position = MaxSector;
1166 mddev->delta_disks = 0;
1167 mddev->new_level = mddev->level;
1168 mddev->new_layout = mddev->layout;
1169 mddev->new_chunk_sectors = mddev->chunk_sectors;
1172 if (sb->state & (1<<MD_SB_CLEAN))
1173 mddev->recovery_cp = MaxSector;
1174 else {
1175 if (sb->events_hi == sb->cp_events_hi &&
1176 sb->events_lo == sb->cp_events_lo) {
1177 mddev->recovery_cp = sb->recovery_cp;
1178 } else
1179 mddev->recovery_cp = 0;
1182 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1183 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1184 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1185 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1187 mddev->max_disks = MD_SB_DISKS;
1189 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1190 mddev->bitmap_info.file == NULL) {
1191 mddev->bitmap_info.offset =
1192 mddev->bitmap_info.default_offset;
1193 mddev->bitmap_info.space =
1194 mddev->bitmap_info.default_space;
1197 } else if (mddev->pers == NULL) {
1198 /* Insist on good event counter while assembling, except
1199 * for spares (which don't need an event count) */
1200 ++ev1;
1201 if (sb->disks[rdev->desc_nr].state & (
1202 (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1203 if (ev1 < mddev->events)
1204 return -EINVAL;
1205 } else if (mddev->bitmap) {
1206 /* if adding to array with a bitmap, then we can accept an
1207 * older device ... but not too old.
1209 if (ev1 < mddev->bitmap->events_cleared)
1210 return 0;
1211 if (ev1 < mddev->events)
1212 set_bit(Bitmap_sync, &rdev->flags);
1213 } else {
1214 if (ev1 < mddev->events)
1215 /* just a hot-add of a new device, leave raid_disk at -1 */
1216 return 0;
1219 if (mddev->level != LEVEL_MULTIPATH) {
1220 desc = sb->disks + rdev->desc_nr;
1222 if (desc->state & (1<<MD_DISK_FAULTY))
1223 set_bit(Faulty, &rdev->flags);
1224 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1225 desc->raid_disk < mddev->raid_disks */) {
1226 set_bit(In_sync, &rdev->flags);
1227 rdev->raid_disk = desc->raid_disk;
1228 rdev->saved_raid_disk = desc->raid_disk;
1229 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1230 /* active but not in sync implies recovery up to
1231 * reshape position. We don't know exactly where
1232 * that is, so set to zero for now */
1233 if (mddev->minor_version >= 91) {
1234 rdev->recovery_offset = 0;
1235 rdev->raid_disk = desc->raid_disk;
1238 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1239 set_bit(WriteMostly, &rdev->flags);
1240 if (desc->state & (1<<MD_DISK_FAILFAST))
1241 set_bit(FailFast, &rdev->flags);
1242 } else /* MULTIPATH are always insync */
1243 set_bit(In_sync, &rdev->flags);
1244 return 0;
1248 * sync_super for 0.90.0
1250 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1252 mdp_super_t *sb;
1253 struct md_rdev *rdev2;
1254 int next_spare = mddev->raid_disks;
1256 /* make rdev->sb match mddev data..
1258 * 1/ zero out disks
1259 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1260 * 3/ any empty disks < next_spare become removed
1262 * disks[0] gets initialised to REMOVED because
1263 * we cannot be sure from other fields if it has
1264 * been initialised or not.
1266 int i;
1267 int active=0, working=0,failed=0,spare=0,nr_disks=0;
1269 rdev->sb_size = MD_SB_BYTES;
1271 sb = page_address(rdev->sb_page);
1273 memset(sb, 0, sizeof(*sb));
1275 sb->md_magic = MD_SB_MAGIC;
1276 sb->major_version = mddev->major_version;
1277 sb->patch_version = mddev->patch_version;
1278 sb->gvalid_words = 0; /* ignored */
1279 memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1280 memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1281 memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1282 memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1284 sb->ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
1285 sb->level = mddev->level;
1286 sb->size = mddev->dev_sectors / 2;
1287 sb->raid_disks = mddev->raid_disks;
1288 sb->md_minor = mddev->md_minor;
1289 sb->not_persistent = 0;
1290 sb->utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
1291 sb->state = 0;
1292 sb->events_hi = (mddev->events>>32);
1293 sb->events_lo = (u32)mddev->events;
1295 if (mddev->reshape_position == MaxSector)
1296 sb->minor_version = 90;
1297 else {
1298 sb->minor_version = 91;
1299 sb->reshape_position = mddev->reshape_position;
1300 sb->new_level = mddev->new_level;
1301 sb->delta_disks = mddev->delta_disks;
1302 sb->new_layout = mddev->new_layout;
1303 sb->new_chunk = mddev->new_chunk_sectors << 9;
1305 mddev->minor_version = sb->minor_version;
1306 if (mddev->in_sync)
1308 sb->recovery_cp = mddev->recovery_cp;
1309 sb->cp_events_hi = (mddev->events>>32);
1310 sb->cp_events_lo = (u32)mddev->events;
1311 if (mddev->recovery_cp == MaxSector)
1312 sb->state = (1<< MD_SB_CLEAN);
1313 } else
1314 sb->recovery_cp = 0;
1316 sb->layout = mddev->layout;
1317 sb->chunk_size = mddev->chunk_sectors << 9;
1319 if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1320 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1322 sb->disks[0].state = (1<<MD_DISK_REMOVED);
1323 rdev_for_each(rdev2, mddev) {
1324 mdp_disk_t *d;
1325 int desc_nr;
1326 int is_active = test_bit(In_sync, &rdev2->flags);
1328 if (rdev2->raid_disk >= 0 &&
1329 sb->minor_version >= 91)
1330 /* we have nowhere to store the recovery_offset,
1331 * but if it is not below the reshape_position,
1332 * we can piggy-back on that.
1334 is_active = 1;
1335 if (rdev2->raid_disk < 0 ||
1336 test_bit(Faulty, &rdev2->flags))
1337 is_active = 0;
1338 if (is_active)
1339 desc_nr = rdev2->raid_disk;
1340 else
1341 desc_nr = next_spare++;
1342 rdev2->desc_nr = desc_nr;
1343 d = &sb->disks[rdev2->desc_nr];
1344 nr_disks++;
1345 d->number = rdev2->desc_nr;
1346 d->major = MAJOR(rdev2->bdev->bd_dev);
1347 d->minor = MINOR(rdev2->bdev->bd_dev);
1348 if (is_active)
1349 d->raid_disk = rdev2->raid_disk;
1350 else
1351 d->raid_disk = rdev2->desc_nr; /* compatibility */
1352 if (test_bit(Faulty, &rdev2->flags))
1353 d->state = (1<<MD_DISK_FAULTY);
1354 else if (is_active) {
1355 d->state = (1<<MD_DISK_ACTIVE);
1356 if (test_bit(In_sync, &rdev2->flags))
1357 d->state |= (1<<MD_DISK_SYNC);
1358 active++;
1359 working++;
1360 } else {
1361 d->state = 0;
1362 spare++;
1363 working++;
1365 if (test_bit(WriteMostly, &rdev2->flags))
1366 d->state |= (1<<MD_DISK_WRITEMOSTLY);
1367 if (test_bit(FailFast, &rdev2->flags))
1368 d->state |= (1<<MD_DISK_FAILFAST);
1370 /* now set the "removed" and "faulty" bits on any missing devices */
1371 for (i=0 ; i < mddev->raid_disks ; i++) {
1372 mdp_disk_t *d = &sb->disks[i];
1373 if (d->state == 0 && d->number == 0) {
1374 d->number = i;
1375 d->raid_disk = i;
1376 d->state = (1<<MD_DISK_REMOVED);
1377 d->state |= (1<<MD_DISK_FAULTY);
1378 failed++;
1381 sb->nr_disks = nr_disks;
1382 sb->active_disks = active;
1383 sb->working_disks = working;
1384 sb->failed_disks = failed;
1385 sb->spare_disks = spare;
1387 sb->this_disk = sb->disks[rdev->desc_nr];
1388 sb->sb_csum = calc_sb_csum(sb);
1392 * rdev_size_change for 0.90.0
1394 static unsigned long long
1395 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1397 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1398 return 0; /* component must fit device */
1399 if (rdev->mddev->bitmap_info.offset)
1400 return 0; /* can't move bitmap */
1401 rdev->sb_start = calc_dev_sboffset(rdev);
1402 if (!num_sectors || num_sectors > rdev->sb_start)
1403 num_sectors = rdev->sb_start;
1404 /* Limit to 4TB as metadata cannot record more than that.
1405 * 4TB == 2^32 KB, or 2*2^32 sectors.
1407 if (IS_ENABLED(CONFIG_LBDAF) && (u64)num_sectors >= (2ULL << 32) &&
1408 rdev->mddev->level >= 1)
1409 num_sectors = (sector_t)(2ULL << 32) - 2;
1410 do {
1411 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1412 rdev->sb_page);
1413 } while (md_super_wait(rdev->mddev) < 0);
1414 return num_sectors;
1417 static int
1418 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1420 /* non-zero offset changes not possible with v0.90 */
1421 return new_offset == 0;
1425 * version 1 superblock
1428 static __le32 calc_sb_1_csum(struct mdp_superblock_1 *sb)
1430 __le32 disk_csum;
1431 u32 csum;
1432 unsigned long long newcsum;
1433 int size = 256 + le32_to_cpu(sb->max_dev)*2;
1434 __le32 *isuper = (__le32*)sb;
1436 disk_csum = sb->sb_csum;
1437 sb->sb_csum = 0;
1438 newcsum = 0;
1439 for (; size >= 4; size -= 4)
1440 newcsum += le32_to_cpu(*isuper++);
1442 if (size == 2)
1443 newcsum += le16_to_cpu(*(__le16*) isuper);
1445 csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1446 sb->sb_csum = disk_csum;
1447 return cpu_to_le32(csum);
1450 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1452 struct mdp_superblock_1 *sb;
1453 int ret;
1454 sector_t sb_start;
1455 sector_t sectors;
1456 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1457 int bmask;
1460 * Calculate the position of the superblock in 512byte sectors.
1461 * It is always aligned to a 4K boundary and
1462 * depeding on minor_version, it can be:
1463 * 0: At least 8K, but less than 12K, from end of device
1464 * 1: At start of device
1465 * 2: 4K from start of device.
1467 switch(minor_version) {
1468 case 0:
1469 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1470 sb_start -= 8*2;
1471 sb_start &= ~(sector_t)(4*2-1);
1472 break;
1473 case 1:
1474 sb_start = 0;
1475 break;
1476 case 2:
1477 sb_start = 8;
1478 break;
1479 default:
1480 return -EINVAL;
1482 rdev->sb_start = sb_start;
1484 /* superblock is rarely larger than 1K, but it can be larger,
1485 * and it is safe to read 4k, so we do that
1487 ret = read_disk_sb(rdev, 4096);
1488 if (ret) return ret;
1490 sb = page_address(rdev->sb_page);
1492 if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1493 sb->major_version != cpu_to_le32(1) ||
1494 le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1495 le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1496 (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1497 return -EINVAL;
1499 if (calc_sb_1_csum(sb) != sb->sb_csum) {
1500 pr_warn("md: invalid superblock checksum on %s\n",
1501 bdevname(rdev->bdev,b));
1502 return -EINVAL;
1504 if (le64_to_cpu(sb->data_size) < 10) {
1505 pr_warn("md: data_size too small on %s\n",
1506 bdevname(rdev->bdev,b));
1507 return -EINVAL;
1509 if (sb->pad0 ||
1510 sb->pad3[0] ||
1511 memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1512 /* Some padding is non-zero, might be a new feature */
1513 return -EINVAL;
1515 rdev->preferred_minor = 0xffff;
1516 rdev->data_offset = le64_to_cpu(sb->data_offset);
1517 rdev->new_data_offset = rdev->data_offset;
1518 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1519 (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1520 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1521 atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1523 rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1524 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1525 if (rdev->sb_size & bmask)
1526 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1528 if (minor_version
1529 && rdev->data_offset < sb_start + (rdev->sb_size/512))
1530 return -EINVAL;
1531 if (minor_version
1532 && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1533 return -EINVAL;
1535 if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1536 rdev->desc_nr = -1;
1537 else
1538 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1540 if (!rdev->bb_page) {
1541 rdev->bb_page = alloc_page(GFP_KERNEL);
1542 if (!rdev->bb_page)
1543 return -ENOMEM;
1545 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1546 rdev->badblocks.count == 0) {
1547 /* need to load the bad block list.
1548 * Currently we limit it to one page.
1550 s32 offset;
1551 sector_t bb_sector;
1552 u64 *bbp;
1553 int i;
1554 int sectors = le16_to_cpu(sb->bblog_size);
1555 if (sectors > (PAGE_SIZE / 512))
1556 return -EINVAL;
1557 offset = le32_to_cpu(sb->bblog_offset);
1558 if (offset == 0)
1559 return -EINVAL;
1560 bb_sector = (long long)offset;
1561 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1562 rdev->bb_page, REQ_OP_READ, 0, true))
1563 return -EIO;
1564 bbp = (u64 *)page_address(rdev->bb_page);
1565 rdev->badblocks.shift = sb->bblog_shift;
1566 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1567 u64 bb = le64_to_cpu(*bbp);
1568 int count = bb & (0x3ff);
1569 u64 sector = bb >> 10;
1570 sector <<= sb->bblog_shift;
1571 count <<= sb->bblog_shift;
1572 if (bb + 1 == 0)
1573 break;
1574 if (badblocks_set(&rdev->badblocks, sector, count, 1))
1575 return -EINVAL;
1577 } else if (sb->bblog_offset != 0)
1578 rdev->badblocks.shift = 0;
1580 if ((le32_to_cpu(sb->feature_map) &
1581 (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS))) {
1582 rdev->ppl.offset = (__s16)le16_to_cpu(sb->ppl.offset);
1583 rdev->ppl.size = le16_to_cpu(sb->ppl.size);
1584 rdev->ppl.sector = rdev->sb_start + rdev->ppl.offset;
1587 if (!refdev) {
1588 ret = 1;
1589 } else {
1590 __u64 ev1, ev2;
1591 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1593 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1594 sb->level != refsb->level ||
1595 sb->layout != refsb->layout ||
1596 sb->chunksize != refsb->chunksize) {
1597 pr_warn("md: %s has strangely different superblock to %s\n",
1598 bdevname(rdev->bdev,b),
1599 bdevname(refdev->bdev,b2));
1600 return -EINVAL;
1602 ev1 = le64_to_cpu(sb->events);
1603 ev2 = le64_to_cpu(refsb->events);
1605 if (ev1 > ev2)
1606 ret = 1;
1607 else
1608 ret = 0;
1610 if (minor_version) {
1611 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1612 sectors -= rdev->data_offset;
1613 } else
1614 sectors = rdev->sb_start;
1615 if (sectors < le64_to_cpu(sb->data_size))
1616 return -EINVAL;
1617 rdev->sectors = le64_to_cpu(sb->data_size);
1618 return ret;
1621 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1623 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1624 __u64 ev1 = le64_to_cpu(sb->events);
1626 rdev->raid_disk = -1;
1627 clear_bit(Faulty, &rdev->flags);
1628 clear_bit(In_sync, &rdev->flags);
1629 clear_bit(Bitmap_sync, &rdev->flags);
1630 clear_bit(WriteMostly, &rdev->flags);
1632 if (mddev->raid_disks == 0) {
1633 mddev->major_version = 1;
1634 mddev->patch_version = 0;
1635 mddev->external = 0;
1636 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1637 mddev->ctime = le64_to_cpu(sb->ctime);
1638 mddev->utime = le64_to_cpu(sb->utime);
1639 mddev->level = le32_to_cpu(sb->level);
1640 mddev->clevel[0] = 0;
1641 mddev->layout = le32_to_cpu(sb->layout);
1642 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1643 mddev->dev_sectors = le64_to_cpu(sb->size);
1644 mddev->events = ev1;
1645 mddev->bitmap_info.offset = 0;
1646 mddev->bitmap_info.space = 0;
1647 /* Default location for bitmap is 1K after superblock
1648 * using 3K - total of 4K
1650 mddev->bitmap_info.default_offset = 1024 >> 9;
1651 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1652 mddev->reshape_backwards = 0;
1654 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1655 memcpy(mddev->uuid, sb->set_uuid, 16);
1657 mddev->max_disks = (4096-256)/2;
1659 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1660 mddev->bitmap_info.file == NULL) {
1661 mddev->bitmap_info.offset =
1662 (__s32)le32_to_cpu(sb->bitmap_offset);
1663 /* Metadata doesn't record how much space is available.
1664 * For 1.0, we assume we can use up to the superblock
1665 * if before, else to 4K beyond superblock.
1666 * For others, assume no change is possible.
1668 if (mddev->minor_version > 0)
1669 mddev->bitmap_info.space = 0;
1670 else if (mddev->bitmap_info.offset > 0)
1671 mddev->bitmap_info.space =
1672 8 - mddev->bitmap_info.offset;
1673 else
1674 mddev->bitmap_info.space =
1675 -mddev->bitmap_info.offset;
1678 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1679 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1680 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1681 mddev->new_level = le32_to_cpu(sb->new_level);
1682 mddev->new_layout = le32_to_cpu(sb->new_layout);
1683 mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1684 if (mddev->delta_disks < 0 ||
1685 (mddev->delta_disks == 0 &&
1686 (le32_to_cpu(sb->feature_map)
1687 & MD_FEATURE_RESHAPE_BACKWARDS)))
1688 mddev->reshape_backwards = 1;
1689 } else {
1690 mddev->reshape_position = MaxSector;
1691 mddev->delta_disks = 0;
1692 mddev->new_level = mddev->level;
1693 mddev->new_layout = mddev->layout;
1694 mddev->new_chunk_sectors = mddev->chunk_sectors;
1697 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)
1698 set_bit(MD_HAS_JOURNAL, &mddev->flags);
1700 if (le32_to_cpu(sb->feature_map) &
1701 (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS)) {
1702 if (le32_to_cpu(sb->feature_map) &
1703 (MD_FEATURE_BITMAP_OFFSET | MD_FEATURE_JOURNAL))
1704 return -EINVAL;
1705 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_PPL) &&
1706 (le32_to_cpu(sb->feature_map) &
1707 MD_FEATURE_MULTIPLE_PPLS))
1708 return -EINVAL;
1709 set_bit(MD_HAS_PPL, &mddev->flags);
1711 } else if (mddev->pers == NULL) {
1712 /* Insist of good event counter while assembling, except for
1713 * spares (which don't need an event count) */
1714 ++ev1;
1715 if (rdev->desc_nr >= 0 &&
1716 rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1717 (le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < MD_DISK_ROLE_MAX ||
1718 le16_to_cpu(sb->dev_roles[rdev->desc_nr]) == MD_DISK_ROLE_JOURNAL))
1719 if (ev1 < mddev->events)
1720 return -EINVAL;
1721 } else if (mddev->bitmap) {
1722 /* If adding to array with a bitmap, then we can accept an
1723 * older device, but not too old.
1725 if (ev1 < mddev->bitmap->events_cleared)
1726 return 0;
1727 if (ev1 < mddev->events)
1728 set_bit(Bitmap_sync, &rdev->flags);
1729 } else {
1730 if (ev1 < mddev->events)
1731 /* just a hot-add of a new device, leave raid_disk at -1 */
1732 return 0;
1734 if (mddev->level != LEVEL_MULTIPATH) {
1735 int role;
1736 if (rdev->desc_nr < 0 ||
1737 rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1738 role = MD_DISK_ROLE_SPARE;
1739 rdev->desc_nr = -1;
1740 } else
1741 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1742 switch(role) {
1743 case MD_DISK_ROLE_SPARE: /* spare */
1744 break;
1745 case MD_DISK_ROLE_FAULTY: /* faulty */
1746 set_bit(Faulty, &rdev->flags);
1747 break;
1748 case MD_DISK_ROLE_JOURNAL: /* journal device */
1749 if (!(le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)) {
1750 /* journal device without journal feature */
1751 pr_warn("md: journal device provided without journal feature, ignoring the device\n");
1752 return -EINVAL;
1754 set_bit(Journal, &rdev->flags);
1755 rdev->journal_tail = le64_to_cpu(sb->journal_tail);
1756 rdev->raid_disk = 0;
1757 break;
1758 default:
1759 rdev->saved_raid_disk = role;
1760 if ((le32_to_cpu(sb->feature_map) &
1761 MD_FEATURE_RECOVERY_OFFSET)) {
1762 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1763 if (!(le32_to_cpu(sb->feature_map) &
1764 MD_FEATURE_RECOVERY_BITMAP))
1765 rdev->saved_raid_disk = -1;
1766 } else
1767 set_bit(In_sync, &rdev->flags);
1768 rdev->raid_disk = role;
1769 break;
1771 if (sb->devflags & WriteMostly1)
1772 set_bit(WriteMostly, &rdev->flags);
1773 if (sb->devflags & FailFast1)
1774 set_bit(FailFast, &rdev->flags);
1775 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1776 set_bit(Replacement, &rdev->flags);
1777 } else /* MULTIPATH are always insync */
1778 set_bit(In_sync, &rdev->flags);
1780 return 0;
1783 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1785 struct mdp_superblock_1 *sb;
1786 struct md_rdev *rdev2;
1787 int max_dev, i;
1788 /* make rdev->sb match mddev and rdev data. */
1790 sb = page_address(rdev->sb_page);
1792 sb->feature_map = 0;
1793 sb->pad0 = 0;
1794 sb->recovery_offset = cpu_to_le64(0);
1795 memset(sb->pad3, 0, sizeof(sb->pad3));
1797 sb->utime = cpu_to_le64((__u64)mddev->utime);
1798 sb->events = cpu_to_le64(mddev->events);
1799 if (mddev->in_sync)
1800 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1801 else if (test_bit(MD_JOURNAL_CLEAN, &mddev->flags))
1802 sb->resync_offset = cpu_to_le64(MaxSector);
1803 else
1804 sb->resync_offset = cpu_to_le64(0);
1806 sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1808 sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1809 sb->size = cpu_to_le64(mddev->dev_sectors);
1810 sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1811 sb->level = cpu_to_le32(mddev->level);
1812 sb->layout = cpu_to_le32(mddev->layout);
1813 if (test_bit(FailFast, &rdev->flags))
1814 sb->devflags |= FailFast1;
1815 else
1816 sb->devflags &= ~FailFast1;
1818 if (test_bit(WriteMostly, &rdev->flags))
1819 sb->devflags |= WriteMostly1;
1820 else
1821 sb->devflags &= ~WriteMostly1;
1822 sb->data_offset = cpu_to_le64(rdev->data_offset);
1823 sb->data_size = cpu_to_le64(rdev->sectors);
1825 if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1826 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1827 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1830 if (rdev->raid_disk >= 0 && !test_bit(Journal, &rdev->flags) &&
1831 !test_bit(In_sync, &rdev->flags)) {
1832 sb->feature_map |=
1833 cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1834 sb->recovery_offset =
1835 cpu_to_le64(rdev->recovery_offset);
1836 if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1837 sb->feature_map |=
1838 cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1840 /* Note: recovery_offset and journal_tail share space */
1841 if (test_bit(Journal, &rdev->flags))
1842 sb->journal_tail = cpu_to_le64(rdev->journal_tail);
1843 if (test_bit(Replacement, &rdev->flags))
1844 sb->feature_map |=
1845 cpu_to_le32(MD_FEATURE_REPLACEMENT);
1847 if (mddev->reshape_position != MaxSector) {
1848 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1849 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1850 sb->new_layout = cpu_to_le32(mddev->new_layout);
1851 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1852 sb->new_level = cpu_to_le32(mddev->new_level);
1853 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1854 if (mddev->delta_disks == 0 &&
1855 mddev->reshape_backwards)
1856 sb->feature_map
1857 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1858 if (rdev->new_data_offset != rdev->data_offset) {
1859 sb->feature_map
1860 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1861 sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1862 - rdev->data_offset));
1866 if (mddev_is_clustered(mddev))
1867 sb->feature_map |= cpu_to_le32(MD_FEATURE_CLUSTERED);
1869 if (rdev->badblocks.count == 0)
1870 /* Nothing to do for bad blocks*/ ;
1871 else if (sb->bblog_offset == 0)
1872 /* Cannot record bad blocks on this device */
1873 md_error(mddev, rdev);
1874 else {
1875 struct badblocks *bb = &rdev->badblocks;
1876 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1877 u64 *p = bb->page;
1878 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1879 if (bb->changed) {
1880 unsigned seq;
1882 retry:
1883 seq = read_seqbegin(&bb->lock);
1885 memset(bbp, 0xff, PAGE_SIZE);
1887 for (i = 0 ; i < bb->count ; i++) {
1888 u64 internal_bb = p[i];
1889 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1890 | BB_LEN(internal_bb));
1891 bbp[i] = cpu_to_le64(store_bb);
1893 bb->changed = 0;
1894 if (read_seqretry(&bb->lock, seq))
1895 goto retry;
1897 bb->sector = (rdev->sb_start +
1898 (int)le32_to_cpu(sb->bblog_offset));
1899 bb->size = le16_to_cpu(sb->bblog_size);
1903 max_dev = 0;
1904 rdev_for_each(rdev2, mddev)
1905 if (rdev2->desc_nr+1 > max_dev)
1906 max_dev = rdev2->desc_nr+1;
1908 if (max_dev > le32_to_cpu(sb->max_dev)) {
1909 int bmask;
1910 sb->max_dev = cpu_to_le32(max_dev);
1911 rdev->sb_size = max_dev * 2 + 256;
1912 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1913 if (rdev->sb_size & bmask)
1914 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1915 } else
1916 max_dev = le32_to_cpu(sb->max_dev);
1918 for (i=0; i<max_dev;i++)
1919 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1921 if (test_bit(MD_HAS_JOURNAL, &mddev->flags))
1922 sb->feature_map |= cpu_to_le32(MD_FEATURE_JOURNAL);
1924 if (test_bit(MD_HAS_PPL, &mddev->flags)) {
1925 if (test_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags))
1926 sb->feature_map |=
1927 cpu_to_le32(MD_FEATURE_MULTIPLE_PPLS);
1928 else
1929 sb->feature_map |= cpu_to_le32(MD_FEATURE_PPL);
1930 sb->ppl.offset = cpu_to_le16(rdev->ppl.offset);
1931 sb->ppl.size = cpu_to_le16(rdev->ppl.size);
1934 rdev_for_each(rdev2, mddev) {
1935 i = rdev2->desc_nr;
1936 if (test_bit(Faulty, &rdev2->flags))
1937 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_FAULTY);
1938 else if (test_bit(In_sync, &rdev2->flags))
1939 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1940 else if (test_bit(Journal, &rdev2->flags))
1941 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_JOURNAL);
1942 else if (rdev2->raid_disk >= 0)
1943 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1944 else
1945 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1948 sb->sb_csum = calc_sb_1_csum(sb);
1951 static unsigned long long
1952 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1954 struct mdp_superblock_1 *sb;
1955 sector_t max_sectors;
1956 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1957 return 0; /* component must fit device */
1958 if (rdev->data_offset != rdev->new_data_offset)
1959 return 0; /* too confusing */
1960 if (rdev->sb_start < rdev->data_offset) {
1961 /* minor versions 1 and 2; superblock before data */
1962 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1963 max_sectors -= rdev->data_offset;
1964 if (!num_sectors || num_sectors > max_sectors)
1965 num_sectors = max_sectors;
1966 } else if (rdev->mddev->bitmap_info.offset) {
1967 /* minor version 0 with bitmap we can't move */
1968 return 0;
1969 } else {
1970 /* minor version 0; superblock after data */
1971 sector_t sb_start;
1972 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1973 sb_start &= ~(sector_t)(4*2 - 1);
1974 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1975 if (!num_sectors || num_sectors > max_sectors)
1976 num_sectors = max_sectors;
1977 rdev->sb_start = sb_start;
1979 sb = page_address(rdev->sb_page);
1980 sb->data_size = cpu_to_le64(num_sectors);
1981 sb->super_offset = cpu_to_le64(rdev->sb_start);
1982 sb->sb_csum = calc_sb_1_csum(sb);
1983 do {
1984 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1985 rdev->sb_page);
1986 } while (md_super_wait(rdev->mddev) < 0);
1987 return num_sectors;
1991 static int
1992 super_1_allow_new_offset(struct md_rdev *rdev,
1993 unsigned long long new_offset)
1995 /* All necessary checks on new >= old have been done */
1996 struct bitmap *bitmap;
1997 if (new_offset >= rdev->data_offset)
1998 return 1;
2000 /* with 1.0 metadata, there is no metadata to tread on
2001 * so we can always move back */
2002 if (rdev->mddev->minor_version == 0)
2003 return 1;
2005 /* otherwise we must be sure not to step on
2006 * any metadata, so stay:
2007 * 36K beyond start of superblock
2008 * beyond end of badblocks
2009 * beyond write-intent bitmap
2011 if (rdev->sb_start + (32+4)*2 > new_offset)
2012 return 0;
2013 bitmap = rdev->mddev->bitmap;
2014 if (bitmap && !rdev->mddev->bitmap_info.file &&
2015 rdev->sb_start + rdev->mddev->bitmap_info.offset +
2016 bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
2017 return 0;
2018 if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
2019 return 0;
2021 return 1;
2024 static struct super_type super_types[] = {
2025 [0] = {
2026 .name = "0.90.0",
2027 .owner = THIS_MODULE,
2028 .load_super = super_90_load,
2029 .validate_super = super_90_validate,
2030 .sync_super = super_90_sync,
2031 .rdev_size_change = super_90_rdev_size_change,
2032 .allow_new_offset = super_90_allow_new_offset,
2034 [1] = {
2035 .name = "md-1",
2036 .owner = THIS_MODULE,
2037 .load_super = super_1_load,
2038 .validate_super = super_1_validate,
2039 .sync_super = super_1_sync,
2040 .rdev_size_change = super_1_rdev_size_change,
2041 .allow_new_offset = super_1_allow_new_offset,
2045 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
2047 if (mddev->sync_super) {
2048 mddev->sync_super(mddev, rdev);
2049 return;
2052 BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
2054 super_types[mddev->major_version].sync_super(mddev, rdev);
2057 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
2059 struct md_rdev *rdev, *rdev2;
2061 rcu_read_lock();
2062 rdev_for_each_rcu(rdev, mddev1) {
2063 if (test_bit(Faulty, &rdev->flags) ||
2064 test_bit(Journal, &rdev->flags) ||
2065 rdev->raid_disk == -1)
2066 continue;
2067 rdev_for_each_rcu(rdev2, mddev2) {
2068 if (test_bit(Faulty, &rdev2->flags) ||
2069 test_bit(Journal, &rdev2->flags) ||
2070 rdev2->raid_disk == -1)
2071 continue;
2072 if (rdev->bdev->bd_contains ==
2073 rdev2->bdev->bd_contains) {
2074 rcu_read_unlock();
2075 return 1;
2079 rcu_read_unlock();
2080 return 0;
2083 static LIST_HEAD(pending_raid_disks);
2086 * Try to register data integrity profile for an mddev
2088 * This is called when an array is started and after a disk has been kicked
2089 * from the array. It only succeeds if all working and active component devices
2090 * are integrity capable with matching profiles.
2092 int md_integrity_register(struct mddev *mddev)
2094 struct md_rdev *rdev, *reference = NULL;
2096 if (list_empty(&mddev->disks))
2097 return 0; /* nothing to do */
2098 if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
2099 return 0; /* shouldn't register, or already is */
2100 rdev_for_each(rdev, mddev) {
2101 /* skip spares and non-functional disks */
2102 if (test_bit(Faulty, &rdev->flags))
2103 continue;
2104 if (rdev->raid_disk < 0)
2105 continue;
2106 if (!reference) {
2107 /* Use the first rdev as the reference */
2108 reference = rdev;
2109 continue;
2111 /* does this rdev's profile match the reference profile? */
2112 if (blk_integrity_compare(reference->bdev->bd_disk,
2113 rdev->bdev->bd_disk) < 0)
2114 return -EINVAL;
2116 if (!reference || !bdev_get_integrity(reference->bdev))
2117 return 0;
2119 * All component devices are integrity capable and have matching
2120 * profiles, register the common profile for the md device.
2122 blk_integrity_register(mddev->gendisk,
2123 bdev_get_integrity(reference->bdev));
2125 pr_debug("md: data integrity enabled on %s\n", mdname(mddev));
2126 if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
2127 pr_err("md: failed to create integrity pool for %s\n",
2128 mdname(mddev));
2129 return -EINVAL;
2131 return 0;
2133 EXPORT_SYMBOL(md_integrity_register);
2136 * Attempt to add an rdev, but only if it is consistent with the current
2137 * integrity profile
2139 int md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2141 struct blk_integrity *bi_rdev;
2142 struct blk_integrity *bi_mddev;
2143 char name[BDEVNAME_SIZE];
2145 if (!mddev->gendisk)
2146 return 0;
2148 bi_rdev = bdev_get_integrity(rdev->bdev);
2149 bi_mddev = blk_get_integrity(mddev->gendisk);
2151 if (!bi_mddev) /* nothing to do */
2152 return 0;
2154 if (blk_integrity_compare(mddev->gendisk, rdev->bdev->bd_disk) != 0) {
2155 pr_err("%s: incompatible integrity profile for %s\n",
2156 mdname(mddev), bdevname(rdev->bdev, name));
2157 return -ENXIO;
2160 return 0;
2162 EXPORT_SYMBOL(md_integrity_add_rdev);
2164 static int bind_rdev_to_array(struct md_rdev *rdev, struct mddev *mddev)
2166 char b[BDEVNAME_SIZE];
2167 struct kobject *ko;
2168 int err;
2170 /* prevent duplicates */
2171 if (find_rdev(mddev, rdev->bdev->bd_dev))
2172 return -EEXIST;
2174 if ((bdev_read_only(rdev->bdev) || bdev_read_only(rdev->meta_bdev)) &&
2175 mddev->pers)
2176 return -EROFS;
2178 /* make sure rdev->sectors exceeds mddev->dev_sectors */
2179 if (!test_bit(Journal, &rdev->flags) &&
2180 rdev->sectors &&
2181 (mddev->dev_sectors == 0 || rdev->sectors < mddev->dev_sectors)) {
2182 if (mddev->pers) {
2183 /* Cannot change size, so fail
2184 * If mddev->level <= 0, then we don't care
2185 * about aligning sizes (e.g. linear)
2187 if (mddev->level > 0)
2188 return -ENOSPC;
2189 } else
2190 mddev->dev_sectors = rdev->sectors;
2193 /* Verify rdev->desc_nr is unique.
2194 * If it is -1, assign a free number, else
2195 * check number is not in use
2197 rcu_read_lock();
2198 if (rdev->desc_nr < 0) {
2199 int choice = 0;
2200 if (mddev->pers)
2201 choice = mddev->raid_disks;
2202 while (md_find_rdev_nr_rcu(mddev, choice))
2203 choice++;
2204 rdev->desc_nr = choice;
2205 } else {
2206 if (md_find_rdev_nr_rcu(mddev, rdev->desc_nr)) {
2207 rcu_read_unlock();
2208 return -EBUSY;
2211 rcu_read_unlock();
2212 if (!test_bit(Journal, &rdev->flags) &&
2213 mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2214 pr_warn("md: %s: array is limited to %d devices\n",
2215 mdname(mddev), mddev->max_disks);
2216 return -EBUSY;
2218 bdevname(rdev->bdev,b);
2219 strreplace(b, '/', '!');
2221 rdev->mddev = mddev;
2222 pr_debug("md: bind<%s>\n", b);
2224 if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2225 goto fail;
2227 ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2228 if (sysfs_create_link(&rdev->kobj, ko, "block"))
2229 /* failure here is OK */;
2230 rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2232 list_add_rcu(&rdev->same_set, &mddev->disks);
2233 bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2235 /* May as well allow recovery to be retried once */
2236 mddev->recovery_disabled++;
2238 return 0;
2240 fail:
2241 pr_warn("md: failed to register dev-%s for %s\n",
2242 b, mdname(mddev));
2243 return err;
2246 static void md_delayed_delete(struct work_struct *ws)
2248 struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2249 kobject_del(&rdev->kobj);
2250 kobject_put(&rdev->kobj);
2253 static void unbind_rdev_from_array(struct md_rdev *rdev)
2255 char b[BDEVNAME_SIZE];
2257 bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2258 list_del_rcu(&rdev->same_set);
2259 pr_debug("md: unbind<%s>\n", bdevname(rdev->bdev,b));
2260 rdev->mddev = NULL;
2261 sysfs_remove_link(&rdev->kobj, "block");
2262 sysfs_put(rdev->sysfs_state);
2263 rdev->sysfs_state = NULL;
2264 rdev->badblocks.count = 0;
2265 /* We need to delay this, otherwise we can deadlock when
2266 * writing to 'remove' to "dev/state". We also need
2267 * to delay it due to rcu usage.
2269 synchronize_rcu();
2270 INIT_WORK(&rdev->del_work, md_delayed_delete);
2271 kobject_get(&rdev->kobj);
2272 queue_work(md_misc_wq, &rdev->del_work);
2276 * prevent the device from being mounted, repartitioned or
2277 * otherwise reused by a RAID array (or any other kernel
2278 * subsystem), by bd_claiming the device.
2280 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2282 int err = 0;
2283 struct block_device *bdev;
2284 char b[BDEVNAME_SIZE];
2286 bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2287 shared ? (struct md_rdev *)lock_rdev : rdev);
2288 if (IS_ERR(bdev)) {
2289 pr_warn("md: could not open %s.\n", __bdevname(dev, b));
2290 return PTR_ERR(bdev);
2292 rdev->bdev = bdev;
2293 return err;
2296 static void unlock_rdev(struct md_rdev *rdev)
2298 struct block_device *bdev = rdev->bdev;
2299 rdev->bdev = NULL;
2300 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2303 void md_autodetect_dev(dev_t dev);
2305 static void export_rdev(struct md_rdev *rdev)
2307 char b[BDEVNAME_SIZE];
2309 pr_debug("md: export_rdev(%s)\n", bdevname(rdev->bdev,b));
2310 md_rdev_clear(rdev);
2311 #ifndef MODULE
2312 if (test_bit(AutoDetected, &rdev->flags))
2313 md_autodetect_dev(rdev->bdev->bd_dev);
2314 #endif
2315 unlock_rdev(rdev);
2316 kobject_put(&rdev->kobj);
2319 void md_kick_rdev_from_array(struct md_rdev *rdev)
2321 unbind_rdev_from_array(rdev);
2322 export_rdev(rdev);
2324 EXPORT_SYMBOL_GPL(md_kick_rdev_from_array);
2326 static void export_array(struct mddev *mddev)
2328 struct md_rdev *rdev;
2330 while (!list_empty(&mddev->disks)) {
2331 rdev = list_first_entry(&mddev->disks, struct md_rdev,
2332 same_set);
2333 md_kick_rdev_from_array(rdev);
2335 mddev->raid_disks = 0;
2336 mddev->major_version = 0;
2339 static bool set_in_sync(struct mddev *mddev)
2341 WARN_ON_ONCE(NR_CPUS != 1 && !spin_is_locked(&mddev->lock));
2342 if (!mddev->in_sync) {
2343 mddev->sync_checkers++;
2344 spin_unlock(&mddev->lock);
2345 percpu_ref_switch_to_atomic_sync(&mddev->writes_pending);
2346 spin_lock(&mddev->lock);
2347 if (!mddev->in_sync &&
2348 percpu_ref_is_zero(&mddev->writes_pending)) {
2349 mddev->in_sync = 1;
2351 * Ensure ->in_sync is visible before we clear
2352 * ->sync_checkers.
2354 smp_mb();
2355 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2356 sysfs_notify_dirent_safe(mddev->sysfs_state);
2358 if (--mddev->sync_checkers == 0)
2359 percpu_ref_switch_to_percpu(&mddev->writes_pending);
2361 if (mddev->safemode == 1)
2362 mddev->safemode = 0;
2363 return mddev->in_sync;
2366 static void sync_sbs(struct mddev *mddev, int nospares)
2368 /* Update each superblock (in-memory image), but
2369 * if we are allowed to, skip spares which already
2370 * have the right event counter, or have one earlier
2371 * (which would mean they aren't being marked as dirty
2372 * with the rest of the array)
2374 struct md_rdev *rdev;
2375 rdev_for_each(rdev, mddev) {
2376 if (rdev->sb_events == mddev->events ||
2377 (nospares &&
2378 rdev->raid_disk < 0 &&
2379 rdev->sb_events+1 == mddev->events)) {
2380 /* Don't update this superblock */
2381 rdev->sb_loaded = 2;
2382 } else {
2383 sync_super(mddev, rdev);
2384 rdev->sb_loaded = 1;
2389 static bool does_sb_need_changing(struct mddev *mddev)
2391 struct md_rdev *rdev;
2392 struct mdp_superblock_1 *sb;
2393 int role;
2395 /* Find a good rdev */
2396 rdev_for_each(rdev, mddev)
2397 if ((rdev->raid_disk >= 0) && !test_bit(Faulty, &rdev->flags))
2398 break;
2400 /* No good device found. */
2401 if (!rdev)
2402 return false;
2404 sb = page_address(rdev->sb_page);
2405 /* Check if a device has become faulty or a spare become active */
2406 rdev_for_each(rdev, mddev) {
2407 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
2408 /* Device activated? */
2409 if (role == 0xffff && rdev->raid_disk >=0 &&
2410 !test_bit(Faulty, &rdev->flags))
2411 return true;
2412 /* Device turned faulty? */
2413 if (test_bit(Faulty, &rdev->flags) && (role < 0xfffd))
2414 return true;
2417 /* Check if any mddev parameters have changed */
2418 if ((mddev->dev_sectors != le64_to_cpu(sb->size)) ||
2419 (mddev->reshape_position != le64_to_cpu(sb->reshape_position)) ||
2420 (mddev->layout != le32_to_cpu(sb->layout)) ||
2421 (mddev->raid_disks != le32_to_cpu(sb->raid_disks)) ||
2422 (mddev->chunk_sectors != le32_to_cpu(sb->chunksize)))
2423 return true;
2425 return false;
2428 void md_update_sb(struct mddev *mddev, int force_change)
2430 struct md_rdev *rdev;
2431 int sync_req;
2432 int nospares = 0;
2433 int any_badblocks_changed = 0;
2434 int ret = -1;
2436 if (mddev->ro) {
2437 if (force_change)
2438 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2439 return;
2442 repeat:
2443 if (mddev_is_clustered(mddev)) {
2444 if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2445 force_change = 1;
2446 if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2447 nospares = 1;
2448 ret = md_cluster_ops->metadata_update_start(mddev);
2449 /* Has someone else has updated the sb */
2450 if (!does_sb_need_changing(mddev)) {
2451 if (ret == 0)
2452 md_cluster_ops->metadata_update_cancel(mddev);
2453 bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2454 BIT(MD_SB_CHANGE_DEVS) |
2455 BIT(MD_SB_CHANGE_CLEAN));
2456 return;
2460 /* First make sure individual recovery_offsets are correct */
2461 rdev_for_each(rdev, mddev) {
2462 if (rdev->raid_disk >= 0 &&
2463 mddev->delta_disks >= 0 &&
2464 !test_bit(Journal, &rdev->flags) &&
2465 !test_bit(In_sync, &rdev->flags) &&
2466 mddev->curr_resync_completed > rdev->recovery_offset)
2467 rdev->recovery_offset = mddev->curr_resync_completed;
2470 if (!mddev->persistent) {
2471 clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2472 clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2473 if (!mddev->external) {
2474 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
2475 rdev_for_each(rdev, mddev) {
2476 if (rdev->badblocks.changed) {
2477 rdev->badblocks.changed = 0;
2478 ack_all_badblocks(&rdev->badblocks);
2479 md_error(mddev, rdev);
2481 clear_bit(Blocked, &rdev->flags);
2482 clear_bit(BlockedBadBlocks, &rdev->flags);
2483 wake_up(&rdev->blocked_wait);
2486 wake_up(&mddev->sb_wait);
2487 return;
2490 spin_lock(&mddev->lock);
2492 mddev->utime = ktime_get_real_seconds();
2494 if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2495 force_change = 1;
2496 if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2497 /* just a clean<-> dirty transition, possibly leave spares alone,
2498 * though if events isn't the right even/odd, we will have to do
2499 * spares after all
2501 nospares = 1;
2502 if (force_change)
2503 nospares = 0;
2504 if (mddev->degraded)
2505 /* If the array is degraded, then skipping spares is both
2506 * dangerous and fairly pointless.
2507 * Dangerous because a device that was removed from the array
2508 * might have a event_count that still looks up-to-date,
2509 * so it can be re-added without a resync.
2510 * Pointless because if there are any spares to skip,
2511 * then a recovery will happen and soon that array won't
2512 * be degraded any more and the spare can go back to sleep then.
2514 nospares = 0;
2516 sync_req = mddev->in_sync;
2518 /* If this is just a dirty<->clean transition, and the array is clean
2519 * and 'events' is odd, we can roll back to the previous clean state */
2520 if (nospares
2521 && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2522 && mddev->can_decrease_events
2523 && mddev->events != 1) {
2524 mddev->events--;
2525 mddev->can_decrease_events = 0;
2526 } else {
2527 /* otherwise we have to go forward and ... */
2528 mddev->events ++;
2529 mddev->can_decrease_events = nospares;
2533 * This 64-bit counter should never wrap.
2534 * Either we are in around ~1 trillion A.C., assuming
2535 * 1 reboot per second, or we have a bug...
2537 WARN_ON(mddev->events == 0);
2539 rdev_for_each(rdev, mddev) {
2540 if (rdev->badblocks.changed)
2541 any_badblocks_changed++;
2542 if (test_bit(Faulty, &rdev->flags))
2543 set_bit(FaultRecorded, &rdev->flags);
2546 sync_sbs(mddev, nospares);
2547 spin_unlock(&mddev->lock);
2549 pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2550 mdname(mddev), mddev->in_sync);
2552 if (mddev->queue)
2553 blk_add_trace_msg(mddev->queue, "md md_update_sb");
2554 rewrite:
2555 bitmap_update_sb(mddev->bitmap);
2556 rdev_for_each(rdev, mddev) {
2557 char b[BDEVNAME_SIZE];
2559 if (rdev->sb_loaded != 1)
2560 continue; /* no noise on spare devices */
2562 if (!test_bit(Faulty, &rdev->flags)) {
2563 md_super_write(mddev,rdev,
2564 rdev->sb_start, rdev->sb_size,
2565 rdev->sb_page);
2566 pr_debug("md: (write) %s's sb offset: %llu\n",
2567 bdevname(rdev->bdev, b),
2568 (unsigned long long)rdev->sb_start);
2569 rdev->sb_events = mddev->events;
2570 if (rdev->badblocks.size) {
2571 md_super_write(mddev, rdev,
2572 rdev->badblocks.sector,
2573 rdev->badblocks.size << 9,
2574 rdev->bb_page);
2575 rdev->badblocks.size = 0;
2578 } else
2579 pr_debug("md: %s (skipping faulty)\n",
2580 bdevname(rdev->bdev, b));
2582 if (mddev->level == LEVEL_MULTIPATH)
2583 /* only need to write one superblock... */
2584 break;
2586 if (md_super_wait(mddev) < 0)
2587 goto rewrite;
2588 /* if there was a failure, MD_SB_CHANGE_DEVS was set, and we re-write super */
2590 if (mddev_is_clustered(mddev) && ret == 0)
2591 md_cluster_ops->metadata_update_finish(mddev);
2593 if (mddev->in_sync != sync_req ||
2594 !bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2595 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_CLEAN)))
2596 /* have to write it out again */
2597 goto repeat;
2598 wake_up(&mddev->sb_wait);
2599 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2600 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2602 rdev_for_each(rdev, mddev) {
2603 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2604 clear_bit(Blocked, &rdev->flags);
2606 if (any_badblocks_changed)
2607 ack_all_badblocks(&rdev->badblocks);
2608 clear_bit(BlockedBadBlocks, &rdev->flags);
2609 wake_up(&rdev->blocked_wait);
2612 EXPORT_SYMBOL(md_update_sb);
2614 static int add_bound_rdev(struct md_rdev *rdev)
2616 struct mddev *mddev = rdev->mddev;
2617 int err = 0;
2618 bool add_journal = test_bit(Journal, &rdev->flags);
2620 if (!mddev->pers->hot_remove_disk || add_journal) {
2621 /* If there is hot_add_disk but no hot_remove_disk
2622 * then added disks for geometry changes,
2623 * and should be added immediately.
2625 super_types[mddev->major_version].
2626 validate_super(mddev, rdev);
2627 if (add_journal)
2628 mddev_suspend(mddev);
2629 err = mddev->pers->hot_add_disk(mddev, rdev);
2630 if (add_journal)
2631 mddev_resume(mddev);
2632 if (err) {
2633 md_kick_rdev_from_array(rdev);
2634 return err;
2637 sysfs_notify_dirent_safe(rdev->sysfs_state);
2639 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2640 if (mddev->degraded)
2641 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2642 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2643 md_new_event(mddev);
2644 md_wakeup_thread(mddev->thread);
2645 return 0;
2648 /* words written to sysfs files may, or may not, be \n terminated.
2649 * We want to accept with case. For this we use cmd_match.
2651 static int cmd_match(const char *cmd, const char *str)
2653 /* See if cmd, written into a sysfs file, matches
2654 * str. They must either be the same, or cmd can
2655 * have a trailing newline
2657 while (*cmd && *str && *cmd == *str) {
2658 cmd++;
2659 str++;
2661 if (*cmd == '\n')
2662 cmd++;
2663 if (*str || *cmd)
2664 return 0;
2665 return 1;
2668 struct rdev_sysfs_entry {
2669 struct attribute attr;
2670 ssize_t (*show)(struct md_rdev *, char *);
2671 ssize_t (*store)(struct md_rdev *, const char *, size_t);
2674 static ssize_t
2675 state_show(struct md_rdev *rdev, char *page)
2677 char *sep = ",";
2678 size_t len = 0;
2679 unsigned long flags = ACCESS_ONCE(rdev->flags);
2681 if (test_bit(Faulty, &flags) ||
2682 (!test_bit(ExternalBbl, &flags) &&
2683 rdev->badblocks.unacked_exist))
2684 len += sprintf(page+len, "faulty%s", sep);
2685 if (test_bit(In_sync, &flags))
2686 len += sprintf(page+len, "in_sync%s", sep);
2687 if (test_bit(Journal, &flags))
2688 len += sprintf(page+len, "journal%s", sep);
2689 if (test_bit(WriteMostly, &flags))
2690 len += sprintf(page+len, "write_mostly%s", sep);
2691 if (test_bit(Blocked, &flags) ||
2692 (rdev->badblocks.unacked_exist
2693 && !test_bit(Faulty, &flags)))
2694 len += sprintf(page+len, "blocked%s", sep);
2695 if (!test_bit(Faulty, &flags) &&
2696 !test_bit(Journal, &flags) &&
2697 !test_bit(In_sync, &flags))
2698 len += sprintf(page+len, "spare%s", sep);
2699 if (test_bit(WriteErrorSeen, &flags))
2700 len += sprintf(page+len, "write_error%s", sep);
2701 if (test_bit(WantReplacement, &flags))
2702 len += sprintf(page+len, "want_replacement%s", sep);
2703 if (test_bit(Replacement, &flags))
2704 len += sprintf(page+len, "replacement%s", sep);
2705 if (test_bit(ExternalBbl, &flags))
2706 len += sprintf(page+len, "external_bbl%s", sep);
2707 if (test_bit(FailFast, &flags))
2708 len += sprintf(page+len, "failfast%s", sep);
2710 if (len)
2711 len -= strlen(sep);
2713 return len+sprintf(page+len, "\n");
2716 static ssize_t
2717 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2719 /* can write
2720 * faulty - simulates an error
2721 * remove - disconnects the device
2722 * writemostly - sets write_mostly
2723 * -writemostly - clears write_mostly
2724 * blocked - sets the Blocked flags
2725 * -blocked - clears the Blocked and possibly simulates an error
2726 * insync - sets Insync providing device isn't active
2727 * -insync - clear Insync for a device with a slot assigned,
2728 * so that it gets rebuilt based on bitmap
2729 * write_error - sets WriteErrorSeen
2730 * -write_error - clears WriteErrorSeen
2731 * {,-}failfast - set/clear FailFast
2733 int err = -EINVAL;
2734 if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2735 md_error(rdev->mddev, rdev);
2736 if (test_bit(Faulty, &rdev->flags))
2737 err = 0;
2738 else
2739 err = -EBUSY;
2740 } else if (cmd_match(buf, "remove")) {
2741 if (rdev->mddev->pers) {
2742 clear_bit(Blocked, &rdev->flags);
2743 remove_and_add_spares(rdev->mddev, rdev);
2745 if (rdev->raid_disk >= 0)
2746 err = -EBUSY;
2747 else {
2748 struct mddev *mddev = rdev->mddev;
2749 err = 0;
2750 if (mddev_is_clustered(mddev))
2751 err = md_cluster_ops->remove_disk(mddev, rdev);
2753 if (err == 0) {
2754 md_kick_rdev_from_array(rdev);
2755 if (mddev->pers) {
2756 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2757 md_wakeup_thread(mddev->thread);
2759 md_new_event(mddev);
2762 } else if (cmd_match(buf, "writemostly")) {
2763 set_bit(WriteMostly, &rdev->flags);
2764 err = 0;
2765 } else if (cmd_match(buf, "-writemostly")) {
2766 clear_bit(WriteMostly, &rdev->flags);
2767 err = 0;
2768 } else if (cmd_match(buf, "blocked")) {
2769 set_bit(Blocked, &rdev->flags);
2770 err = 0;
2771 } else if (cmd_match(buf, "-blocked")) {
2772 if (!test_bit(Faulty, &rdev->flags) &&
2773 !test_bit(ExternalBbl, &rdev->flags) &&
2774 rdev->badblocks.unacked_exist) {
2775 /* metadata handler doesn't understand badblocks,
2776 * so we need to fail the device
2778 md_error(rdev->mddev, rdev);
2780 clear_bit(Blocked, &rdev->flags);
2781 clear_bit(BlockedBadBlocks, &rdev->flags);
2782 wake_up(&rdev->blocked_wait);
2783 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2784 md_wakeup_thread(rdev->mddev->thread);
2786 err = 0;
2787 } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2788 set_bit(In_sync, &rdev->flags);
2789 err = 0;
2790 } else if (cmd_match(buf, "failfast")) {
2791 set_bit(FailFast, &rdev->flags);
2792 err = 0;
2793 } else if (cmd_match(buf, "-failfast")) {
2794 clear_bit(FailFast, &rdev->flags);
2795 err = 0;
2796 } else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0 &&
2797 !test_bit(Journal, &rdev->flags)) {
2798 if (rdev->mddev->pers == NULL) {
2799 clear_bit(In_sync, &rdev->flags);
2800 rdev->saved_raid_disk = rdev->raid_disk;
2801 rdev->raid_disk = -1;
2802 err = 0;
2804 } else if (cmd_match(buf, "write_error")) {
2805 set_bit(WriteErrorSeen, &rdev->flags);
2806 err = 0;
2807 } else if (cmd_match(buf, "-write_error")) {
2808 clear_bit(WriteErrorSeen, &rdev->flags);
2809 err = 0;
2810 } else if (cmd_match(buf, "want_replacement")) {
2811 /* Any non-spare device that is not a replacement can
2812 * become want_replacement at any time, but we then need to
2813 * check if recovery is needed.
2815 if (rdev->raid_disk >= 0 &&
2816 !test_bit(Journal, &rdev->flags) &&
2817 !test_bit(Replacement, &rdev->flags))
2818 set_bit(WantReplacement, &rdev->flags);
2819 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2820 md_wakeup_thread(rdev->mddev->thread);
2821 err = 0;
2822 } else if (cmd_match(buf, "-want_replacement")) {
2823 /* Clearing 'want_replacement' is always allowed.
2824 * Once replacements starts it is too late though.
2826 err = 0;
2827 clear_bit(WantReplacement, &rdev->flags);
2828 } else if (cmd_match(buf, "replacement")) {
2829 /* Can only set a device as a replacement when array has not
2830 * yet been started. Once running, replacement is automatic
2831 * from spares, or by assigning 'slot'.
2833 if (rdev->mddev->pers)
2834 err = -EBUSY;
2835 else {
2836 set_bit(Replacement, &rdev->flags);
2837 err = 0;
2839 } else if (cmd_match(buf, "-replacement")) {
2840 /* Similarly, can only clear Replacement before start */
2841 if (rdev->mddev->pers)
2842 err = -EBUSY;
2843 else {
2844 clear_bit(Replacement, &rdev->flags);
2845 err = 0;
2847 } else if (cmd_match(buf, "re-add")) {
2848 if (test_bit(Faulty, &rdev->flags) && (rdev->raid_disk == -1) &&
2849 rdev->saved_raid_disk >= 0) {
2850 /* clear_bit is performed _after_ all the devices
2851 * have their local Faulty bit cleared. If any writes
2852 * happen in the meantime in the local node, they
2853 * will land in the local bitmap, which will be synced
2854 * by this node eventually
2856 if (!mddev_is_clustered(rdev->mddev) ||
2857 (err = md_cluster_ops->gather_bitmaps(rdev)) == 0) {
2858 clear_bit(Faulty, &rdev->flags);
2859 err = add_bound_rdev(rdev);
2861 } else
2862 err = -EBUSY;
2863 } else if (cmd_match(buf, "external_bbl") && (rdev->mddev->external)) {
2864 set_bit(ExternalBbl, &rdev->flags);
2865 rdev->badblocks.shift = 0;
2866 err = 0;
2867 } else if (cmd_match(buf, "-external_bbl") && (rdev->mddev->external)) {
2868 clear_bit(ExternalBbl, &rdev->flags);
2869 err = 0;
2871 if (!err)
2872 sysfs_notify_dirent_safe(rdev->sysfs_state);
2873 return err ? err : len;
2875 static struct rdev_sysfs_entry rdev_state =
2876 __ATTR_PREALLOC(state, S_IRUGO|S_IWUSR, state_show, state_store);
2878 static ssize_t
2879 errors_show(struct md_rdev *rdev, char *page)
2881 return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2884 static ssize_t
2885 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2887 unsigned int n;
2888 int rv;
2890 rv = kstrtouint(buf, 10, &n);
2891 if (rv < 0)
2892 return rv;
2893 atomic_set(&rdev->corrected_errors, n);
2894 return len;
2896 static struct rdev_sysfs_entry rdev_errors =
2897 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2899 static ssize_t
2900 slot_show(struct md_rdev *rdev, char *page)
2902 if (test_bit(Journal, &rdev->flags))
2903 return sprintf(page, "journal\n");
2904 else if (rdev->raid_disk < 0)
2905 return sprintf(page, "none\n");
2906 else
2907 return sprintf(page, "%d\n", rdev->raid_disk);
2910 static ssize_t
2911 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2913 int slot;
2914 int err;
2916 if (test_bit(Journal, &rdev->flags))
2917 return -EBUSY;
2918 if (strncmp(buf, "none", 4)==0)
2919 slot = -1;
2920 else {
2921 err = kstrtouint(buf, 10, (unsigned int *)&slot);
2922 if (err < 0)
2923 return err;
2925 if (rdev->mddev->pers && slot == -1) {
2926 /* Setting 'slot' on an active array requires also
2927 * updating the 'rd%d' link, and communicating
2928 * with the personality with ->hot_*_disk.
2929 * For now we only support removing
2930 * failed/spare devices. This normally happens automatically,
2931 * but not when the metadata is externally managed.
2933 if (rdev->raid_disk == -1)
2934 return -EEXIST;
2935 /* personality does all needed checks */
2936 if (rdev->mddev->pers->hot_remove_disk == NULL)
2937 return -EINVAL;
2938 clear_bit(Blocked, &rdev->flags);
2939 remove_and_add_spares(rdev->mddev, rdev);
2940 if (rdev->raid_disk >= 0)
2941 return -EBUSY;
2942 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2943 md_wakeup_thread(rdev->mddev->thread);
2944 } else if (rdev->mddev->pers) {
2945 /* Activating a spare .. or possibly reactivating
2946 * if we ever get bitmaps working here.
2948 int err;
2950 if (rdev->raid_disk != -1)
2951 return -EBUSY;
2953 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2954 return -EBUSY;
2956 if (rdev->mddev->pers->hot_add_disk == NULL)
2957 return -EINVAL;
2959 if (slot >= rdev->mddev->raid_disks &&
2960 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2961 return -ENOSPC;
2963 rdev->raid_disk = slot;
2964 if (test_bit(In_sync, &rdev->flags))
2965 rdev->saved_raid_disk = slot;
2966 else
2967 rdev->saved_raid_disk = -1;
2968 clear_bit(In_sync, &rdev->flags);
2969 clear_bit(Bitmap_sync, &rdev->flags);
2970 err = rdev->mddev->pers->
2971 hot_add_disk(rdev->mddev, rdev);
2972 if (err) {
2973 rdev->raid_disk = -1;
2974 return err;
2975 } else
2976 sysfs_notify_dirent_safe(rdev->sysfs_state);
2977 if (sysfs_link_rdev(rdev->mddev, rdev))
2978 /* failure here is OK */;
2979 /* don't wakeup anyone, leave that to userspace. */
2980 } else {
2981 if (slot >= rdev->mddev->raid_disks &&
2982 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2983 return -ENOSPC;
2984 rdev->raid_disk = slot;
2985 /* assume it is working */
2986 clear_bit(Faulty, &rdev->flags);
2987 clear_bit(WriteMostly, &rdev->flags);
2988 set_bit(In_sync, &rdev->flags);
2989 sysfs_notify_dirent_safe(rdev->sysfs_state);
2991 return len;
2994 static struct rdev_sysfs_entry rdev_slot =
2995 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2997 static ssize_t
2998 offset_show(struct md_rdev *rdev, char *page)
3000 return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
3003 static ssize_t
3004 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
3006 unsigned long long offset;
3007 if (kstrtoull(buf, 10, &offset) < 0)
3008 return -EINVAL;
3009 if (rdev->mddev->pers && rdev->raid_disk >= 0)
3010 return -EBUSY;
3011 if (rdev->sectors && rdev->mddev->external)
3012 /* Must set offset before size, so overlap checks
3013 * can be sane */
3014 return -EBUSY;
3015 rdev->data_offset = offset;
3016 rdev->new_data_offset = offset;
3017 return len;
3020 static struct rdev_sysfs_entry rdev_offset =
3021 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
3023 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
3025 return sprintf(page, "%llu\n",
3026 (unsigned long long)rdev->new_data_offset);
3029 static ssize_t new_offset_store(struct md_rdev *rdev,
3030 const char *buf, size_t len)
3032 unsigned long long new_offset;
3033 struct mddev *mddev = rdev->mddev;
3035 if (kstrtoull(buf, 10, &new_offset) < 0)
3036 return -EINVAL;
3038 if (mddev->sync_thread ||
3039 test_bit(MD_RECOVERY_RUNNING,&mddev->recovery))
3040 return -EBUSY;
3041 if (new_offset == rdev->data_offset)
3042 /* reset is always permitted */
3044 else if (new_offset > rdev->data_offset) {
3045 /* must not push array size beyond rdev_sectors */
3046 if (new_offset - rdev->data_offset
3047 + mddev->dev_sectors > rdev->sectors)
3048 return -E2BIG;
3050 /* Metadata worries about other space details. */
3052 /* decreasing the offset is inconsistent with a backwards
3053 * reshape.
3055 if (new_offset < rdev->data_offset &&
3056 mddev->reshape_backwards)
3057 return -EINVAL;
3058 /* Increasing offset is inconsistent with forwards
3059 * reshape. reshape_direction should be set to
3060 * 'backwards' first.
3062 if (new_offset > rdev->data_offset &&
3063 !mddev->reshape_backwards)
3064 return -EINVAL;
3066 if (mddev->pers && mddev->persistent &&
3067 !super_types[mddev->major_version]
3068 .allow_new_offset(rdev, new_offset))
3069 return -E2BIG;
3070 rdev->new_data_offset = new_offset;
3071 if (new_offset > rdev->data_offset)
3072 mddev->reshape_backwards = 1;
3073 else if (new_offset < rdev->data_offset)
3074 mddev->reshape_backwards = 0;
3076 return len;
3078 static struct rdev_sysfs_entry rdev_new_offset =
3079 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
3081 static ssize_t
3082 rdev_size_show(struct md_rdev *rdev, char *page)
3084 return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
3087 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
3089 /* check if two start/length pairs overlap */
3090 if (s1+l1 <= s2)
3091 return 0;
3092 if (s2+l2 <= s1)
3093 return 0;
3094 return 1;
3097 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
3099 unsigned long long blocks;
3100 sector_t new;
3102 if (kstrtoull(buf, 10, &blocks) < 0)
3103 return -EINVAL;
3105 if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
3106 return -EINVAL; /* sector conversion overflow */
3108 new = blocks * 2;
3109 if (new != blocks * 2)
3110 return -EINVAL; /* unsigned long long to sector_t overflow */
3112 *sectors = new;
3113 return 0;
3116 static ssize_t
3117 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3119 struct mddev *my_mddev = rdev->mddev;
3120 sector_t oldsectors = rdev->sectors;
3121 sector_t sectors;
3123 if (test_bit(Journal, &rdev->flags))
3124 return -EBUSY;
3125 if (strict_blocks_to_sectors(buf, &sectors) < 0)
3126 return -EINVAL;
3127 if (rdev->data_offset != rdev->new_data_offset)
3128 return -EINVAL; /* too confusing */
3129 if (my_mddev->pers && rdev->raid_disk >= 0) {
3130 if (my_mddev->persistent) {
3131 sectors = super_types[my_mddev->major_version].
3132 rdev_size_change(rdev, sectors);
3133 if (!sectors)
3134 return -EBUSY;
3135 } else if (!sectors)
3136 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
3137 rdev->data_offset;
3138 if (!my_mddev->pers->resize)
3139 /* Cannot change size for RAID0 or Linear etc */
3140 return -EINVAL;
3142 if (sectors < my_mddev->dev_sectors)
3143 return -EINVAL; /* component must fit device */
3145 rdev->sectors = sectors;
3146 if (sectors > oldsectors && my_mddev->external) {
3147 /* Need to check that all other rdevs with the same
3148 * ->bdev do not overlap. 'rcu' is sufficient to walk
3149 * the rdev lists safely.
3150 * This check does not provide a hard guarantee, it
3151 * just helps avoid dangerous mistakes.
3153 struct mddev *mddev;
3154 int overlap = 0;
3155 struct list_head *tmp;
3157 rcu_read_lock();
3158 for_each_mddev(mddev, tmp) {
3159 struct md_rdev *rdev2;
3161 rdev_for_each(rdev2, mddev)
3162 if (rdev->bdev == rdev2->bdev &&
3163 rdev != rdev2 &&
3164 overlaps(rdev->data_offset, rdev->sectors,
3165 rdev2->data_offset,
3166 rdev2->sectors)) {
3167 overlap = 1;
3168 break;
3170 if (overlap) {
3171 mddev_put(mddev);
3172 break;
3175 rcu_read_unlock();
3176 if (overlap) {
3177 /* Someone else could have slipped in a size
3178 * change here, but doing so is just silly.
3179 * We put oldsectors back because we *know* it is
3180 * safe, and trust userspace not to race with
3181 * itself
3183 rdev->sectors = oldsectors;
3184 return -EBUSY;
3187 return len;
3190 static struct rdev_sysfs_entry rdev_size =
3191 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3193 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3195 unsigned long long recovery_start = rdev->recovery_offset;
3197 if (test_bit(In_sync, &rdev->flags) ||
3198 recovery_start == MaxSector)
3199 return sprintf(page, "none\n");
3201 return sprintf(page, "%llu\n", recovery_start);
3204 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3206 unsigned long long recovery_start;
3208 if (cmd_match(buf, "none"))
3209 recovery_start = MaxSector;
3210 else if (kstrtoull(buf, 10, &recovery_start))
3211 return -EINVAL;
3213 if (rdev->mddev->pers &&
3214 rdev->raid_disk >= 0)
3215 return -EBUSY;
3217 rdev->recovery_offset = recovery_start;
3218 if (recovery_start == MaxSector)
3219 set_bit(In_sync, &rdev->flags);
3220 else
3221 clear_bit(In_sync, &rdev->flags);
3222 return len;
3225 static struct rdev_sysfs_entry rdev_recovery_start =
3226 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3228 /* sysfs access to bad-blocks list.
3229 * We present two files.
3230 * 'bad-blocks' lists sector numbers and lengths of ranges that
3231 * are recorded as bad. The list is truncated to fit within
3232 * the one-page limit of sysfs.
3233 * Writing "sector length" to this file adds an acknowledged
3234 * bad block list.
3235 * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
3236 * been acknowledged. Writing to this file adds bad blocks
3237 * without acknowledging them. This is largely for testing.
3239 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3241 return badblocks_show(&rdev->badblocks, page, 0);
3243 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3245 int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3246 /* Maybe that ack was all we needed */
3247 if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3248 wake_up(&rdev->blocked_wait);
3249 return rv;
3251 static struct rdev_sysfs_entry rdev_bad_blocks =
3252 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3254 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3256 return badblocks_show(&rdev->badblocks, page, 1);
3258 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3260 return badblocks_store(&rdev->badblocks, page, len, 1);
3262 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3263 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3265 static ssize_t
3266 ppl_sector_show(struct md_rdev *rdev, char *page)
3268 return sprintf(page, "%llu\n", (unsigned long long)rdev->ppl.sector);
3271 static ssize_t
3272 ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len)
3274 unsigned long long sector;
3276 if (kstrtoull(buf, 10, &sector) < 0)
3277 return -EINVAL;
3278 if (sector != (sector_t)sector)
3279 return -EINVAL;
3281 if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3282 rdev->raid_disk >= 0)
3283 return -EBUSY;
3285 if (rdev->mddev->persistent) {
3286 if (rdev->mddev->major_version == 0)
3287 return -EINVAL;
3288 if ((sector > rdev->sb_start &&
3289 sector - rdev->sb_start > S16_MAX) ||
3290 (sector < rdev->sb_start &&
3291 rdev->sb_start - sector > -S16_MIN))
3292 return -EINVAL;
3293 rdev->ppl.offset = sector - rdev->sb_start;
3294 } else if (!rdev->mddev->external) {
3295 return -EBUSY;
3297 rdev->ppl.sector = sector;
3298 return len;
3301 static struct rdev_sysfs_entry rdev_ppl_sector =
3302 __ATTR(ppl_sector, S_IRUGO|S_IWUSR, ppl_sector_show, ppl_sector_store);
3304 static ssize_t
3305 ppl_size_show(struct md_rdev *rdev, char *page)
3307 return sprintf(page, "%u\n", rdev->ppl.size);
3310 static ssize_t
3311 ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3313 unsigned int size;
3315 if (kstrtouint(buf, 10, &size) < 0)
3316 return -EINVAL;
3318 if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3319 rdev->raid_disk >= 0)
3320 return -EBUSY;
3322 if (rdev->mddev->persistent) {
3323 if (rdev->mddev->major_version == 0)
3324 return -EINVAL;
3325 if (size > U16_MAX)
3326 return -EINVAL;
3327 } else if (!rdev->mddev->external) {
3328 return -EBUSY;
3330 rdev->ppl.size = size;
3331 return len;
3334 static struct rdev_sysfs_entry rdev_ppl_size =
3335 __ATTR(ppl_size, S_IRUGO|S_IWUSR, ppl_size_show, ppl_size_store);
3337 static struct attribute *rdev_default_attrs[] = {
3338 &rdev_state.attr,
3339 &rdev_errors.attr,
3340 &rdev_slot.attr,
3341 &rdev_offset.attr,
3342 &rdev_new_offset.attr,
3343 &rdev_size.attr,
3344 &rdev_recovery_start.attr,
3345 &rdev_bad_blocks.attr,
3346 &rdev_unack_bad_blocks.attr,
3347 &rdev_ppl_sector.attr,
3348 &rdev_ppl_size.attr,
3349 NULL,
3351 static ssize_t
3352 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3354 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3355 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3357 if (!entry->show)
3358 return -EIO;
3359 if (!rdev->mddev)
3360 return -EBUSY;
3361 return entry->show(rdev, page);
3364 static ssize_t
3365 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3366 const char *page, size_t length)
3368 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3369 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3370 ssize_t rv;
3371 struct mddev *mddev = rdev->mddev;
3373 if (!entry->store)
3374 return -EIO;
3375 if (!capable(CAP_SYS_ADMIN))
3376 return -EACCES;
3377 rv = mddev ? mddev_lock(mddev): -EBUSY;
3378 if (!rv) {
3379 if (rdev->mddev == NULL)
3380 rv = -EBUSY;
3381 else
3382 rv = entry->store(rdev, page, length);
3383 mddev_unlock(mddev);
3385 return rv;
3388 static void rdev_free(struct kobject *ko)
3390 struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3391 kfree(rdev);
3393 static const struct sysfs_ops rdev_sysfs_ops = {
3394 .show = rdev_attr_show,
3395 .store = rdev_attr_store,
3397 static struct kobj_type rdev_ktype = {
3398 .release = rdev_free,
3399 .sysfs_ops = &rdev_sysfs_ops,
3400 .default_attrs = rdev_default_attrs,
3403 int md_rdev_init(struct md_rdev *rdev)
3405 rdev->desc_nr = -1;
3406 rdev->saved_raid_disk = -1;
3407 rdev->raid_disk = -1;
3408 rdev->flags = 0;
3409 rdev->data_offset = 0;
3410 rdev->new_data_offset = 0;
3411 rdev->sb_events = 0;
3412 rdev->last_read_error = 0;
3413 rdev->sb_loaded = 0;
3414 rdev->bb_page = NULL;
3415 atomic_set(&rdev->nr_pending, 0);
3416 atomic_set(&rdev->read_errors, 0);
3417 atomic_set(&rdev->corrected_errors, 0);
3419 INIT_LIST_HEAD(&rdev->same_set);
3420 init_waitqueue_head(&rdev->blocked_wait);
3422 /* Add space to store bad block list.
3423 * This reserves the space even on arrays where it cannot
3424 * be used - I wonder if that matters
3426 return badblocks_init(&rdev->badblocks, 0);
3428 EXPORT_SYMBOL_GPL(md_rdev_init);
3430 * Import a device. If 'super_format' >= 0, then sanity check the superblock
3432 * mark the device faulty if:
3434 * - the device is nonexistent (zero size)
3435 * - the device has no valid superblock
3437 * a faulty rdev _never_ has rdev->sb set.
3439 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3441 char b[BDEVNAME_SIZE];
3442 int err;
3443 struct md_rdev *rdev;
3444 sector_t size;
3446 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3447 if (!rdev)
3448 return ERR_PTR(-ENOMEM);
3450 err = md_rdev_init(rdev);
3451 if (err)
3452 goto abort_free;
3453 err = alloc_disk_sb(rdev);
3454 if (err)
3455 goto abort_free;
3457 err = lock_rdev(rdev, newdev, super_format == -2);
3458 if (err)
3459 goto abort_free;
3461 kobject_init(&rdev->kobj, &rdev_ktype);
3463 size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3464 if (!size) {
3465 pr_warn("md: %s has zero or unknown size, marking faulty!\n",
3466 bdevname(rdev->bdev,b));
3467 err = -EINVAL;
3468 goto abort_free;
3471 if (super_format >= 0) {
3472 err = super_types[super_format].
3473 load_super(rdev, NULL, super_minor);
3474 if (err == -EINVAL) {
3475 pr_warn("md: %s does not have a valid v%d.%d superblock, not importing!\n",
3476 bdevname(rdev->bdev,b),
3477 super_format, super_minor);
3478 goto abort_free;
3480 if (err < 0) {
3481 pr_warn("md: could not read %s's sb, not importing!\n",
3482 bdevname(rdev->bdev,b));
3483 goto abort_free;
3487 return rdev;
3489 abort_free:
3490 if (rdev->bdev)
3491 unlock_rdev(rdev);
3492 md_rdev_clear(rdev);
3493 kfree(rdev);
3494 return ERR_PTR(err);
3498 * Check a full RAID array for plausibility
3501 static void analyze_sbs(struct mddev *mddev)
3503 int i;
3504 struct md_rdev *rdev, *freshest, *tmp;
3505 char b[BDEVNAME_SIZE];
3507 freshest = NULL;
3508 rdev_for_each_safe(rdev, tmp, mddev)
3509 switch (super_types[mddev->major_version].
3510 load_super(rdev, freshest, mddev->minor_version)) {
3511 case 1:
3512 freshest = rdev;
3513 break;
3514 case 0:
3515 break;
3516 default:
3517 pr_warn("md: fatal superblock inconsistency in %s -- removing from array\n",
3518 bdevname(rdev->bdev,b));
3519 md_kick_rdev_from_array(rdev);
3522 super_types[mddev->major_version].
3523 validate_super(mddev, freshest);
3525 i = 0;
3526 rdev_for_each_safe(rdev, tmp, mddev) {
3527 if (mddev->max_disks &&
3528 (rdev->desc_nr >= mddev->max_disks ||
3529 i > mddev->max_disks)) {
3530 pr_warn("md: %s: %s: only %d devices permitted\n",
3531 mdname(mddev), bdevname(rdev->bdev, b),
3532 mddev->max_disks);
3533 md_kick_rdev_from_array(rdev);
3534 continue;
3536 if (rdev != freshest) {
3537 if (super_types[mddev->major_version].
3538 validate_super(mddev, rdev)) {
3539 pr_warn("md: kicking non-fresh %s from array!\n",
3540 bdevname(rdev->bdev,b));
3541 md_kick_rdev_from_array(rdev);
3542 continue;
3545 if (mddev->level == LEVEL_MULTIPATH) {
3546 rdev->desc_nr = i++;
3547 rdev->raid_disk = rdev->desc_nr;
3548 set_bit(In_sync, &rdev->flags);
3549 } else if (rdev->raid_disk >=
3550 (mddev->raid_disks - min(0, mddev->delta_disks)) &&
3551 !test_bit(Journal, &rdev->flags)) {
3552 rdev->raid_disk = -1;
3553 clear_bit(In_sync, &rdev->flags);
3558 /* Read a fixed-point number.
3559 * Numbers in sysfs attributes should be in "standard" units where
3560 * possible, so time should be in seconds.
3561 * However we internally use a a much smaller unit such as
3562 * milliseconds or jiffies.
3563 * This function takes a decimal number with a possible fractional
3564 * component, and produces an integer which is the result of
3565 * multiplying that number by 10^'scale'.
3566 * all without any floating-point arithmetic.
3568 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3570 unsigned long result = 0;
3571 long decimals = -1;
3572 while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3573 if (*cp == '.')
3574 decimals = 0;
3575 else if (decimals < scale) {
3576 unsigned int value;
3577 value = *cp - '0';
3578 result = result * 10 + value;
3579 if (decimals >= 0)
3580 decimals++;
3582 cp++;
3584 if (*cp == '\n')
3585 cp++;
3586 if (*cp)
3587 return -EINVAL;
3588 if (decimals < 0)
3589 decimals = 0;
3590 while (decimals < scale) {
3591 result *= 10;
3592 decimals ++;
3594 *res = result;
3595 return 0;
3598 static ssize_t
3599 safe_delay_show(struct mddev *mddev, char *page)
3601 int msec = (mddev->safemode_delay*1000)/HZ;
3602 return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3604 static ssize_t
3605 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3607 unsigned long msec;
3609 if (mddev_is_clustered(mddev)) {
3610 pr_warn("md: Safemode is disabled for clustered mode\n");
3611 return -EINVAL;
3614 if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3615 return -EINVAL;
3616 if (msec == 0)
3617 mddev->safemode_delay = 0;
3618 else {
3619 unsigned long old_delay = mddev->safemode_delay;
3620 unsigned long new_delay = (msec*HZ)/1000;
3622 if (new_delay == 0)
3623 new_delay = 1;
3624 mddev->safemode_delay = new_delay;
3625 if (new_delay < old_delay || old_delay == 0)
3626 mod_timer(&mddev->safemode_timer, jiffies+1);
3628 return len;
3630 static struct md_sysfs_entry md_safe_delay =
3631 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3633 static ssize_t
3634 level_show(struct mddev *mddev, char *page)
3636 struct md_personality *p;
3637 int ret;
3638 spin_lock(&mddev->lock);
3639 p = mddev->pers;
3640 if (p)
3641 ret = sprintf(page, "%s\n", p->name);
3642 else if (mddev->clevel[0])
3643 ret = sprintf(page, "%s\n", mddev->clevel);
3644 else if (mddev->level != LEVEL_NONE)
3645 ret = sprintf(page, "%d\n", mddev->level);
3646 else
3647 ret = 0;
3648 spin_unlock(&mddev->lock);
3649 return ret;
3652 static ssize_t
3653 level_store(struct mddev *mddev, const char *buf, size_t len)
3655 char clevel[16];
3656 ssize_t rv;
3657 size_t slen = len;
3658 struct md_personality *pers, *oldpers;
3659 long level;
3660 void *priv, *oldpriv;
3661 struct md_rdev *rdev;
3663 if (slen == 0 || slen >= sizeof(clevel))
3664 return -EINVAL;
3666 rv = mddev_lock(mddev);
3667 if (rv)
3668 return rv;
3670 if (mddev->pers == NULL) {
3671 strncpy(mddev->clevel, buf, slen);
3672 if (mddev->clevel[slen-1] == '\n')
3673 slen--;
3674 mddev->clevel[slen] = 0;
3675 mddev->level = LEVEL_NONE;
3676 rv = len;
3677 goto out_unlock;
3679 rv = -EROFS;
3680 if (mddev->ro)
3681 goto out_unlock;
3683 /* request to change the personality. Need to ensure:
3684 * - array is not engaged in resync/recovery/reshape
3685 * - old personality can be suspended
3686 * - new personality will access other array.
3689 rv = -EBUSY;
3690 if (mddev->sync_thread ||
3691 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3692 mddev->reshape_position != MaxSector ||
3693 mddev->sysfs_active)
3694 goto out_unlock;
3696 rv = -EINVAL;
3697 if (!mddev->pers->quiesce) {
3698 pr_warn("md: %s: %s does not support online personality change\n",
3699 mdname(mddev), mddev->pers->name);
3700 goto out_unlock;
3703 /* Now find the new personality */
3704 strncpy(clevel, buf, slen);
3705 if (clevel[slen-1] == '\n')
3706 slen--;
3707 clevel[slen] = 0;
3708 if (kstrtol(clevel, 10, &level))
3709 level = LEVEL_NONE;
3711 if (request_module("md-%s", clevel) != 0)
3712 request_module("md-level-%s", clevel);
3713 spin_lock(&pers_lock);
3714 pers = find_pers(level, clevel);
3715 if (!pers || !try_module_get(pers->owner)) {
3716 spin_unlock(&pers_lock);
3717 pr_warn("md: personality %s not loaded\n", clevel);
3718 rv = -EINVAL;
3719 goto out_unlock;
3721 spin_unlock(&pers_lock);
3723 if (pers == mddev->pers) {
3724 /* Nothing to do! */
3725 module_put(pers->owner);
3726 rv = len;
3727 goto out_unlock;
3729 if (!pers->takeover) {
3730 module_put(pers->owner);
3731 pr_warn("md: %s: %s does not support personality takeover\n",
3732 mdname(mddev), clevel);
3733 rv = -EINVAL;
3734 goto out_unlock;
3737 rdev_for_each(rdev, mddev)
3738 rdev->new_raid_disk = rdev->raid_disk;
3740 /* ->takeover must set new_* and/or delta_disks
3741 * if it succeeds, and may set them when it fails.
3743 priv = pers->takeover(mddev);
3744 if (IS_ERR(priv)) {
3745 mddev->new_level = mddev->level;
3746 mddev->new_layout = mddev->layout;
3747 mddev->new_chunk_sectors = mddev->chunk_sectors;
3748 mddev->raid_disks -= mddev->delta_disks;
3749 mddev->delta_disks = 0;
3750 mddev->reshape_backwards = 0;
3751 module_put(pers->owner);
3752 pr_warn("md: %s: %s would not accept array\n",
3753 mdname(mddev), clevel);
3754 rv = PTR_ERR(priv);
3755 goto out_unlock;
3758 /* Looks like we have a winner */
3759 mddev_suspend(mddev);
3760 mddev_detach(mddev);
3762 spin_lock(&mddev->lock);
3763 oldpers = mddev->pers;
3764 oldpriv = mddev->private;
3765 mddev->pers = pers;
3766 mddev->private = priv;
3767 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3768 mddev->level = mddev->new_level;
3769 mddev->layout = mddev->new_layout;
3770 mddev->chunk_sectors = mddev->new_chunk_sectors;
3771 mddev->delta_disks = 0;
3772 mddev->reshape_backwards = 0;
3773 mddev->degraded = 0;
3774 spin_unlock(&mddev->lock);
3776 if (oldpers->sync_request == NULL &&
3777 mddev->external) {
3778 /* We are converting from a no-redundancy array
3779 * to a redundancy array and metadata is managed
3780 * externally so we need to be sure that writes
3781 * won't block due to a need to transition
3782 * clean->dirty
3783 * until external management is started.
3785 mddev->in_sync = 0;
3786 mddev->safemode_delay = 0;
3787 mddev->safemode = 0;
3790 oldpers->free(mddev, oldpriv);
3792 if (oldpers->sync_request == NULL &&
3793 pers->sync_request != NULL) {
3794 /* need to add the md_redundancy_group */
3795 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3796 pr_warn("md: cannot register extra attributes for %s\n",
3797 mdname(mddev));
3798 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
3800 if (oldpers->sync_request != NULL &&
3801 pers->sync_request == NULL) {
3802 /* need to remove the md_redundancy_group */
3803 if (mddev->to_remove == NULL)
3804 mddev->to_remove = &md_redundancy_group;
3807 module_put(oldpers->owner);
3809 rdev_for_each(rdev, mddev) {
3810 if (rdev->raid_disk < 0)
3811 continue;
3812 if (rdev->new_raid_disk >= mddev->raid_disks)
3813 rdev->new_raid_disk = -1;
3814 if (rdev->new_raid_disk == rdev->raid_disk)
3815 continue;
3816 sysfs_unlink_rdev(mddev, rdev);
3818 rdev_for_each(rdev, mddev) {
3819 if (rdev->raid_disk < 0)
3820 continue;
3821 if (rdev->new_raid_disk == rdev->raid_disk)
3822 continue;
3823 rdev->raid_disk = rdev->new_raid_disk;
3824 if (rdev->raid_disk < 0)
3825 clear_bit(In_sync, &rdev->flags);
3826 else {
3827 if (sysfs_link_rdev(mddev, rdev))
3828 pr_warn("md: cannot register rd%d for %s after level change\n",
3829 rdev->raid_disk, mdname(mddev));
3833 if (pers->sync_request == NULL) {
3834 /* this is now an array without redundancy, so
3835 * it must always be in_sync
3837 mddev->in_sync = 1;
3838 del_timer_sync(&mddev->safemode_timer);
3840 blk_set_stacking_limits(&mddev->queue->limits);
3841 pers->run(mddev);
3842 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
3843 mddev_resume(mddev);
3844 if (!mddev->thread)
3845 md_update_sb(mddev, 1);
3846 sysfs_notify(&mddev->kobj, NULL, "level");
3847 md_new_event(mddev);
3848 rv = len;
3849 out_unlock:
3850 mddev_unlock(mddev);
3851 return rv;
3854 static struct md_sysfs_entry md_level =
3855 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3857 static ssize_t
3858 layout_show(struct mddev *mddev, char *page)
3860 /* just a number, not meaningful for all levels */
3861 if (mddev->reshape_position != MaxSector &&
3862 mddev->layout != mddev->new_layout)
3863 return sprintf(page, "%d (%d)\n",
3864 mddev->new_layout, mddev->layout);
3865 return sprintf(page, "%d\n", mddev->layout);
3868 static ssize_t
3869 layout_store(struct mddev *mddev, const char *buf, size_t len)
3871 unsigned int n;
3872 int err;
3874 err = kstrtouint(buf, 10, &n);
3875 if (err < 0)
3876 return err;
3877 err = mddev_lock(mddev);
3878 if (err)
3879 return err;
3881 if (mddev->pers) {
3882 if (mddev->pers->check_reshape == NULL)
3883 err = -EBUSY;
3884 else if (mddev->ro)
3885 err = -EROFS;
3886 else {
3887 mddev->new_layout = n;
3888 err = mddev->pers->check_reshape(mddev);
3889 if (err)
3890 mddev->new_layout = mddev->layout;
3892 } else {
3893 mddev->new_layout = n;
3894 if (mddev->reshape_position == MaxSector)
3895 mddev->layout = n;
3897 mddev_unlock(mddev);
3898 return err ?: len;
3900 static struct md_sysfs_entry md_layout =
3901 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3903 static ssize_t
3904 raid_disks_show(struct mddev *mddev, char *page)
3906 if (mddev->raid_disks == 0)
3907 return 0;
3908 if (mddev->reshape_position != MaxSector &&
3909 mddev->delta_disks != 0)
3910 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3911 mddev->raid_disks - mddev->delta_disks);
3912 return sprintf(page, "%d\n", mddev->raid_disks);
3915 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3917 static ssize_t
3918 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3920 unsigned int n;
3921 int err;
3923 err = kstrtouint(buf, 10, &n);
3924 if (err < 0)
3925 return err;
3927 err = mddev_lock(mddev);
3928 if (err)
3929 return err;
3930 if (mddev->pers)
3931 err = update_raid_disks(mddev, n);
3932 else if (mddev->reshape_position != MaxSector) {
3933 struct md_rdev *rdev;
3934 int olddisks = mddev->raid_disks - mddev->delta_disks;
3936 err = -EINVAL;
3937 rdev_for_each(rdev, mddev) {
3938 if (olddisks < n &&
3939 rdev->data_offset < rdev->new_data_offset)
3940 goto out_unlock;
3941 if (olddisks > n &&
3942 rdev->data_offset > rdev->new_data_offset)
3943 goto out_unlock;
3945 err = 0;
3946 mddev->delta_disks = n - olddisks;
3947 mddev->raid_disks = n;
3948 mddev->reshape_backwards = (mddev->delta_disks < 0);
3949 } else
3950 mddev->raid_disks = n;
3951 out_unlock:
3952 mddev_unlock(mddev);
3953 return err ? err : len;
3955 static struct md_sysfs_entry md_raid_disks =
3956 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3958 static ssize_t
3959 chunk_size_show(struct mddev *mddev, char *page)
3961 if (mddev->reshape_position != MaxSector &&
3962 mddev->chunk_sectors != mddev->new_chunk_sectors)
3963 return sprintf(page, "%d (%d)\n",
3964 mddev->new_chunk_sectors << 9,
3965 mddev->chunk_sectors << 9);
3966 return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3969 static ssize_t
3970 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3972 unsigned long n;
3973 int err;
3975 err = kstrtoul(buf, 10, &n);
3976 if (err < 0)
3977 return err;
3979 err = mddev_lock(mddev);
3980 if (err)
3981 return err;
3982 if (mddev->pers) {
3983 if (mddev->pers->check_reshape == NULL)
3984 err = -EBUSY;
3985 else if (mddev->ro)
3986 err = -EROFS;
3987 else {
3988 mddev->new_chunk_sectors = n >> 9;
3989 err = mddev->pers->check_reshape(mddev);
3990 if (err)
3991 mddev->new_chunk_sectors = mddev->chunk_sectors;
3993 } else {
3994 mddev->new_chunk_sectors = n >> 9;
3995 if (mddev->reshape_position == MaxSector)
3996 mddev->chunk_sectors = n >> 9;
3998 mddev_unlock(mddev);
3999 return err ?: len;
4001 static struct md_sysfs_entry md_chunk_size =
4002 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
4004 static ssize_t
4005 resync_start_show(struct mddev *mddev, char *page)
4007 if (mddev->recovery_cp == MaxSector)
4008 return sprintf(page, "none\n");
4009 return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
4012 static ssize_t
4013 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
4015 unsigned long long n;
4016 int err;
4018 if (cmd_match(buf, "none"))
4019 n = MaxSector;
4020 else {
4021 err = kstrtoull(buf, 10, &n);
4022 if (err < 0)
4023 return err;
4024 if (n != (sector_t)n)
4025 return -EINVAL;
4028 err = mddev_lock(mddev);
4029 if (err)
4030 return err;
4031 if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4032 err = -EBUSY;
4034 if (!err) {
4035 mddev->recovery_cp = n;
4036 if (mddev->pers)
4037 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
4039 mddev_unlock(mddev);
4040 return err ?: len;
4042 static struct md_sysfs_entry md_resync_start =
4043 __ATTR_PREALLOC(resync_start, S_IRUGO|S_IWUSR,
4044 resync_start_show, resync_start_store);
4047 * The array state can be:
4049 * clear
4050 * No devices, no size, no level
4051 * Equivalent to STOP_ARRAY ioctl
4052 * inactive
4053 * May have some settings, but array is not active
4054 * all IO results in error
4055 * When written, doesn't tear down array, but just stops it
4056 * suspended (not supported yet)
4057 * All IO requests will block. The array can be reconfigured.
4058 * Writing this, if accepted, will block until array is quiescent
4059 * readonly
4060 * no resync can happen. no superblocks get written.
4061 * write requests fail
4062 * read-auto
4063 * like readonly, but behaves like 'clean' on a write request.
4065 * clean - no pending writes, but otherwise active.
4066 * When written to inactive array, starts without resync
4067 * If a write request arrives then
4068 * if metadata is known, mark 'dirty' and switch to 'active'.
4069 * if not known, block and switch to write-pending
4070 * If written to an active array that has pending writes, then fails.
4071 * active
4072 * fully active: IO and resync can be happening.
4073 * When written to inactive array, starts with resync
4075 * write-pending
4076 * clean, but writes are blocked waiting for 'active' to be written.
4078 * active-idle
4079 * like active, but no writes have been seen for a while (100msec).
4082 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
4083 write_pending, active_idle, bad_word};
4084 static char *array_states[] = {
4085 "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
4086 "write-pending", "active-idle", NULL };
4088 static int match_word(const char *word, char **list)
4090 int n;
4091 for (n=0; list[n]; n++)
4092 if (cmd_match(word, list[n]))
4093 break;
4094 return n;
4097 static ssize_t
4098 array_state_show(struct mddev *mddev, char *page)
4100 enum array_state st = inactive;
4102 if (mddev->pers)
4103 switch(mddev->ro) {
4104 case 1:
4105 st = readonly;
4106 break;
4107 case 2:
4108 st = read_auto;
4109 break;
4110 case 0:
4111 spin_lock(&mddev->lock);
4112 if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
4113 st = write_pending;
4114 else if (mddev->in_sync)
4115 st = clean;
4116 else if (mddev->safemode)
4117 st = active_idle;
4118 else
4119 st = active;
4120 spin_unlock(&mddev->lock);
4122 else {
4123 if (list_empty(&mddev->disks) &&
4124 mddev->raid_disks == 0 &&
4125 mddev->dev_sectors == 0)
4126 st = clear;
4127 else
4128 st = inactive;
4130 return sprintf(page, "%s\n", array_states[st]);
4133 static int do_md_stop(struct mddev *mddev, int ro, struct block_device *bdev);
4134 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev);
4135 static int do_md_run(struct mddev *mddev);
4136 static int restart_array(struct mddev *mddev);
4138 static ssize_t
4139 array_state_store(struct mddev *mddev, const char *buf, size_t len)
4141 int err = 0;
4142 enum array_state st = match_word(buf, array_states);
4144 if (mddev->pers && (st == active || st == clean) && mddev->ro != 1) {
4145 /* don't take reconfig_mutex when toggling between
4146 * clean and active
4148 spin_lock(&mddev->lock);
4149 if (st == active) {
4150 restart_array(mddev);
4151 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4152 md_wakeup_thread(mddev->thread);
4153 wake_up(&mddev->sb_wait);
4154 } else /* st == clean */ {
4155 restart_array(mddev);
4156 if (!set_in_sync(mddev))
4157 err = -EBUSY;
4159 if (!err)
4160 sysfs_notify_dirent_safe(mddev->sysfs_state);
4161 spin_unlock(&mddev->lock);
4162 return err ?: len;
4164 err = mddev_lock(mddev);
4165 if (err)
4166 return err;
4167 err = -EINVAL;
4168 switch(st) {
4169 case bad_word:
4170 break;
4171 case clear:
4172 /* stopping an active array */
4173 err = do_md_stop(mddev, 0, NULL);
4174 break;
4175 case inactive:
4176 /* stopping an active array */
4177 if (mddev->pers)
4178 err = do_md_stop(mddev, 2, NULL);
4179 else
4180 err = 0; /* already inactive */
4181 break;
4182 case suspended:
4183 break; /* not supported yet */
4184 case readonly:
4185 if (mddev->pers)
4186 err = md_set_readonly(mddev, NULL);
4187 else {
4188 mddev->ro = 1;
4189 set_disk_ro(mddev->gendisk, 1);
4190 err = do_md_run(mddev);
4192 break;
4193 case read_auto:
4194 if (mddev->pers) {
4195 if (mddev->ro == 0)
4196 err = md_set_readonly(mddev, NULL);
4197 else if (mddev->ro == 1)
4198 err = restart_array(mddev);
4199 if (err == 0) {
4200 mddev->ro = 2;
4201 set_disk_ro(mddev->gendisk, 0);
4203 } else {
4204 mddev->ro = 2;
4205 err = do_md_run(mddev);
4207 break;
4208 case clean:
4209 if (mddev->pers) {
4210 err = restart_array(mddev);
4211 if (err)
4212 break;
4213 spin_lock(&mddev->lock);
4214 if (!set_in_sync(mddev))
4215 err = -EBUSY;
4216 spin_unlock(&mddev->lock);
4217 } else
4218 err = -EINVAL;
4219 break;
4220 case active:
4221 if (mddev->pers) {
4222 err = restart_array(mddev);
4223 if (err)
4224 break;
4225 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4226 wake_up(&mddev->sb_wait);
4227 err = 0;
4228 } else {
4229 mddev->ro = 0;
4230 set_disk_ro(mddev->gendisk, 0);
4231 err = do_md_run(mddev);
4233 break;
4234 case write_pending:
4235 case active_idle:
4236 /* these cannot be set */
4237 break;
4240 if (!err) {
4241 if (mddev->hold_active == UNTIL_IOCTL)
4242 mddev->hold_active = 0;
4243 sysfs_notify_dirent_safe(mddev->sysfs_state);
4245 mddev_unlock(mddev);
4246 return err ?: len;
4248 static struct md_sysfs_entry md_array_state =
4249 __ATTR_PREALLOC(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
4251 static ssize_t
4252 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
4253 return sprintf(page, "%d\n",
4254 atomic_read(&mddev->max_corr_read_errors));
4257 static ssize_t
4258 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
4260 unsigned int n;
4261 int rv;
4263 rv = kstrtouint(buf, 10, &n);
4264 if (rv < 0)
4265 return rv;
4266 atomic_set(&mddev->max_corr_read_errors, n);
4267 return len;
4270 static struct md_sysfs_entry max_corr_read_errors =
4271 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
4272 max_corrected_read_errors_store);
4274 static ssize_t
4275 null_show(struct mddev *mddev, char *page)
4277 return -EINVAL;
4280 static ssize_t
4281 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
4283 /* buf must be %d:%d\n? giving major and minor numbers */
4284 /* The new device is added to the array.
4285 * If the array has a persistent superblock, we read the
4286 * superblock to initialise info and check validity.
4287 * Otherwise, only checking done is that in bind_rdev_to_array,
4288 * which mainly checks size.
4290 char *e;
4291 int major = simple_strtoul(buf, &e, 10);
4292 int minor;
4293 dev_t dev;
4294 struct md_rdev *rdev;
4295 int err;
4297 if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
4298 return -EINVAL;
4299 minor = simple_strtoul(e+1, &e, 10);
4300 if (*e && *e != '\n')
4301 return -EINVAL;
4302 dev = MKDEV(major, minor);
4303 if (major != MAJOR(dev) ||
4304 minor != MINOR(dev))
4305 return -EOVERFLOW;
4307 flush_workqueue(md_misc_wq);
4309 err = mddev_lock(mddev);
4310 if (err)
4311 return err;
4312 if (mddev->persistent) {
4313 rdev = md_import_device(dev, mddev->major_version,
4314 mddev->minor_version);
4315 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
4316 struct md_rdev *rdev0
4317 = list_entry(mddev->disks.next,
4318 struct md_rdev, same_set);
4319 err = super_types[mddev->major_version]
4320 .load_super(rdev, rdev0, mddev->minor_version);
4321 if (err < 0)
4322 goto out;
4324 } else if (mddev->external)
4325 rdev = md_import_device(dev, -2, -1);
4326 else
4327 rdev = md_import_device(dev, -1, -1);
4329 if (IS_ERR(rdev)) {
4330 mddev_unlock(mddev);
4331 return PTR_ERR(rdev);
4333 err = bind_rdev_to_array(rdev, mddev);
4334 out:
4335 if (err)
4336 export_rdev(rdev);
4337 mddev_unlock(mddev);
4338 if (!err)
4339 md_new_event(mddev);
4340 return err ? err : len;
4343 static struct md_sysfs_entry md_new_device =
4344 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4346 static ssize_t
4347 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4349 char *end;
4350 unsigned long chunk, end_chunk;
4351 int err;
4353 err = mddev_lock(mddev);
4354 if (err)
4355 return err;
4356 if (!mddev->bitmap)
4357 goto out;
4358 /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4359 while (*buf) {
4360 chunk = end_chunk = simple_strtoul(buf, &end, 0);
4361 if (buf == end) break;
4362 if (*end == '-') { /* range */
4363 buf = end + 1;
4364 end_chunk = simple_strtoul(buf, &end, 0);
4365 if (buf == end) break;
4367 if (*end && !isspace(*end)) break;
4368 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4369 buf = skip_spaces(end);
4371 bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4372 out:
4373 mddev_unlock(mddev);
4374 return len;
4377 static struct md_sysfs_entry md_bitmap =
4378 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4380 static ssize_t
4381 size_show(struct mddev *mddev, char *page)
4383 return sprintf(page, "%llu\n",
4384 (unsigned long long)mddev->dev_sectors / 2);
4387 static int update_size(struct mddev *mddev, sector_t num_sectors);
4389 static ssize_t
4390 size_store(struct mddev *mddev, const char *buf, size_t len)
4392 /* If array is inactive, we can reduce the component size, but
4393 * not increase it (except from 0).
4394 * If array is active, we can try an on-line resize
4396 sector_t sectors;
4397 int err = strict_blocks_to_sectors(buf, &sectors);
4399 if (err < 0)
4400 return err;
4401 err = mddev_lock(mddev);
4402 if (err)
4403 return err;
4404 if (mddev->pers) {
4405 err = update_size(mddev, sectors);
4406 if (err == 0)
4407 md_update_sb(mddev, 1);
4408 } else {
4409 if (mddev->dev_sectors == 0 ||
4410 mddev->dev_sectors > sectors)
4411 mddev->dev_sectors = sectors;
4412 else
4413 err = -ENOSPC;
4415 mddev_unlock(mddev);
4416 return err ? err : len;
4419 static struct md_sysfs_entry md_size =
4420 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4422 /* Metadata version.
4423 * This is one of
4424 * 'none' for arrays with no metadata (good luck...)
4425 * 'external' for arrays with externally managed metadata,
4426 * or N.M for internally known formats
4428 static ssize_t
4429 metadata_show(struct mddev *mddev, char *page)
4431 if (mddev->persistent)
4432 return sprintf(page, "%d.%d\n",
4433 mddev->major_version, mddev->minor_version);
4434 else if (mddev->external)
4435 return sprintf(page, "external:%s\n", mddev->metadata_type);
4436 else
4437 return sprintf(page, "none\n");
4440 static ssize_t
4441 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4443 int major, minor;
4444 char *e;
4445 int err;
4446 /* Changing the details of 'external' metadata is
4447 * always permitted. Otherwise there must be
4448 * no devices attached to the array.
4451 err = mddev_lock(mddev);
4452 if (err)
4453 return err;
4454 err = -EBUSY;
4455 if (mddev->external && strncmp(buf, "external:", 9) == 0)
4457 else if (!list_empty(&mddev->disks))
4458 goto out_unlock;
4460 err = 0;
4461 if (cmd_match(buf, "none")) {
4462 mddev->persistent = 0;
4463 mddev->external = 0;
4464 mddev->major_version = 0;
4465 mddev->minor_version = 90;
4466 goto out_unlock;
4468 if (strncmp(buf, "external:", 9) == 0) {
4469 size_t namelen = len-9;
4470 if (namelen >= sizeof(mddev->metadata_type))
4471 namelen = sizeof(mddev->metadata_type)-1;
4472 strncpy(mddev->metadata_type, buf+9, namelen);
4473 mddev->metadata_type[namelen] = 0;
4474 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4475 mddev->metadata_type[--namelen] = 0;
4476 mddev->persistent = 0;
4477 mddev->external = 1;
4478 mddev->major_version = 0;
4479 mddev->minor_version = 90;
4480 goto out_unlock;
4482 major = simple_strtoul(buf, &e, 10);
4483 err = -EINVAL;
4484 if (e==buf || *e != '.')
4485 goto out_unlock;
4486 buf = e+1;
4487 minor = simple_strtoul(buf, &e, 10);
4488 if (e==buf || (*e && *e != '\n') )
4489 goto out_unlock;
4490 err = -ENOENT;
4491 if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4492 goto out_unlock;
4493 mddev->major_version = major;
4494 mddev->minor_version = minor;
4495 mddev->persistent = 1;
4496 mddev->external = 0;
4497 err = 0;
4498 out_unlock:
4499 mddev_unlock(mddev);
4500 return err ?: len;
4503 static struct md_sysfs_entry md_metadata =
4504 __ATTR_PREALLOC(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4506 static ssize_t
4507 action_show(struct mddev *mddev, char *page)
4509 char *type = "idle";
4510 unsigned long recovery = mddev->recovery;
4511 if (test_bit(MD_RECOVERY_FROZEN, &recovery))
4512 type = "frozen";
4513 else if (test_bit(MD_RECOVERY_RUNNING, &recovery) ||
4514 (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &recovery))) {
4515 if (test_bit(MD_RECOVERY_RESHAPE, &recovery))
4516 type = "reshape";
4517 else if (test_bit(MD_RECOVERY_SYNC, &recovery)) {
4518 if (!test_bit(MD_RECOVERY_REQUESTED, &recovery))
4519 type = "resync";
4520 else if (test_bit(MD_RECOVERY_CHECK, &recovery))
4521 type = "check";
4522 else
4523 type = "repair";
4524 } else if (test_bit(MD_RECOVERY_RECOVER, &recovery))
4525 type = "recover";
4526 else if (mddev->reshape_position != MaxSector)
4527 type = "reshape";
4529 return sprintf(page, "%s\n", type);
4532 static ssize_t
4533 action_store(struct mddev *mddev, const char *page, size_t len)
4535 if (!mddev->pers || !mddev->pers->sync_request)
4536 return -EINVAL;
4539 if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4540 if (cmd_match(page, "frozen"))
4541 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4542 else
4543 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4544 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4545 mddev_lock(mddev) == 0) {
4546 flush_workqueue(md_misc_wq);
4547 if (mddev->sync_thread) {
4548 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4549 md_reap_sync_thread(mddev);
4551 mddev_unlock(mddev);
4553 } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4554 return -EBUSY;
4555 else if (cmd_match(page, "resync"))
4556 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4557 else if (cmd_match(page, "recover")) {
4558 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4559 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4560 } else if (cmd_match(page, "reshape")) {
4561 int err;
4562 if (mddev->pers->start_reshape == NULL)
4563 return -EINVAL;
4564 err = mddev_lock(mddev);
4565 if (!err) {
4566 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4567 err = -EBUSY;
4568 else {
4569 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4570 err = mddev->pers->start_reshape(mddev);
4572 mddev_unlock(mddev);
4574 if (err)
4575 return err;
4576 sysfs_notify(&mddev->kobj, NULL, "degraded");
4577 } else {
4578 if (cmd_match(page, "check"))
4579 set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4580 else if (!cmd_match(page, "repair"))
4581 return -EINVAL;
4582 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4583 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4584 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4586 if (mddev->ro == 2) {
4587 /* A write to sync_action is enough to justify
4588 * canceling read-auto mode
4590 mddev->ro = 0;
4591 md_wakeup_thread(mddev->sync_thread);
4593 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4594 md_wakeup_thread(mddev->thread);
4595 sysfs_notify_dirent_safe(mddev->sysfs_action);
4596 return len;
4599 static struct md_sysfs_entry md_scan_mode =
4600 __ATTR_PREALLOC(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4602 static ssize_t
4603 last_sync_action_show(struct mddev *mddev, char *page)
4605 return sprintf(page, "%s\n", mddev->last_sync_action);
4608 static struct md_sysfs_entry md_last_scan_mode = __ATTR_RO(last_sync_action);
4610 static ssize_t
4611 mismatch_cnt_show(struct mddev *mddev, char *page)
4613 return sprintf(page, "%llu\n",
4614 (unsigned long long)
4615 atomic64_read(&mddev->resync_mismatches));
4618 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4620 static ssize_t
4621 sync_min_show(struct mddev *mddev, char *page)
4623 return sprintf(page, "%d (%s)\n", speed_min(mddev),
4624 mddev->sync_speed_min ? "local": "system");
4627 static ssize_t
4628 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4630 unsigned int min;
4631 int rv;
4633 if (strncmp(buf, "system", 6)==0) {
4634 min = 0;
4635 } else {
4636 rv = kstrtouint(buf, 10, &min);
4637 if (rv < 0)
4638 return rv;
4639 if (min == 0)
4640 return -EINVAL;
4642 mddev->sync_speed_min = min;
4643 return len;
4646 static struct md_sysfs_entry md_sync_min =
4647 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4649 static ssize_t
4650 sync_max_show(struct mddev *mddev, char *page)
4652 return sprintf(page, "%d (%s)\n", speed_max(mddev),
4653 mddev->sync_speed_max ? "local": "system");
4656 static ssize_t
4657 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4659 unsigned int max;
4660 int rv;
4662 if (strncmp(buf, "system", 6)==0) {
4663 max = 0;
4664 } else {
4665 rv = kstrtouint(buf, 10, &max);
4666 if (rv < 0)
4667 return rv;
4668 if (max == 0)
4669 return -EINVAL;
4671 mddev->sync_speed_max = max;
4672 return len;
4675 static struct md_sysfs_entry md_sync_max =
4676 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4678 static ssize_t
4679 degraded_show(struct mddev *mddev, char *page)
4681 return sprintf(page, "%d\n", mddev->degraded);
4683 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4685 static ssize_t
4686 sync_force_parallel_show(struct mddev *mddev, char *page)
4688 return sprintf(page, "%d\n", mddev->parallel_resync);
4691 static ssize_t
4692 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4694 long n;
4696 if (kstrtol(buf, 10, &n))
4697 return -EINVAL;
4699 if (n != 0 && n != 1)
4700 return -EINVAL;
4702 mddev->parallel_resync = n;
4704 if (mddev->sync_thread)
4705 wake_up(&resync_wait);
4707 return len;
4710 /* force parallel resync, even with shared block devices */
4711 static struct md_sysfs_entry md_sync_force_parallel =
4712 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4713 sync_force_parallel_show, sync_force_parallel_store);
4715 static ssize_t
4716 sync_speed_show(struct mddev *mddev, char *page)
4718 unsigned long resync, dt, db;
4719 if (mddev->curr_resync == 0)
4720 return sprintf(page, "none\n");
4721 resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4722 dt = (jiffies - mddev->resync_mark) / HZ;
4723 if (!dt) dt++;
4724 db = resync - mddev->resync_mark_cnt;
4725 return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4728 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4730 static ssize_t
4731 sync_completed_show(struct mddev *mddev, char *page)
4733 unsigned long long max_sectors, resync;
4735 if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4736 return sprintf(page, "none\n");
4738 if (mddev->curr_resync == 1 ||
4739 mddev->curr_resync == 2)
4740 return sprintf(page, "delayed\n");
4742 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4743 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4744 max_sectors = mddev->resync_max_sectors;
4745 else
4746 max_sectors = mddev->dev_sectors;
4748 resync = mddev->curr_resync_completed;
4749 return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4752 static struct md_sysfs_entry md_sync_completed =
4753 __ATTR_PREALLOC(sync_completed, S_IRUGO, sync_completed_show, NULL);
4755 static ssize_t
4756 min_sync_show(struct mddev *mddev, char *page)
4758 return sprintf(page, "%llu\n",
4759 (unsigned long long)mddev->resync_min);
4761 static ssize_t
4762 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4764 unsigned long long min;
4765 int err;
4767 if (kstrtoull(buf, 10, &min))
4768 return -EINVAL;
4770 spin_lock(&mddev->lock);
4771 err = -EINVAL;
4772 if (min > mddev->resync_max)
4773 goto out_unlock;
4775 err = -EBUSY;
4776 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4777 goto out_unlock;
4779 /* Round down to multiple of 4K for safety */
4780 mddev->resync_min = round_down(min, 8);
4781 err = 0;
4783 out_unlock:
4784 spin_unlock(&mddev->lock);
4785 return err ?: len;
4788 static struct md_sysfs_entry md_min_sync =
4789 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4791 static ssize_t
4792 max_sync_show(struct mddev *mddev, char *page)
4794 if (mddev->resync_max == MaxSector)
4795 return sprintf(page, "max\n");
4796 else
4797 return sprintf(page, "%llu\n",
4798 (unsigned long long)mddev->resync_max);
4800 static ssize_t
4801 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4803 int err;
4804 spin_lock(&mddev->lock);
4805 if (strncmp(buf, "max", 3) == 0)
4806 mddev->resync_max = MaxSector;
4807 else {
4808 unsigned long long max;
4809 int chunk;
4811 err = -EINVAL;
4812 if (kstrtoull(buf, 10, &max))
4813 goto out_unlock;
4814 if (max < mddev->resync_min)
4815 goto out_unlock;
4817 err = -EBUSY;
4818 if (max < mddev->resync_max &&
4819 mddev->ro == 0 &&
4820 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4821 goto out_unlock;
4823 /* Must be a multiple of chunk_size */
4824 chunk = mddev->chunk_sectors;
4825 if (chunk) {
4826 sector_t temp = max;
4828 err = -EINVAL;
4829 if (sector_div(temp, chunk))
4830 goto out_unlock;
4832 mddev->resync_max = max;
4834 wake_up(&mddev->recovery_wait);
4835 err = 0;
4836 out_unlock:
4837 spin_unlock(&mddev->lock);
4838 return err ?: len;
4841 static struct md_sysfs_entry md_max_sync =
4842 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4844 static ssize_t
4845 suspend_lo_show(struct mddev *mddev, char *page)
4847 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4850 static ssize_t
4851 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4853 unsigned long long old, new;
4854 int err;
4856 err = kstrtoull(buf, 10, &new);
4857 if (err < 0)
4858 return err;
4859 if (new != (sector_t)new)
4860 return -EINVAL;
4862 err = mddev_lock(mddev);
4863 if (err)
4864 return err;
4865 err = -EINVAL;
4866 if (mddev->pers == NULL ||
4867 mddev->pers->quiesce == NULL)
4868 goto unlock;
4869 old = mddev->suspend_lo;
4870 mddev->suspend_lo = new;
4871 if (new >= old) {
4872 /* Shrinking suspended region */
4873 wake_up(&mddev->sb_wait);
4874 mddev->pers->quiesce(mddev, 2);
4875 } else {
4876 /* Expanding suspended region - need to wait */
4877 mddev_suspend(mddev);
4878 mddev_resume(mddev);
4880 err = 0;
4881 unlock:
4882 mddev_unlock(mddev);
4883 return err ?: len;
4885 static struct md_sysfs_entry md_suspend_lo =
4886 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4888 static ssize_t
4889 suspend_hi_show(struct mddev *mddev, char *page)
4891 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4894 static ssize_t
4895 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4897 unsigned long long old, new;
4898 int err;
4900 err = kstrtoull(buf, 10, &new);
4901 if (err < 0)
4902 return err;
4903 if (new != (sector_t)new)
4904 return -EINVAL;
4906 err = mddev_lock(mddev);
4907 if (err)
4908 return err;
4909 err = -EINVAL;
4910 if (mddev->pers == NULL ||
4911 mddev->pers->quiesce == NULL)
4912 goto unlock;
4913 old = mddev->suspend_hi;
4914 mddev->suspend_hi = new;
4915 if (new <= old) {
4916 /* Shrinking suspended region */
4917 wake_up(&mddev->sb_wait);
4918 mddev->pers->quiesce(mddev, 2);
4919 } else {
4920 /* Expanding suspended region - need to wait */
4921 mddev_suspend(mddev);
4922 mddev_resume(mddev);
4924 err = 0;
4925 unlock:
4926 mddev_unlock(mddev);
4927 return err ?: len;
4929 static struct md_sysfs_entry md_suspend_hi =
4930 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4932 static ssize_t
4933 reshape_position_show(struct mddev *mddev, char *page)
4935 if (mddev->reshape_position != MaxSector)
4936 return sprintf(page, "%llu\n",
4937 (unsigned long long)mddev->reshape_position);
4938 strcpy(page, "none\n");
4939 return 5;
4942 static ssize_t
4943 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4945 struct md_rdev *rdev;
4946 unsigned long long new;
4947 int err;
4949 err = kstrtoull(buf, 10, &new);
4950 if (err < 0)
4951 return err;
4952 if (new != (sector_t)new)
4953 return -EINVAL;
4954 err = mddev_lock(mddev);
4955 if (err)
4956 return err;
4957 err = -EBUSY;
4958 if (mddev->pers)
4959 goto unlock;
4960 mddev->reshape_position = new;
4961 mddev->delta_disks = 0;
4962 mddev->reshape_backwards = 0;
4963 mddev->new_level = mddev->level;
4964 mddev->new_layout = mddev->layout;
4965 mddev->new_chunk_sectors = mddev->chunk_sectors;
4966 rdev_for_each(rdev, mddev)
4967 rdev->new_data_offset = rdev->data_offset;
4968 err = 0;
4969 unlock:
4970 mddev_unlock(mddev);
4971 return err ?: len;
4974 static struct md_sysfs_entry md_reshape_position =
4975 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4976 reshape_position_store);
4978 static ssize_t
4979 reshape_direction_show(struct mddev *mddev, char *page)
4981 return sprintf(page, "%s\n",
4982 mddev->reshape_backwards ? "backwards" : "forwards");
4985 static ssize_t
4986 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
4988 int backwards = 0;
4989 int err;
4991 if (cmd_match(buf, "forwards"))
4992 backwards = 0;
4993 else if (cmd_match(buf, "backwards"))
4994 backwards = 1;
4995 else
4996 return -EINVAL;
4997 if (mddev->reshape_backwards == backwards)
4998 return len;
5000 err = mddev_lock(mddev);
5001 if (err)
5002 return err;
5003 /* check if we are allowed to change */
5004 if (mddev->delta_disks)
5005 err = -EBUSY;
5006 else if (mddev->persistent &&
5007 mddev->major_version == 0)
5008 err = -EINVAL;
5009 else
5010 mddev->reshape_backwards = backwards;
5011 mddev_unlock(mddev);
5012 return err ?: len;
5015 static struct md_sysfs_entry md_reshape_direction =
5016 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
5017 reshape_direction_store);
5019 static ssize_t
5020 array_size_show(struct mddev *mddev, char *page)
5022 if (mddev->external_size)
5023 return sprintf(page, "%llu\n",
5024 (unsigned long long)mddev->array_sectors/2);
5025 else
5026 return sprintf(page, "default\n");
5029 static ssize_t
5030 array_size_store(struct mddev *mddev, const char *buf, size_t len)
5032 sector_t sectors;
5033 int err;
5035 err = mddev_lock(mddev);
5036 if (err)
5037 return err;
5039 /* cluster raid doesn't support change array_sectors */
5040 if (mddev_is_clustered(mddev)) {
5041 mddev_unlock(mddev);
5042 return -EINVAL;
5045 if (strncmp(buf, "default", 7) == 0) {
5046 if (mddev->pers)
5047 sectors = mddev->pers->size(mddev, 0, 0);
5048 else
5049 sectors = mddev->array_sectors;
5051 mddev->external_size = 0;
5052 } else {
5053 if (strict_blocks_to_sectors(buf, &sectors) < 0)
5054 err = -EINVAL;
5055 else if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
5056 err = -E2BIG;
5057 else
5058 mddev->external_size = 1;
5061 if (!err) {
5062 mddev->array_sectors = sectors;
5063 if (mddev->pers) {
5064 set_capacity(mddev->gendisk, mddev->array_sectors);
5065 revalidate_disk(mddev->gendisk);
5068 mddev_unlock(mddev);
5069 return err ?: len;
5072 static struct md_sysfs_entry md_array_size =
5073 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
5074 array_size_store);
5076 static ssize_t
5077 consistency_policy_show(struct mddev *mddev, char *page)
5079 int ret;
5081 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
5082 ret = sprintf(page, "journal\n");
5083 } else if (test_bit(MD_HAS_PPL, &mddev->flags)) {
5084 ret = sprintf(page, "ppl\n");
5085 } else if (mddev->bitmap) {
5086 ret = sprintf(page, "bitmap\n");
5087 } else if (mddev->pers) {
5088 if (mddev->pers->sync_request)
5089 ret = sprintf(page, "resync\n");
5090 else
5091 ret = sprintf(page, "none\n");
5092 } else {
5093 ret = sprintf(page, "unknown\n");
5096 return ret;
5099 static ssize_t
5100 consistency_policy_store(struct mddev *mddev, const char *buf, size_t len)
5102 int err = 0;
5104 if (mddev->pers) {
5105 if (mddev->pers->change_consistency_policy)
5106 err = mddev->pers->change_consistency_policy(mddev, buf);
5107 else
5108 err = -EBUSY;
5109 } else if (mddev->external && strncmp(buf, "ppl", 3) == 0) {
5110 set_bit(MD_HAS_PPL, &mddev->flags);
5111 } else {
5112 err = -EINVAL;
5115 return err ? err : len;
5118 static struct md_sysfs_entry md_consistency_policy =
5119 __ATTR(consistency_policy, S_IRUGO | S_IWUSR, consistency_policy_show,
5120 consistency_policy_store);
5122 static struct attribute *md_default_attrs[] = {
5123 &md_level.attr,
5124 &md_layout.attr,
5125 &md_raid_disks.attr,
5126 &md_chunk_size.attr,
5127 &md_size.attr,
5128 &md_resync_start.attr,
5129 &md_metadata.attr,
5130 &md_new_device.attr,
5131 &md_safe_delay.attr,
5132 &md_array_state.attr,
5133 &md_reshape_position.attr,
5134 &md_reshape_direction.attr,
5135 &md_array_size.attr,
5136 &max_corr_read_errors.attr,
5137 &md_consistency_policy.attr,
5138 NULL,
5141 static struct attribute *md_redundancy_attrs[] = {
5142 &md_scan_mode.attr,
5143 &md_last_scan_mode.attr,
5144 &md_mismatches.attr,
5145 &md_sync_min.attr,
5146 &md_sync_max.attr,
5147 &md_sync_speed.attr,
5148 &md_sync_force_parallel.attr,
5149 &md_sync_completed.attr,
5150 &md_min_sync.attr,
5151 &md_max_sync.attr,
5152 &md_suspend_lo.attr,
5153 &md_suspend_hi.attr,
5154 &md_bitmap.attr,
5155 &md_degraded.attr,
5156 NULL,
5158 static struct attribute_group md_redundancy_group = {
5159 .name = NULL,
5160 .attrs = md_redundancy_attrs,
5163 static ssize_t
5164 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
5166 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5167 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5168 ssize_t rv;
5170 if (!entry->show)
5171 return -EIO;
5172 spin_lock(&all_mddevs_lock);
5173 if (list_empty(&mddev->all_mddevs)) {
5174 spin_unlock(&all_mddevs_lock);
5175 return -EBUSY;
5177 mddev_get(mddev);
5178 spin_unlock(&all_mddevs_lock);
5180 rv = entry->show(mddev, page);
5181 mddev_put(mddev);
5182 return rv;
5185 static ssize_t
5186 md_attr_store(struct kobject *kobj, struct attribute *attr,
5187 const char *page, size_t length)
5189 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5190 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5191 ssize_t rv;
5193 if (!entry->store)
5194 return -EIO;
5195 if (!capable(CAP_SYS_ADMIN))
5196 return -EACCES;
5197 spin_lock(&all_mddevs_lock);
5198 if (list_empty(&mddev->all_mddevs)) {
5199 spin_unlock(&all_mddevs_lock);
5200 return -EBUSY;
5202 mddev_get(mddev);
5203 spin_unlock(&all_mddevs_lock);
5204 rv = entry->store(mddev, page, length);
5205 mddev_put(mddev);
5206 return rv;
5209 static void md_free(struct kobject *ko)
5211 struct mddev *mddev = container_of(ko, struct mddev, kobj);
5213 if (mddev->sysfs_state)
5214 sysfs_put(mddev->sysfs_state);
5216 if (mddev->queue)
5217 blk_cleanup_queue(mddev->queue);
5218 if (mddev->gendisk) {
5219 del_gendisk(mddev->gendisk);
5220 put_disk(mddev->gendisk);
5222 percpu_ref_exit(&mddev->writes_pending);
5224 kfree(mddev);
5227 static const struct sysfs_ops md_sysfs_ops = {
5228 .show = md_attr_show,
5229 .store = md_attr_store,
5231 static struct kobj_type md_ktype = {
5232 .release = md_free,
5233 .sysfs_ops = &md_sysfs_ops,
5234 .default_attrs = md_default_attrs,
5237 int mdp_major = 0;
5239 static void mddev_delayed_delete(struct work_struct *ws)
5241 struct mddev *mddev = container_of(ws, struct mddev, del_work);
5243 sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
5244 kobject_del(&mddev->kobj);
5245 kobject_put(&mddev->kobj);
5248 static void no_op(struct percpu_ref *r) {}
5250 int mddev_init_writes_pending(struct mddev *mddev)
5252 if (mddev->writes_pending.percpu_count_ptr)
5253 return 0;
5254 if (percpu_ref_init(&mddev->writes_pending, no_op, 0, GFP_KERNEL) < 0)
5255 return -ENOMEM;
5256 /* We want to start with the refcount at zero */
5257 percpu_ref_put(&mddev->writes_pending);
5258 return 0;
5260 EXPORT_SYMBOL_GPL(mddev_init_writes_pending);
5262 static int md_alloc(dev_t dev, char *name)
5265 * If dev is zero, name is the name of a device to allocate with
5266 * an arbitrary minor number. It will be "md_???"
5267 * If dev is non-zero it must be a device number with a MAJOR of
5268 * MD_MAJOR or mdp_major. In this case, if "name" is NULL, then
5269 * the device is being created by opening a node in /dev.
5270 * If "name" is not NULL, the device is being created by
5271 * writing to /sys/module/md_mod/parameters/new_array.
5273 static DEFINE_MUTEX(disks_mutex);
5274 struct mddev *mddev = mddev_find(dev);
5275 struct gendisk *disk;
5276 int partitioned;
5277 int shift;
5278 int unit;
5279 int error;
5281 if (!mddev)
5282 return -ENODEV;
5284 partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
5285 shift = partitioned ? MdpMinorShift : 0;
5286 unit = MINOR(mddev->unit) >> shift;
5288 /* wait for any previous instance of this device to be
5289 * completely removed (mddev_delayed_delete).
5291 flush_workqueue(md_misc_wq);
5293 mutex_lock(&disks_mutex);
5294 error = -EEXIST;
5295 if (mddev->gendisk)
5296 goto abort;
5298 if (name && !dev) {
5299 /* Need to ensure that 'name' is not a duplicate.
5301 struct mddev *mddev2;
5302 spin_lock(&all_mddevs_lock);
5304 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
5305 if (mddev2->gendisk &&
5306 strcmp(mddev2->gendisk->disk_name, name) == 0) {
5307 spin_unlock(&all_mddevs_lock);
5308 goto abort;
5310 spin_unlock(&all_mddevs_lock);
5312 if (name && dev)
5314 * Creating /dev/mdNNN via "newarray", so adjust hold_active.
5316 mddev->hold_active = UNTIL_STOP;
5318 error = -ENOMEM;
5319 mddev->queue = blk_alloc_queue(GFP_KERNEL);
5320 if (!mddev->queue)
5321 goto abort;
5322 mddev->queue->queuedata = mddev;
5324 blk_queue_make_request(mddev->queue, md_make_request);
5325 blk_set_stacking_limits(&mddev->queue->limits);
5327 disk = alloc_disk(1 << shift);
5328 if (!disk) {
5329 blk_cleanup_queue(mddev->queue);
5330 mddev->queue = NULL;
5331 goto abort;
5333 disk->major = MAJOR(mddev->unit);
5334 disk->first_minor = unit << shift;
5335 if (name)
5336 strcpy(disk->disk_name, name);
5337 else if (partitioned)
5338 sprintf(disk->disk_name, "md_d%d", unit);
5339 else
5340 sprintf(disk->disk_name, "md%d", unit);
5341 disk->fops = &md_fops;
5342 disk->private_data = mddev;
5343 disk->queue = mddev->queue;
5344 blk_queue_write_cache(mddev->queue, true, true);
5345 /* Allow extended partitions. This makes the
5346 * 'mdp' device redundant, but we can't really
5347 * remove it now.
5349 disk->flags |= GENHD_FL_EXT_DEVT;
5350 mddev->gendisk = disk;
5351 /* As soon as we call add_disk(), another thread could get
5352 * through to md_open, so make sure it doesn't get too far
5354 mutex_lock(&mddev->open_mutex);
5355 add_disk(disk);
5357 error = kobject_init_and_add(&mddev->kobj, &md_ktype,
5358 &disk_to_dev(disk)->kobj, "%s", "md");
5359 if (error) {
5360 /* This isn't possible, but as kobject_init_and_add is marked
5361 * __must_check, we must do something with the result
5363 pr_debug("md: cannot register %s/md - name in use\n",
5364 disk->disk_name);
5365 error = 0;
5367 if (mddev->kobj.sd &&
5368 sysfs_create_group(&mddev->kobj, &md_bitmap_group))
5369 pr_debug("pointless warning\n");
5370 mutex_unlock(&mddev->open_mutex);
5371 abort:
5372 mutex_unlock(&disks_mutex);
5373 if (!error && mddev->kobj.sd) {
5374 kobject_uevent(&mddev->kobj, KOBJ_ADD);
5375 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
5377 mddev_put(mddev);
5378 return error;
5381 static struct kobject *md_probe(dev_t dev, int *part, void *data)
5383 if (create_on_open)
5384 md_alloc(dev, NULL);
5385 return NULL;
5388 static int add_named_array(const char *val, struct kernel_param *kp)
5391 * val must be "md_*" or "mdNNN".
5392 * For "md_*" we allocate an array with a large free minor number, and
5393 * set the name to val. val must not already be an active name.
5394 * For "mdNNN" we allocate an array with the minor number NNN
5395 * which must not already be in use.
5397 int len = strlen(val);
5398 char buf[DISK_NAME_LEN];
5399 unsigned long devnum;
5401 while (len && val[len-1] == '\n')
5402 len--;
5403 if (len >= DISK_NAME_LEN)
5404 return -E2BIG;
5405 strlcpy(buf, val, len+1);
5406 if (strncmp(buf, "md_", 3) == 0)
5407 return md_alloc(0, buf);
5408 if (strncmp(buf, "md", 2) == 0 &&
5409 isdigit(buf[2]) &&
5410 kstrtoul(buf+2, 10, &devnum) == 0 &&
5411 devnum <= MINORMASK)
5412 return md_alloc(MKDEV(MD_MAJOR, devnum), NULL);
5414 return -EINVAL;
5417 static void md_safemode_timeout(unsigned long data)
5419 struct mddev *mddev = (struct mddev *) data;
5421 mddev->safemode = 1;
5422 if (mddev->external)
5423 sysfs_notify_dirent_safe(mddev->sysfs_state);
5425 md_wakeup_thread(mddev->thread);
5428 static int start_dirty_degraded;
5430 int md_run(struct mddev *mddev)
5432 int err;
5433 struct md_rdev *rdev;
5434 struct md_personality *pers;
5436 if (list_empty(&mddev->disks))
5437 /* cannot run an array with no devices.. */
5438 return -EINVAL;
5440 if (mddev->pers)
5441 return -EBUSY;
5442 /* Cannot run until previous stop completes properly */
5443 if (mddev->sysfs_active)
5444 return -EBUSY;
5447 * Analyze all RAID superblock(s)
5449 if (!mddev->raid_disks) {
5450 if (!mddev->persistent)
5451 return -EINVAL;
5452 analyze_sbs(mddev);
5455 if (mddev->level != LEVEL_NONE)
5456 request_module("md-level-%d", mddev->level);
5457 else if (mddev->clevel[0])
5458 request_module("md-%s", mddev->clevel);
5461 * Drop all container device buffers, from now on
5462 * the only valid external interface is through the md
5463 * device.
5465 mddev->has_superblocks = false;
5466 rdev_for_each(rdev, mddev) {
5467 if (test_bit(Faulty, &rdev->flags))
5468 continue;
5469 sync_blockdev(rdev->bdev);
5470 invalidate_bdev(rdev->bdev);
5471 if (mddev->ro != 1 &&
5472 (bdev_read_only(rdev->bdev) ||
5473 bdev_read_only(rdev->meta_bdev))) {
5474 mddev->ro = 1;
5475 if (mddev->gendisk)
5476 set_disk_ro(mddev->gendisk, 1);
5479 if (rdev->sb_page)
5480 mddev->has_superblocks = true;
5482 /* perform some consistency tests on the device.
5483 * We don't want the data to overlap the metadata,
5484 * Internal Bitmap issues have been handled elsewhere.
5486 if (rdev->meta_bdev) {
5487 /* Nothing to check */;
5488 } else if (rdev->data_offset < rdev->sb_start) {
5489 if (mddev->dev_sectors &&
5490 rdev->data_offset + mddev->dev_sectors
5491 > rdev->sb_start) {
5492 pr_warn("md: %s: data overlaps metadata\n",
5493 mdname(mddev));
5494 return -EINVAL;
5496 } else {
5497 if (rdev->sb_start + rdev->sb_size/512
5498 > rdev->data_offset) {
5499 pr_warn("md: %s: metadata overlaps data\n",
5500 mdname(mddev));
5501 return -EINVAL;
5504 sysfs_notify_dirent_safe(rdev->sysfs_state);
5507 if (mddev->bio_set == NULL) {
5508 mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5509 if (!mddev->bio_set)
5510 return -ENOMEM;
5512 if (mddev->sync_set == NULL) {
5513 mddev->sync_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5514 if (!mddev->sync_set) {
5515 err = -ENOMEM;
5516 goto abort;
5520 spin_lock(&pers_lock);
5521 pers = find_pers(mddev->level, mddev->clevel);
5522 if (!pers || !try_module_get(pers->owner)) {
5523 spin_unlock(&pers_lock);
5524 if (mddev->level != LEVEL_NONE)
5525 pr_warn("md: personality for level %d is not loaded!\n",
5526 mddev->level);
5527 else
5528 pr_warn("md: personality for level %s is not loaded!\n",
5529 mddev->clevel);
5530 err = -EINVAL;
5531 goto abort;
5533 spin_unlock(&pers_lock);
5534 if (mddev->level != pers->level) {
5535 mddev->level = pers->level;
5536 mddev->new_level = pers->level;
5538 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5540 if (mddev->reshape_position != MaxSector &&
5541 pers->start_reshape == NULL) {
5542 /* This personality cannot handle reshaping... */
5543 module_put(pers->owner);
5544 err = -EINVAL;
5545 goto abort;
5548 if (pers->sync_request) {
5549 /* Warn if this is a potentially silly
5550 * configuration.
5552 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5553 struct md_rdev *rdev2;
5554 int warned = 0;
5556 rdev_for_each(rdev, mddev)
5557 rdev_for_each(rdev2, mddev) {
5558 if (rdev < rdev2 &&
5559 rdev->bdev->bd_contains ==
5560 rdev2->bdev->bd_contains) {
5561 pr_warn("%s: WARNING: %s appears to be on the same physical disk as %s.\n",
5562 mdname(mddev),
5563 bdevname(rdev->bdev,b),
5564 bdevname(rdev2->bdev,b2));
5565 warned = 1;
5569 if (warned)
5570 pr_warn("True protection against single-disk failure might be compromised.\n");
5573 mddev->recovery = 0;
5574 /* may be over-ridden by personality */
5575 mddev->resync_max_sectors = mddev->dev_sectors;
5577 mddev->ok_start_degraded = start_dirty_degraded;
5579 if (start_readonly && mddev->ro == 0)
5580 mddev->ro = 2; /* read-only, but switch on first write */
5583 * NOTE: some pers->run(), for example r5l_recovery_log(), wakes
5584 * up mddev->thread. It is important to initialize critical
5585 * resources for mddev->thread BEFORE calling pers->run().
5587 err = pers->run(mddev);
5588 if (err)
5589 pr_warn("md: pers->run() failed ...\n");
5590 else if (pers->size(mddev, 0, 0) < mddev->array_sectors) {
5591 WARN_ONCE(!mddev->external_size,
5592 "%s: default size too small, but 'external_size' not in effect?\n",
5593 __func__);
5594 pr_warn("md: invalid array_size %llu > default size %llu\n",
5595 (unsigned long long)mddev->array_sectors / 2,
5596 (unsigned long long)pers->size(mddev, 0, 0) / 2);
5597 err = -EINVAL;
5599 if (err == 0 && pers->sync_request &&
5600 (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5601 struct bitmap *bitmap;
5603 bitmap = bitmap_create(mddev, -1);
5604 if (IS_ERR(bitmap)) {
5605 err = PTR_ERR(bitmap);
5606 pr_warn("%s: failed to create bitmap (%d)\n",
5607 mdname(mddev), err);
5608 } else
5609 mddev->bitmap = bitmap;
5612 if (err) {
5613 mddev_detach(mddev);
5614 if (mddev->private)
5615 pers->free(mddev, mddev->private);
5616 mddev->private = NULL;
5617 module_put(pers->owner);
5618 bitmap_destroy(mddev);
5619 goto abort;
5621 if (mddev->queue) {
5622 bool nonrot = true;
5624 rdev_for_each(rdev, mddev) {
5625 if (rdev->raid_disk >= 0 &&
5626 !blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
5627 nonrot = false;
5628 break;
5631 if (mddev->degraded)
5632 nonrot = false;
5633 if (nonrot)
5634 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, mddev->queue);
5635 else
5636 queue_flag_clear_unlocked(QUEUE_FLAG_NONROT, mddev->queue);
5637 mddev->queue->backing_dev_info->congested_data = mddev;
5638 mddev->queue->backing_dev_info->congested_fn = md_congested;
5640 if (pers->sync_request) {
5641 if (mddev->kobj.sd &&
5642 sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5643 pr_warn("md: cannot register extra attributes for %s\n",
5644 mdname(mddev));
5645 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5646 } else if (mddev->ro == 2) /* auto-readonly not meaningful */
5647 mddev->ro = 0;
5649 atomic_set(&mddev->max_corr_read_errors,
5650 MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5651 mddev->safemode = 0;
5652 if (mddev_is_clustered(mddev))
5653 mddev->safemode_delay = 0;
5654 else
5655 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5656 mddev->in_sync = 1;
5657 smp_wmb();
5658 spin_lock(&mddev->lock);
5659 mddev->pers = pers;
5660 spin_unlock(&mddev->lock);
5661 rdev_for_each(rdev, mddev)
5662 if (rdev->raid_disk >= 0)
5663 if (sysfs_link_rdev(mddev, rdev))
5664 /* failure here is OK */;
5666 if (mddev->degraded && !mddev->ro)
5667 /* This ensures that recovering status is reported immediately
5668 * via sysfs - until a lack of spares is confirmed.
5670 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5671 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5673 if (mddev->sb_flags)
5674 md_update_sb(mddev, 0);
5676 md_new_event(mddev);
5677 sysfs_notify_dirent_safe(mddev->sysfs_state);
5678 sysfs_notify_dirent_safe(mddev->sysfs_action);
5679 sysfs_notify(&mddev->kobj, NULL, "degraded");
5680 return 0;
5682 abort:
5683 if (mddev->bio_set) {
5684 bioset_free(mddev->bio_set);
5685 mddev->bio_set = NULL;
5687 if (mddev->sync_set) {
5688 bioset_free(mddev->sync_set);
5689 mddev->sync_set = NULL;
5692 return err;
5694 EXPORT_SYMBOL_GPL(md_run);
5696 static int do_md_run(struct mddev *mddev)
5698 int err;
5700 err = md_run(mddev);
5701 if (err)
5702 goto out;
5703 err = bitmap_load(mddev);
5704 if (err) {
5705 bitmap_destroy(mddev);
5706 goto out;
5709 if (mddev_is_clustered(mddev))
5710 md_allow_write(mddev);
5712 md_wakeup_thread(mddev->thread);
5713 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5715 set_capacity(mddev->gendisk, mddev->array_sectors);
5716 revalidate_disk(mddev->gendisk);
5717 mddev->changed = 1;
5718 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5719 out:
5720 return err;
5723 static int restart_array(struct mddev *mddev)
5725 struct gendisk *disk = mddev->gendisk;
5726 struct md_rdev *rdev;
5727 bool has_journal = false;
5728 bool has_readonly = false;
5730 /* Complain if it has no devices */
5731 if (list_empty(&mddev->disks))
5732 return -ENXIO;
5733 if (!mddev->pers)
5734 return -EINVAL;
5735 if (!mddev->ro)
5736 return -EBUSY;
5738 rcu_read_lock();
5739 rdev_for_each_rcu(rdev, mddev) {
5740 if (test_bit(Journal, &rdev->flags) &&
5741 !test_bit(Faulty, &rdev->flags))
5742 has_journal = true;
5743 if (bdev_read_only(rdev->bdev))
5744 has_readonly = true;
5746 rcu_read_unlock();
5747 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !has_journal)
5748 /* Don't restart rw with journal missing/faulty */
5749 return -EINVAL;
5750 if (has_readonly)
5751 return -EROFS;
5753 mddev->safemode = 0;
5754 mddev->ro = 0;
5755 set_disk_ro(disk, 0);
5756 pr_debug("md: %s switched to read-write mode.\n", mdname(mddev));
5757 /* Kick recovery or resync if necessary */
5758 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5759 md_wakeup_thread(mddev->thread);
5760 md_wakeup_thread(mddev->sync_thread);
5761 sysfs_notify_dirent_safe(mddev->sysfs_state);
5762 return 0;
5765 static void md_clean(struct mddev *mddev)
5767 mddev->array_sectors = 0;
5768 mddev->external_size = 0;
5769 mddev->dev_sectors = 0;
5770 mddev->raid_disks = 0;
5771 mddev->recovery_cp = 0;
5772 mddev->resync_min = 0;
5773 mddev->resync_max = MaxSector;
5774 mddev->reshape_position = MaxSector;
5775 mddev->external = 0;
5776 mddev->persistent = 0;
5777 mddev->level = LEVEL_NONE;
5778 mddev->clevel[0] = 0;
5779 mddev->flags = 0;
5780 mddev->sb_flags = 0;
5781 mddev->ro = 0;
5782 mddev->metadata_type[0] = 0;
5783 mddev->chunk_sectors = 0;
5784 mddev->ctime = mddev->utime = 0;
5785 mddev->layout = 0;
5786 mddev->max_disks = 0;
5787 mddev->events = 0;
5788 mddev->can_decrease_events = 0;
5789 mddev->delta_disks = 0;
5790 mddev->reshape_backwards = 0;
5791 mddev->new_level = LEVEL_NONE;
5792 mddev->new_layout = 0;
5793 mddev->new_chunk_sectors = 0;
5794 mddev->curr_resync = 0;
5795 atomic64_set(&mddev->resync_mismatches, 0);
5796 mddev->suspend_lo = mddev->suspend_hi = 0;
5797 mddev->sync_speed_min = mddev->sync_speed_max = 0;
5798 mddev->recovery = 0;
5799 mddev->in_sync = 0;
5800 mddev->changed = 0;
5801 mddev->degraded = 0;
5802 mddev->safemode = 0;
5803 mddev->private = NULL;
5804 mddev->cluster_info = NULL;
5805 mddev->bitmap_info.offset = 0;
5806 mddev->bitmap_info.default_offset = 0;
5807 mddev->bitmap_info.default_space = 0;
5808 mddev->bitmap_info.chunksize = 0;
5809 mddev->bitmap_info.daemon_sleep = 0;
5810 mddev->bitmap_info.max_write_behind = 0;
5811 mddev->bitmap_info.nodes = 0;
5814 static void __md_stop_writes(struct mddev *mddev)
5816 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5817 flush_workqueue(md_misc_wq);
5818 if (mddev->sync_thread) {
5819 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5820 md_reap_sync_thread(mddev);
5823 del_timer_sync(&mddev->safemode_timer);
5825 if (mddev->pers && mddev->pers->quiesce) {
5826 mddev->pers->quiesce(mddev, 1);
5827 mddev->pers->quiesce(mddev, 0);
5829 bitmap_flush(mddev);
5831 if (mddev->ro == 0 &&
5832 ((!mddev->in_sync && !mddev_is_clustered(mddev)) ||
5833 mddev->sb_flags)) {
5834 /* mark array as shutdown cleanly */
5835 if (!mddev_is_clustered(mddev))
5836 mddev->in_sync = 1;
5837 md_update_sb(mddev, 1);
5841 void md_stop_writes(struct mddev *mddev)
5843 mddev_lock_nointr(mddev);
5844 __md_stop_writes(mddev);
5845 mddev_unlock(mddev);
5847 EXPORT_SYMBOL_GPL(md_stop_writes);
5849 static void mddev_detach(struct mddev *mddev)
5851 bitmap_wait_behind_writes(mddev);
5852 if (mddev->pers && mddev->pers->quiesce) {
5853 mddev->pers->quiesce(mddev, 1);
5854 mddev->pers->quiesce(mddev, 0);
5856 md_unregister_thread(&mddev->thread);
5857 if (mddev->queue)
5858 blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
5861 static void __md_stop(struct mddev *mddev)
5863 struct md_personality *pers = mddev->pers;
5864 bitmap_destroy(mddev);
5865 mddev_detach(mddev);
5866 /* Ensure ->event_work is done */
5867 flush_workqueue(md_misc_wq);
5868 spin_lock(&mddev->lock);
5869 mddev->pers = NULL;
5870 spin_unlock(&mddev->lock);
5871 pers->free(mddev, mddev->private);
5872 mddev->private = NULL;
5873 if (pers->sync_request && mddev->to_remove == NULL)
5874 mddev->to_remove = &md_redundancy_group;
5875 module_put(pers->owner);
5876 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5879 void md_stop(struct mddev *mddev)
5881 /* stop the array and free an attached data structures.
5882 * This is called from dm-raid
5884 __md_stop(mddev);
5885 if (mddev->bio_set)
5886 bioset_free(mddev->bio_set);
5889 EXPORT_SYMBOL_GPL(md_stop);
5891 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5893 int err = 0;
5894 int did_freeze = 0;
5896 if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5897 did_freeze = 1;
5898 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5899 md_wakeup_thread(mddev->thread);
5901 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5902 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5903 if (mddev->sync_thread)
5904 /* Thread might be blocked waiting for metadata update
5905 * which will now never happen */
5906 wake_up_process(mddev->sync_thread->tsk);
5908 if (mddev->external && test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
5909 return -EBUSY;
5910 mddev_unlock(mddev);
5911 wait_event(resync_wait, !test_bit(MD_RECOVERY_RUNNING,
5912 &mddev->recovery));
5913 wait_event(mddev->sb_wait,
5914 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
5915 mddev_lock_nointr(mddev);
5917 mutex_lock(&mddev->open_mutex);
5918 if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5919 mddev->sync_thread ||
5920 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
5921 pr_warn("md: %s still in use.\n",mdname(mddev));
5922 if (did_freeze) {
5923 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5924 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5925 md_wakeup_thread(mddev->thread);
5927 err = -EBUSY;
5928 goto out;
5930 if (mddev->pers) {
5931 __md_stop_writes(mddev);
5933 err = -ENXIO;
5934 if (mddev->ro==1)
5935 goto out;
5936 mddev->ro = 1;
5937 set_disk_ro(mddev->gendisk, 1);
5938 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5939 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5940 md_wakeup_thread(mddev->thread);
5941 sysfs_notify_dirent_safe(mddev->sysfs_state);
5942 err = 0;
5944 out:
5945 mutex_unlock(&mddev->open_mutex);
5946 return err;
5949 /* mode:
5950 * 0 - completely stop and dis-assemble array
5951 * 2 - stop but do not disassemble array
5953 static int do_md_stop(struct mddev *mddev, int mode,
5954 struct block_device *bdev)
5956 struct gendisk *disk = mddev->gendisk;
5957 struct md_rdev *rdev;
5958 int did_freeze = 0;
5960 if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5961 did_freeze = 1;
5962 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5963 md_wakeup_thread(mddev->thread);
5965 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5966 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5967 if (mddev->sync_thread)
5968 /* Thread might be blocked waiting for metadata update
5969 * which will now never happen */
5970 wake_up_process(mddev->sync_thread->tsk);
5972 mddev_unlock(mddev);
5973 wait_event(resync_wait, (mddev->sync_thread == NULL &&
5974 !test_bit(MD_RECOVERY_RUNNING,
5975 &mddev->recovery)));
5976 mddev_lock_nointr(mddev);
5978 mutex_lock(&mddev->open_mutex);
5979 if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5980 mddev->sysfs_active ||
5981 mddev->sync_thread ||
5982 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
5983 pr_warn("md: %s still in use.\n",mdname(mddev));
5984 mutex_unlock(&mddev->open_mutex);
5985 if (did_freeze) {
5986 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5987 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5988 md_wakeup_thread(mddev->thread);
5990 return -EBUSY;
5992 if (mddev->pers) {
5993 if (mddev->ro)
5994 set_disk_ro(disk, 0);
5996 __md_stop_writes(mddev);
5997 __md_stop(mddev);
5998 mddev->queue->backing_dev_info->congested_fn = NULL;
6000 /* tell userspace to handle 'inactive' */
6001 sysfs_notify_dirent_safe(mddev->sysfs_state);
6003 rdev_for_each(rdev, mddev)
6004 if (rdev->raid_disk >= 0)
6005 sysfs_unlink_rdev(mddev, rdev);
6007 set_capacity(disk, 0);
6008 mutex_unlock(&mddev->open_mutex);
6009 mddev->changed = 1;
6010 revalidate_disk(disk);
6012 if (mddev->ro)
6013 mddev->ro = 0;
6014 } else
6015 mutex_unlock(&mddev->open_mutex);
6017 * Free resources if final stop
6019 if (mode == 0) {
6020 pr_info("md: %s stopped.\n", mdname(mddev));
6022 if (mddev->bitmap_info.file) {
6023 struct file *f = mddev->bitmap_info.file;
6024 spin_lock(&mddev->lock);
6025 mddev->bitmap_info.file = NULL;
6026 spin_unlock(&mddev->lock);
6027 fput(f);
6029 mddev->bitmap_info.offset = 0;
6031 export_array(mddev);
6033 md_clean(mddev);
6034 if (mddev->hold_active == UNTIL_STOP)
6035 mddev->hold_active = 0;
6037 md_new_event(mddev);
6038 sysfs_notify_dirent_safe(mddev->sysfs_state);
6039 return 0;
6042 #ifndef MODULE
6043 static void autorun_array(struct mddev *mddev)
6045 struct md_rdev *rdev;
6046 int err;
6048 if (list_empty(&mddev->disks))
6049 return;
6051 pr_info("md: running: ");
6053 rdev_for_each(rdev, mddev) {
6054 char b[BDEVNAME_SIZE];
6055 pr_cont("<%s>", bdevname(rdev->bdev,b));
6057 pr_cont("\n");
6059 err = do_md_run(mddev);
6060 if (err) {
6061 pr_warn("md: do_md_run() returned %d\n", err);
6062 do_md_stop(mddev, 0, NULL);
6067 * lets try to run arrays based on all disks that have arrived
6068 * until now. (those are in pending_raid_disks)
6070 * the method: pick the first pending disk, collect all disks with
6071 * the same UUID, remove all from the pending list and put them into
6072 * the 'same_array' list. Then order this list based on superblock
6073 * update time (freshest comes first), kick out 'old' disks and
6074 * compare superblocks. If everything's fine then run it.
6076 * If "unit" is allocated, then bump its reference count
6078 static void autorun_devices(int part)
6080 struct md_rdev *rdev0, *rdev, *tmp;
6081 struct mddev *mddev;
6082 char b[BDEVNAME_SIZE];
6084 pr_info("md: autorun ...\n");
6085 while (!list_empty(&pending_raid_disks)) {
6086 int unit;
6087 dev_t dev;
6088 LIST_HEAD(candidates);
6089 rdev0 = list_entry(pending_raid_disks.next,
6090 struct md_rdev, same_set);
6092 pr_debug("md: considering %s ...\n", bdevname(rdev0->bdev,b));
6093 INIT_LIST_HEAD(&candidates);
6094 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
6095 if (super_90_load(rdev, rdev0, 0) >= 0) {
6096 pr_debug("md: adding %s ...\n",
6097 bdevname(rdev->bdev,b));
6098 list_move(&rdev->same_set, &candidates);
6101 * now we have a set of devices, with all of them having
6102 * mostly sane superblocks. It's time to allocate the
6103 * mddev.
6105 if (part) {
6106 dev = MKDEV(mdp_major,
6107 rdev0->preferred_minor << MdpMinorShift);
6108 unit = MINOR(dev) >> MdpMinorShift;
6109 } else {
6110 dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
6111 unit = MINOR(dev);
6113 if (rdev0->preferred_minor != unit) {
6114 pr_warn("md: unit number in %s is bad: %d\n",
6115 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
6116 break;
6119 md_probe(dev, NULL, NULL);
6120 mddev = mddev_find(dev);
6121 if (!mddev || !mddev->gendisk) {
6122 if (mddev)
6123 mddev_put(mddev);
6124 break;
6126 if (mddev_lock(mddev))
6127 pr_warn("md: %s locked, cannot run\n", mdname(mddev));
6128 else if (mddev->raid_disks || mddev->major_version
6129 || !list_empty(&mddev->disks)) {
6130 pr_warn("md: %s already running, cannot run %s\n",
6131 mdname(mddev), bdevname(rdev0->bdev,b));
6132 mddev_unlock(mddev);
6133 } else {
6134 pr_debug("md: created %s\n", mdname(mddev));
6135 mddev->persistent = 1;
6136 rdev_for_each_list(rdev, tmp, &candidates) {
6137 list_del_init(&rdev->same_set);
6138 if (bind_rdev_to_array(rdev, mddev))
6139 export_rdev(rdev);
6141 autorun_array(mddev);
6142 mddev_unlock(mddev);
6144 /* on success, candidates will be empty, on error
6145 * it won't...
6147 rdev_for_each_list(rdev, tmp, &candidates) {
6148 list_del_init(&rdev->same_set);
6149 export_rdev(rdev);
6151 mddev_put(mddev);
6153 pr_info("md: ... autorun DONE.\n");
6155 #endif /* !MODULE */
6157 static int get_version(void __user *arg)
6159 mdu_version_t ver;
6161 ver.major = MD_MAJOR_VERSION;
6162 ver.minor = MD_MINOR_VERSION;
6163 ver.patchlevel = MD_PATCHLEVEL_VERSION;
6165 if (copy_to_user(arg, &ver, sizeof(ver)))
6166 return -EFAULT;
6168 return 0;
6171 static int get_array_info(struct mddev *mddev, void __user *arg)
6173 mdu_array_info_t info;
6174 int nr,working,insync,failed,spare;
6175 struct md_rdev *rdev;
6177 nr = working = insync = failed = spare = 0;
6178 rcu_read_lock();
6179 rdev_for_each_rcu(rdev, mddev) {
6180 nr++;
6181 if (test_bit(Faulty, &rdev->flags))
6182 failed++;
6183 else {
6184 working++;
6185 if (test_bit(In_sync, &rdev->flags))
6186 insync++;
6187 else if (test_bit(Journal, &rdev->flags))
6188 /* TODO: add journal count to md_u.h */
6190 else
6191 spare++;
6194 rcu_read_unlock();
6196 info.major_version = mddev->major_version;
6197 info.minor_version = mddev->minor_version;
6198 info.patch_version = MD_PATCHLEVEL_VERSION;
6199 info.ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
6200 info.level = mddev->level;
6201 info.size = mddev->dev_sectors / 2;
6202 if (info.size != mddev->dev_sectors / 2) /* overflow */
6203 info.size = -1;
6204 info.nr_disks = nr;
6205 info.raid_disks = mddev->raid_disks;
6206 info.md_minor = mddev->md_minor;
6207 info.not_persistent= !mddev->persistent;
6209 info.utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
6210 info.state = 0;
6211 if (mddev->in_sync)
6212 info.state = (1<<MD_SB_CLEAN);
6213 if (mddev->bitmap && mddev->bitmap_info.offset)
6214 info.state |= (1<<MD_SB_BITMAP_PRESENT);
6215 if (mddev_is_clustered(mddev))
6216 info.state |= (1<<MD_SB_CLUSTERED);
6217 info.active_disks = insync;
6218 info.working_disks = working;
6219 info.failed_disks = failed;
6220 info.spare_disks = spare;
6222 info.layout = mddev->layout;
6223 info.chunk_size = mddev->chunk_sectors << 9;
6225 if (copy_to_user(arg, &info, sizeof(info)))
6226 return -EFAULT;
6228 return 0;
6231 static int get_bitmap_file(struct mddev *mddev, void __user * arg)
6233 mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
6234 char *ptr;
6235 int err;
6237 file = kzalloc(sizeof(*file), GFP_NOIO);
6238 if (!file)
6239 return -ENOMEM;
6241 err = 0;
6242 spin_lock(&mddev->lock);
6243 /* bitmap enabled */
6244 if (mddev->bitmap_info.file) {
6245 ptr = file_path(mddev->bitmap_info.file, file->pathname,
6246 sizeof(file->pathname));
6247 if (IS_ERR(ptr))
6248 err = PTR_ERR(ptr);
6249 else
6250 memmove(file->pathname, ptr,
6251 sizeof(file->pathname)-(ptr-file->pathname));
6253 spin_unlock(&mddev->lock);
6255 if (err == 0 &&
6256 copy_to_user(arg, file, sizeof(*file)))
6257 err = -EFAULT;
6259 kfree(file);
6260 return err;
6263 static int get_disk_info(struct mddev *mddev, void __user * arg)
6265 mdu_disk_info_t info;
6266 struct md_rdev *rdev;
6268 if (copy_from_user(&info, arg, sizeof(info)))
6269 return -EFAULT;
6271 rcu_read_lock();
6272 rdev = md_find_rdev_nr_rcu(mddev, info.number);
6273 if (rdev) {
6274 info.major = MAJOR(rdev->bdev->bd_dev);
6275 info.minor = MINOR(rdev->bdev->bd_dev);
6276 info.raid_disk = rdev->raid_disk;
6277 info.state = 0;
6278 if (test_bit(Faulty, &rdev->flags))
6279 info.state |= (1<<MD_DISK_FAULTY);
6280 else if (test_bit(In_sync, &rdev->flags)) {
6281 info.state |= (1<<MD_DISK_ACTIVE);
6282 info.state |= (1<<MD_DISK_SYNC);
6284 if (test_bit(Journal, &rdev->flags))
6285 info.state |= (1<<MD_DISK_JOURNAL);
6286 if (test_bit(WriteMostly, &rdev->flags))
6287 info.state |= (1<<MD_DISK_WRITEMOSTLY);
6288 if (test_bit(FailFast, &rdev->flags))
6289 info.state |= (1<<MD_DISK_FAILFAST);
6290 } else {
6291 info.major = info.minor = 0;
6292 info.raid_disk = -1;
6293 info.state = (1<<MD_DISK_REMOVED);
6295 rcu_read_unlock();
6297 if (copy_to_user(arg, &info, sizeof(info)))
6298 return -EFAULT;
6300 return 0;
6303 static int add_new_disk(struct mddev *mddev, mdu_disk_info_t *info)
6305 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
6306 struct md_rdev *rdev;
6307 dev_t dev = MKDEV(info->major,info->minor);
6309 if (mddev_is_clustered(mddev) &&
6310 !(info->state & ((1 << MD_DISK_CLUSTER_ADD) | (1 << MD_DISK_CANDIDATE)))) {
6311 pr_warn("%s: Cannot add to clustered mddev.\n",
6312 mdname(mddev));
6313 return -EINVAL;
6316 if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
6317 return -EOVERFLOW;
6319 if (!mddev->raid_disks) {
6320 int err;
6321 /* expecting a device which has a superblock */
6322 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
6323 if (IS_ERR(rdev)) {
6324 pr_warn("md: md_import_device returned %ld\n",
6325 PTR_ERR(rdev));
6326 return PTR_ERR(rdev);
6328 if (!list_empty(&mddev->disks)) {
6329 struct md_rdev *rdev0
6330 = list_entry(mddev->disks.next,
6331 struct md_rdev, same_set);
6332 err = super_types[mddev->major_version]
6333 .load_super(rdev, rdev0, mddev->minor_version);
6334 if (err < 0) {
6335 pr_warn("md: %s has different UUID to %s\n",
6336 bdevname(rdev->bdev,b),
6337 bdevname(rdev0->bdev,b2));
6338 export_rdev(rdev);
6339 return -EINVAL;
6342 err = bind_rdev_to_array(rdev, mddev);
6343 if (err)
6344 export_rdev(rdev);
6345 return err;
6349 * add_new_disk can be used once the array is assembled
6350 * to add "hot spares". They must already have a superblock
6351 * written
6353 if (mddev->pers) {
6354 int err;
6355 if (!mddev->pers->hot_add_disk) {
6356 pr_warn("%s: personality does not support diskops!\n",
6357 mdname(mddev));
6358 return -EINVAL;
6360 if (mddev->persistent)
6361 rdev = md_import_device(dev, mddev->major_version,
6362 mddev->minor_version);
6363 else
6364 rdev = md_import_device(dev, -1, -1);
6365 if (IS_ERR(rdev)) {
6366 pr_warn("md: md_import_device returned %ld\n",
6367 PTR_ERR(rdev));
6368 return PTR_ERR(rdev);
6370 /* set saved_raid_disk if appropriate */
6371 if (!mddev->persistent) {
6372 if (info->state & (1<<MD_DISK_SYNC) &&
6373 info->raid_disk < mddev->raid_disks) {
6374 rdev->raid_disk = info->raid_disk;
6375 set_bit(In_sync, &rdev->flags);
6376 clear_bit(Bitmap_sync, &rdev->flags);
6377 } else
6378 rdev->raid_disk = -1;
6379 rdev->saved_raid_disk = rdev->raid_disk;
6380 } else
6381 super_types[mddev->major_version].
6382 validate_super(mddev, rdev);
6383 if ((info->state & (1<<MD_DISK_SYNC)) &&
6384 rdev->raid_disk != info->raid_disk) {
6385 /* This was a hot-add request, but events doesn't
6386 * match, so reject it.
6388 export_rdev(rdev);
6389 return -EINVAL;
6392 clear_bit(In_sync, &rdev->flags); /* just to be sure */
6393 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6394 set_bit(WriteMostly, &rdev->flags);
6395 else
6396 clear_bit(WriteMostly, &rdev->flags);
6397 if (info->state & (1<<MD_DISK_FAILFAST))
6398 set_bit(FailFast, &rdev->flags);
6399 else
6400 clear_bit(FailFast, &rdev->flags);
6402 if (info->state & (1<<MD_DISK_JOURNAL)) {
6403 struct md_rdev *rdev2;
6404 bool has_journal = false;
6406 /* make sure no existing journal disk */
6407 rdev_for_each(rdev2, mddev) {
6408 if (test_bit(Journal, &rdev2->flags)) {
6409 has_journal = true;
6410 break;
6413 if (has_journal || mddev->bitmap) {
6414 export_rdev(rdev);
6415 return -EBUSY;
6417 set_bit(Journal, &rdev->flags);
6420 * check whether the device shows up in other nodes
6422 if (mddev_is_clustered(mddev)) {
6423 if (info->state & (1 << MD_DISK_CANDIDATE))
6424 set_bit(Candidate, &rdev->flags);
6425 else if (info->state & (1 << MD_DISK_CLUSTER_ADD)) {
6426 /* --add initiated by this node */
6427 err = md_cluster_ops->add_new_disk(mddev, rdev);
6428 if (err) {
6429 export_rdev(rdev);
6430 return err;
6435 rdev->raid_disk = -1;
6436 err = bind_rdev_to_array(rdev, mddev);
6438 if (err)
6439 export_rdev(rdev);
6441 if (mddev_is_clustered(mddev)) {
6442 if (info->state & (1 << MD_DISK_CANDIDATE)) {
6443 if (!err) {
6444 err = md_cluster_ops->new_disk_ack(mddev,
6445 err == 0);
6446 if (err)
6447 md_kick_rdev_from_array(rdev);
6449 } else {
6450 if (err)
6451 md_cluster_ops->add_new_disk_cancel(mddev);
6452 else
6453 err = add_bound_rdev(rdev);
6456 } else if (!err)
6457 err = add_bound_rdev(rdev);
6459 return err;
6462 /* otherwise, add_new_disk is only allowed
6463 * for major_version==0 superblocks
6465 if (mddev->major_version != 0) {
6466 pr_warn("%s: ADD_NEW_DISK not supported\n", mdname(mddev));
6467 return -EINVAL;
6470 if (!(info->state & (1<<MD_DISK_FAULTY))) {
6471 int err;
6472 rdev = md_import_device(dev, -1, 0);
6473 if (IS_ERR(rdev)) {
6474 pr_warn("md: error, md_import_device() returned %ld\n",
6475 PTR_ERR(rdev));
6476 return PTR_ERR(rdev);
6478 rdev->desc_nr = info->number;
6479 if (info->raid_disk < mddev->raid_disks)
6480 rdev->raid_disk = info->raid_disk;
6481 else
6482 rdev->raid_disk = -1;
6484 if (rdev->raid_disk < mddev->raid_disks)
6485 if (info->state & (1<<MD_DISK_SYNC))
6486 set_bit(In_sync, &rdev->flags);
6488 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6489 set_bit(WriteMostly, &rdev->flags);
6490 if (info->state & (1<<MD_DISK_FAILFAST))
6491 set_bit(FailFast, &rdev->flags);
6493 if (!mddev->persistent) {
6494 pr_debug("md: nonpersistent superblock ...\n");
6495 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6496 } else
6497 rdev->sb_start = calc_dev_sboffset(rdev);
6498 rdev->sectors = rdev->sb_start;
6500 err = bind_rdev_to_array(rdev, mddev);
6501 if (err) {
6502 export_rdev(rdev);
6503 return err;
6507 return 0;
6510 static int hot_remove_disk(struct mddev *mddev, dev_t dev)
6512 char b[BDEVNAME_SIZE];
6513 struct md_rdev *rdev;
6515 rdev = find_rdev(mddev, dev);
6516 if (!rdev)
6517 return -ENXIO;
6519 if (rdev->raid_disk < 0)
6520 goto kick_rdev;
6522 clear_bit(Blocked, &rdev->flags);
6523 remove_and_add_spares(mddev, rdev);
6525 if (rdev->raid_disk >= 0)
6526 goto busy;
6528 kick_rdev:
6529 if (mddev_is_clustered(mddev))
6530 md_cluster_ops->remove_disk(mddev, rdev);
6532 md_kick_rdev_from_array(rdev);
6533 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6534 if (mddev->thread)
6535 md_wakeup_thread(mddev->thread);
6536 else
6537 md_update_sb(mddev, 1);
6538 md_new_event(mddev);
6540 return 0;
6541 busy:
6542 pr_debug("md: cannot remove active disk %s from %s ...\n",
6543 bdevname(rdev->bdev,b), mdname(mddev));
6544 return -EBUSY;
6547 static int hot_add_disk(struct mddev *mddev, dev_t dev)
6549 char b[BDEVNAME_SIZE];
6550 int err;
6551 struct md_rdev *rdev;
6553 if (!mddev->pers)
6554 return -ENODEV;
6556 if (mddev->major_version != 0) {
6557 pr_warn("%s: HOT_ADD may only be used with version-0 superblocks.\n",
6558 mdname(mddev));
6559 return -EINVAL;
6561 if (!mddev->pers->hot_add_disk) {
6562 pr_warn("%s: personality does not support diskops!\n",
6563 mdname(mddev));
6564 return -EINVAL;
6567 rdev = md_import_device(dev, -1, 0);
6568 if (IS_ERR(rdev)) {
6569 pr_warn("md: error, md_import_device() returned %ld\n",
6570 PTR_ERR(rdev));
6571 return -EINVAL;
6574 if (mddev->persistent)
6575 rdev->sb_start = calc_dev_sboffset(rdev);
6576 else
6577 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6579 rdev->sectors = rdev->sb_start;
6581 if (test_bit(Faulty, &rdev->flags)) {
6582 pr_warn("md: can not hot-add faulty %s disk to %s!\n",
6583 bdevname(rdev->bdev,b), mdname(mddev));
6584 err = -EINVAL;
6585 goto abort_export;
6588 clear_bit(In_sync, &rdev->flags);
6589 rdev->desc_nr = -1;
6590 rdev->saved_raid_disk = -1;
6591 err = bind_rdev_to_array(rdev, mddev);
6592 if (err)
6593 goto abort_export;
6596 * The rest should better be atomic, we can have disk failures
6597 * noticed in interrupt contexts ...
6600 rdev->raid_disk = -1;
6602 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6603 if (!mddev->thread)
6604 md_update_sb(mddev, 1);
6606 * Kick recovery, maybe this spare has to be added to the
6607 * array immediately.
6609 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6610 md_wakeup_thread(mddev->thread);
6611 md_new_event(mddev);
6612 return 0;
6614 abort_export:
6615 export_rdev(rdev);
6616 return err;
6619 static int set_bitmap_file(struct mddev *mddev, int fd)
6621 int err = 0;
6623 if (mddev->pers) {
6624 if (!mddev->pers->quiesce || !mddev->thread)
6625 return -EBUSY;
6626 if (mddev->recovery || mddev->sync_thread)
6627 return -EBUSY;
6628 /* we should be able to change the bitmap.. */
6631 if (fd >= 0) {
6632 struct inode *inode;
6633 struct file *f;
6635 if (mddev->bitmap || mddev->bitmap_info.file)
6636 return -EEXIST; /* cannot add when bitmap is present */
6637 f = fget(fd);
6639 if (f == NULL) {
6640 pr_warn("%s: error: failed to get bitmap file\n",
6641 mdname(mddev));
6642 return -EBADF;
6645 inode = f->f_mapping->host;
6646 if (!S_ISREG(inode->i_mode)) {
6647 pr_warn("%s: error: bitmap file must be a regular file\n",
6648 mdname(mddev));
6649 err = -EBADF;
6650 } else if (!(f->f_mode & FMODE_WRITE)) {
6651 pr_warn("%s: error: bitmap file must open for write\n",
6652 mdname(mddev));
6653 err = -EBADF;
6654 } else if (atomic_read(&inode->i_writecount) != 1) {
6655 pr_warn("%s: error: bitmap file is already in use\n",
6656 mdname(mddev));
6657 err = -EBUSY;
6659 if (err) {
6660 fput(f);
6661 return err;
6663 mddev->bitmap_info.file = f;
6664 mddev->bitmap_info.offset = 0; /* file overrides offset */
6665 } else if (mddev->bitmap == NULL)
6666 return -ENOENT; /* cannot remove what isn't there */
6667 err = 0;
6668 if (mddev->pers) {
6669 if (fd >= 0) {
6670 struct bitmap *bitmap;
6672 bitmap = bitmap_create(mddev, -1);
6673 mddev_suspend(mddev);
6674 if (!IS_ERR(bitmap)) {
6675 mddev->bitmap = bitmap;
6676 err = bitmap_load(mddev);
6677 } else
6678 err = PTR_ERR(bitmap);
6679 if (err) {
6680 bitmap_destroy(mddev);
6681 fd = -1;
6683 mddev_resume(mddev);
6684 } else if (fd < 0) {
6685 mddev_suspend(mddev);
6686 bitmap_destroy(mddev);
6687 mddev_resume(mddev);
6690 if (fd < 0) {
6691 struct file *f = mddev->bitmap_info.file;
6692 if (f) {
6693 spin_lock(&mddev->lock);
6694 mddev->bitmap_info.file = NULL;
6695 spin_unlock(&mddev->lock);
6696 fput(f);
6700 return err;
6704 * set_array_info is used two different ways
6705 * The original usage is when creating a new array.
6706 * In this usage, raid_disks is > 0 and it together with
6707 * level, size, not_persistent,layout,chunksize determine the
6708 * shape of the array.
6709 * This will always create an array with a type-0.90.0 superblock.
6710 * The newer usage is when assembling an array.
6711 * In this case raid_disks will be 0, and the major_version field is
6712 * use to determine which style super-blocks are to be found on the devices.
6713 * The minor and patch _version numbers are also kept incase the
6714 * super_block handler wishes to interpret them.
6716 static int set_array_info(struct mddev *mddev, mdu_array_info_t *info)
6719 if (info->raid_disks == 0) {
6720 /* just setting version number for superblock loading */
6721 if (info->major_version < 0 ||
6722 info->major_version >= ARRAY_SIZE(super_types) ||
6723 super_types[info->major_version].name == NULL) {
6724 /* maybe try to auto-load a module? */
6725 pr_warn("md: superblock version %d not known\n",
6726 info->major_version);
6727 return -EINVAL;
6729 mddev->major_version = info->major_version;
6730 mddev->minor_version = info->minor_version;
6731 mddev->patch_version = info->patch_version;
6732 mddev->persistent = !info->not_persistent;
6733 /* ensure mddev_put doesn't delete this now that there
6734 * is some minimal configuration.
6736 mddev->ctime = ktime_get_real_seconds();
6737 return 0;
6739 mddev->major_version = MD_MAJOR_VERSION;
6740 mddev->minor_version = MD_MINOR_VERSION;
6741 mddev->patch_version = MD_PATCHLEVEL_VERSION;
6742 mddev->ctime = ktime_get_real_seconds();
6744 mddev->level = info->level;
6745 mddev->clevel[0] = 0;
6746 mddev->dev_sectors = 2 * (sector_t)info->size;
6747 mddev->raid_disks = info->raid_disks;
6748 /* don't set md_minor, it is determined by which /dev/md* was
6749 * openned
6751 if (info->state & (1<<MD_SB_CLEAN))
6752 mddev->recovery_cp = MaxSector;
6753 else
6754 mddev->recovery_cp = 0;
6755 mddev->persistent = ! info->not_persistent;
6756 mddev->external = 0;
6758 mddev->layout = info->layout;
6759 mddev->chunk_sectors = info->chunk_size >> 9;
6761 if (mddev->persistent) {
6762 mddev->max_disks = MD_SB_DISKS;
6763 mddev->flags = 0;
6764 mddev->sb_flags = 0;
6766 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6768 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6769 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6770 mddev->bitmap_info.offset = 0;
6772 mddev->reshape_position = MaxSector;
6775 * Generate a 128 bit UUID
6777 get_random_bytes(mddev->uuid, 16);
6779 mddev->new_level = mddev->level;
6780 mddev->new_chunk_sectors = mddev->chunk_sectors;
6781 mddev->new_layout = mddev->layout;
6782 mddev->delta_disks = 0;
6783 mddev->reshape_backwards = 0;
6785 return 0;
6788 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6790 WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
6792 if (mddev->external_size)
6793 return;
6795 mddev->array_sectors = array_sectors;
6797 EXPORT_SYMBOL(md_set_array_sectors);
6799 static int update_size(struct mddev *mddev, sector_t num_sectors)
6801 struct md_rdev *rdev;
6802 int rv;
6803 int fit = (num_sectors == 0);
6804 sector_t old_dev_sectors = mddev->dev_sectors;
6806 if (mddev->pers->resize == NULL)
6807 return -EINVAL;
6808 /* The "num_sectors" is the number of sectors of each device that
6809 * is used. This can only make sense for arrays with redundancy.
6810 * linear and raid0 always use whatever space is available. We can only
6811 * consider changing this number if no resync or reconstruction is
6812 * happening, and if the new size is acceptable. It must fit before the
6813 * sb_start or, if that is <data_offset, it must fit before the size
6814 * of each device. If num_sectors is zero, we find the largest size
6815 * that fits.
6817 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6818 mddev->sync_thread)
6819 return -EBUSY;
6820 if (mddev->ro)
6821 return -EROFS;
6823 rdev_for_each(rdev, mddev) {
6824 sector_t avail = rdev->sectors;
6826 if (fit && (num_sectors == 0 || num_sectors > avail))
6827 num_sectors = avail;
6828 if (avail < num_sectors)
6829 return -ENOSPC;
6831 rv = mddev->pers->resize(mddev, num_sectors);
6832 if (!rv) {
6833 if (mddev_is_clustered(mddev))
6834 md_cluster_ops->update_size(mddev, old_dev_sectors);
6835 else if (mddev->queue) {
6836 set_capacity(mddev->gendisk, mddev->array_sectors);
6837 revalidate_disk(mddev->gendisk);
6840 return rv;
6843 static int update_raid_disks(struct mddev *mddev, int raid_disks)
6845 int rv;
6846 struct md_rdev *rdev;
6847 /* change the number of raid disks */
6848 if (mddev->pers->check_reshape == NULL)
6849 return -EINVAL;
6850 if (mddev->ro)
6851 return -EROFS;
6852 if (raid_disks <= 0 ||
6853 (mddev->max_disks && raid_disks >= mddev->max_disks))
6854 return -EINVAL;
6855 if (mddev->sync_thread ||
6856 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6857 mddev->reshape_position != MaxSector)
6858 return -EBUSY;
6860 rdev_for_each(rdev, mddev) {
6861 if (mddev->raid_disks < raid_disks &&
6862 rdev->data_offset < rdev->new_data_offset)
6863 return -EINVAL;
6864 if (mddev->raid_disks > raid_disks &&
6865 rdev->data_offset > rdev->new_data_offset)
6866 return -EINVAL;
6869 mddev->delta_disks = raid_disks - mddev->raid_disks;
6870 if (mddev->delta_disks < 0)
6871 mddev->reshape_backwards = 1;
6872 else if (mddev->delta_disks > 0)
6873 mddev->reshape_backwards = 0;
6875 rv = mddev->pers->check_reshape(mddev);
6876 if (rv < 0) {
6877 mddev->delta_disks = 0;
6878 mddev->reshape_backwards = 0;
6880 return rv;
6884 * update_array_info is used to change the configuration of an
6885 * on-line array.
6886 * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
6887 * fields in the info are checked against the array.
6888 * Any differences that cannot be handled will cause an error.
6889 * Normally, only one change can be managed at a time.
6891 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
6893 int rv = 0;
6894 int cnt = 0;
6895 int state = 0;
6897 /* calculate expected state,ignoring low bits */
6898 if (mddev->bitmap && mddev->bitmap_info.offset)
6899 state |= (1 << MD_SB_BITMAP_PRESENT);
6901 if (mddev->major_version != info->major_version ||
6902 mddev->minor_version != info->minor_version ||
6903 /* mddev->patch_version != info->patch_version || */
6904 mddev->ctime != info->ctime ||
6905 mddev->level != info->level ||
6906 /* mddev->layout != info->layout || */
6907 mddev->persistent != !info->not_persistent ||
6908 mddev->chunk_sectors != info->chunk_size >> 9 ||
6909 /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6910 ((state^info->state) & 0xfffffe00)
6912 return -EINVAL;
6913 /* Check there is only one change */
6914 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6915 cnt++;
6916 if (mddev->raid_disks != info->raid_disks)
6917 cnt++;
6918 if (mddev->layout != info->layout)
6919 cnt++;
6920 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6921 cnt++;
6922 if (cnt == 0)
6923 return 0;
6924 if (cnt > 1)
6925 return -EINVAL;
6927 if (mddev->layout != info->layout) {
6928 /* Change layout
6929 * we don't need to do anything at the md level, the
6930 * personality will take care of it all.
6932 if (mddev->pers->check_reshape == NULL)
6933 return -EINVAL;
6934 else {
6935 mddev->new_layout = info->layout;
6936 rv = mddev->pers->check_reshape(mddev);
6937 if (rv)
6938 mddev->new_layout = mddev->layout;
6939 return rv;
6942 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6943 rv = update_size(mddev, (sector_t)info->size * 2);
6945 if (mddev->raid_disks != info->raid_disks)
6946 rv = update_raid_disks(mddev, info->raid_disks);
6948 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6949 if (mddev->pers->quiesce == NULL || mddev->thread == NULL) {
6950 rv = -EINVAL;
6951 goto err;
6953 if (mddev->recovery || mddev->sync_thread) {
6954 rv = -EBUSY;
6955 goto err;
6957 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
6958 struct bitmap *bitmap;
6959 /* add the bitmap */
6960 if (mddev->bitmap) {
6961 rv = -EEXIST;
6962 goto err;
6964 if (mddev->bitmap_info.default_offset == 0) {
6965 rv = -EINVAL;
6966 goto err;
6968 mddev->bitmap_info.offset =
6969 mddev->bitmap_info.default_offset;
6970 mddev->bitmap_info.space =
6971 mddev->bitmap_info.default_space;
6972 bitmap = bitmap_create(mddev, -1);
6973 mddev_suspend(mddev);
6974 if (!IS_ERR(bitmap)) {
6975 mddev->bitmap = bitmap;
6976 rv = bitmap_load(mddev);
6977 } else
6978 rv = PTR_ERR(bitmap);
6979 if (rv)
6980 bitmap_destroy(mddev);
6981 mddev_resume(mddev);
6982 } else {
6983 /* remove the bitmap */
6984 if (!mddev->bitmap) {
6985 rv = -ENOENT;
6986 goto err;
6988 if (mddev->bitmap->storage.file) {
6989 rv = -EINVAL;
6990 goto err;
6992 if (mddev->bitmap_info.nodes) {
6993 /* hold PW on all the bitmap lock */
6994 if (md_cluster_ops->lock_all_bitmaps(mddev) <= 0) {
6995 pr_warn("md: can't change bitmap to none since the array is in use by more than one node\n");
6996 rv = -EPERM;
6997 md_cluster_ops->unlock_all_bitmaps(mddev);
6998 goto err;
7001 mddev->bitmap_info.nodes = 0;
7002 md_cluster_ops->leave(mddev);
7004 mddev_suspend(mddev);
7005 bitmap_destroy(mddev);
7006 mddev_resume(mddev);
7007 mddev->bitmap_info.offset = 0;
7010 md_update_sb(mddev, 1);
7011 return rv;
7012 err:
7013 return rv;
7016 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
7018 struct md_rdev *rdev;
7019 int err = 0;
7021 if (mddev->pers == NULL)
7022 return -ENODEV;
7024 rcu_read_lock();
7025 rdev = find_rdev_rcu(mddev, dev);
7026 if (!rdev)
7027 err = -ENODEV;
7028 else {
7029 md_error(mddev, rdev);
7030 if (!test_bit(Faulty, &rdev->flags))
7031 err = -EBUSY;
7033 rcu_read_unlock();
7034 return err;
7038 * We have a problem here : there is no easy way to give a CHS
7039 * virtual geometry. We currently pretend that we have a 2 heads
7040 * 4 sectors (with a BIG number of cylinders...). This drives
7041 * dosfs just mad... ;-)
7043 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
7045 struct mddev *mddev = bdev->bd_disk->private_data;
7047 geo->heads = 2;
7048 geo->sectors = 4;
7049 geo->cylinders = mddev->array_sectors / 8;
7050 return 0;
7053 static inline bool md_ioctl_valid(unsigned int cmd)
7055 switch (cmd) {
7056 case ADD_NEW_DISK:
7057 case BLKROSET:
7058 case GET_ARRAY_INFO:
7059 case GET_BITMAP_FILE:
7060 case GET_DISK_INFO:
7061 case HOT_ADD_DISK:
7062 case HOT_REMOVE_DISK:
7063 case RAID_AUTORUN:
7064 case RAID_VERSION:
7065 case RESTART_ARRAY_RW:
7066 case RUN_ARRAY:
7067 case SET_ARRAY_INFO:
7068 case SET_BITMAP_FILE:
7069 case SET_DISK_FAULTY:
7070 case STOP_ARRAY:
7071 case STOP_ARRAY_RO:
7072 case CLUSTERED_DISK_NACK:
7073 return true;
7074 default:
7075 return false;
7079 static int md_ioctl(struct block_device *bdev, fmode_t mode,
7080 unsigned int cmd, unsigned long arg)
7082 int err = 0;
7083 void __user *argp = (void __user *)arg;
7084 struct mddev *mddev = NULL;
7085 int ro;
7086 bool did_set_md_closing = false;
7088 if (!md_ioctl_valid(cmd))
7089 return -ENOTTY;
7091 switch (cmd) {
7092 case RAID_VERSION:
7093 case GET_ARRAY_INFO:
7094 case GET_DISK_INFO:
7095 break;
7096 default:
7097 if (!capable(CAP_SYS_ADMIN))
7098 return -EACCES;
7102 * Commands dealing with the RAID driver but not any
7103 * particular array:
7105 switch (cmd) {
7106 case RAID_VERSION:
7107 err = get_version(argp);
7108 goto out;
7110 #ifndef MODULE
7111 case RAID_AUTORUN:
7112 err = 0;
7113 autostart_arrays(arg);
7114 goto out;
7115 #endif
7116 default:;
7120 * Commands creating/starting a new array:
7123 mddev = bdev->bd_disk->private_data;
7125 if (!mddev) {
7126 BUG();
7127 goto out;
7130 /* Some actions do not requires the mutex */
7131 switch (cmd) {
7132 case GET_ARRAY_INFO:
7133 if (!mddev->raid_disks && !mddev->external)
7134 err = -ENODEV;
7135 else
7136 err = get_array_info(mddev, argp);
7137 goto out;
7139 case GET_DISK_INFO:
7140 if (!mddev->raid_disks && !mddev->external)
7141 err = -ENODEV;
7142 else
7143 err = get_disk_info(mddev, argp);
7144 goto out;
7146 case SET_DISK_FAULTY:
7147 err = set_disk_faulty(mddev, new_decode_dev(arg));
7148 goto out;
7150 case GET_BITMAP_FILE:
7151 err = get_bitmap_file(mddev, argp);
7152 goto out;
7156 if (cmd == ADD_NEW_DISK)
7157 /* need to ensure md_delayed_delete() has completed */
7158 flush_workqueue(md_misc_wq);
7160 if (cmd == HOT_REMOVE_DISK)
7161 /* need to ensure recovery thread has run */
7162 wait_event_interruptible_timeout(mddev->sb_wait,
7163 !test_bit(MD_RECOVERY_NEEDED,
7164 &mddev->recovery),
7165 msecs_to_jiffies(5000));
7166 if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
7167 /* Need to flush page cache, and ensure no-one else opens
7168 * and writes
7170 mutex_lock(&mddev->open_mutex);
7171 if (mddev->pers && atomic_read(&mddev->openers) > 1) {
7172 mutex_unlock(&mddev->open_mutex);
7173 err = -EBUSY;
7174 goto out;
7176 WARN_ON_ONCE(test_bit(MD_CLOSING, &mddev->flags));
7177 set_bit(MD_CLOSING, &mddev->flags);
7178 did_set_md_closing = true;
7179 mutex_unlock(&mddev->open_mutex);
7180 sync_blockdev(bdev);
7182 err = mddev_lock(mddev);
7183 if (err) {
7184 pr_debug("md: ioctl lock interrupted, reason %d, cmd %d\n",
7185 err, cmd);
7186 goto out;
7189 if (cmd == SET_ARRAY_INFO) {
7190 mdu_array_info_t info;
7191 if (!arg)
7192 memset(&info, 0, sizeof(info));
7193 else if (copy_from_user(&info, argp, sizeof(info))) {
7194 err = -EFAULT;
7195 goto unlock;
7197 if (mddev->pers) {
7198 err = update_array_info(mddev, &info);
7199 if (err) {
7200 pr_warn("md: couldn't update array info. %d\n", err);
7201 goto unlock;
7203 goto unlock;
7205 if (!list_empty(&mddev->disks)) {
7206 pr_warn("md: array %s already has disks!\n", mdname(mddev));
7207 err = -EBUSY;
7208 goto unlock;
7210 if (mddev->raid_disks) {
7211 pr_warn("md: array %s already initialised!\n", mdname(mddev));
7212 err = -EBUSY;
7213 goto unlock;
7215 err = set_array_info(mddev, &info);
7216 if (err) {
7217 pr_warn("md: couldn't set array info. %d\n", err);
7218 goto unlock;
7220 goto unlock;
7224 * Commands querying/configuring an existing array:
7226 /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
7227 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
7228 if ((!mddev->raid_disks && !mddev->external)
7229 && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
7230 && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
7231 && cmd != GET_BITMAP_FILE) {
7232 err = -ENODEV;
7233 goto unlock;
7237 * Commands even a read-only array can execute:
7239 switch (cmd) {
7240 case RESTART_ARRAY_RW:
7241 err = restart_array(mddev);
7242 goto unlock;
7244 case STOP_ARRAY:
7245 err = do_md_stop(mddev, 0, bdev);
7246 goto unlock;
7248 case STOP_ARRAY_RO:
7249 err = md_set_readonly(mddev, bdev);
7250 goto unlock;
7252 case HOT_REMOVE_DISK:
7253 err = hot_remove_disk(mddev, new_decode_dev(arg));
7254 goto unlock;
7256 case ADD_NEW_DISK:
7257 /* We can support ADD_NEW_DISK on read-only arrays
7258 * only if we are re-adding a preexisting device.
7259 * So require mddev->pers and MD_DISK_SYNC.
7261 if (mddev->pers) {
7262 mdu_disk_info_t info;
7263 if (copy_from_user(&info, argp, sizeof(info)))
7264 err = -EFAULT;
7265 else if (!(info.state & (1<<MD_DISK_SYNC)))
7266 /* Need to clear read-only for this */
7267 break;
7268 else
7269 err = add_new_disk(mddev, &info);
7270 goto unlock;
7272 break;
7274 case BLKROSET:
7275 if (get_user(ro, (int __user *)(arg))) {
7276 err = -EFAULT;
7277 goto unlock;
7279 err = -EINVAL;
7281 /* if the bdev is going readonly the value of mddev->ro
7282 * does not matter, no writes are coming
7284 if (ro)
7285 goto unlock;
7287 /* are we are already prepared for writes? */
7288 if (mddev->ro != 1)
7289 goto unlock;
7291 /* transitioning to readauto need only happen for
7292 * arrays that call md_write_start
7294 if (mddev->pers) {
7295 err = restart_array(mddev);
7296 if (err == 0) {
7297 mddev->ro = 2;
7298 set_disk_ro(mddev->gendisk, 0);
7301 goto unlock;
7305 * The remaining ioctls are changing the state of the
7306 * superblock, so we do not allow them on read-only arrays.
7308 if (mddev->ro && mddev->pers) {
7309 if (mddev->ro == 2) {
7310 mddev->ro = 0;
7311 sysfs_notify_dirent_safe(mddev->sysfs_state);
7312 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7313 /* mddev_unlock will wake thread */
7314 /* If a device failed while we were read-only, we
7315 * need to make sure the metadata is updated now.
7317 if (test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)) {
7318 mddev_unlock(mddev);
7319 wait_event(mddev->sb_wait,
7320 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags) &&
7321 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
7322 mddev_lock_nointr(mddev);
7324 } else {
7325 err = -EROFS;
7326 goto unlock;
7330 switch (cmd) {
7331 case ADD_NEW_DISK:
7333 mdu_disk_info_t info;
7334 if (copy_from_user(&info, argp, sizeof(info)))
7335 err = -EFAULT;
7336 else
7337 err = add_new_disk(mddev, &info);
7338 goto unlock;
7341 case CLUSTERED_DISK_NACK:
7342 if (mddev_is_clustered(mddev))
7343 md_cluster_ops->new_disk_ack(mddev, false);
7344 else
7345 err = -EINVAL;
7346 goto unlock;
7348 case HOT_ADD_DISK:
7349 err = hot_add_disk(mddev, new_decode_dev(arg));
7350 goto unlock;
7352 case RUN_ARRAY:
7353 err = do_md_run(mddev);
7354 goto unlock;
7356 case SET_BITMAP_FILE:
7357 err = set_bitmap_file(mddev, (int)arg);
7358 goto unlock;
7360 default:
7361 err = -EINVAL;
7362 goto unlock;
7365 unlock:
7366 if (mddev->hold_active == UNTIL_IOCTL &&
7367 err != -EINVAL)
7368 mddev->hold_active = 0;
7369 mddev_unlock(mddev);
7370 out:
7371 if(did_set_md_closing)
7372 clear_bit(MD_CLOSING, &mddev->flags);
7373 return err;
7375 #ifdef CONFIG_COMPAT
7376 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
7377 unsigned int cmd, unsigned long arg)
7379 switch (cmd) {
7380 case HOT_REMOVE_DISK:
7381 case HOT_ADD_DISK:
7382 case SET_DISK_FAULTY:
7383 case SET_BITMAP_FILE:
7384 /* These take in integer arg, do not convert */
7385 break;
7386 default:
7387 arg = (unsigned long)compat_ptr(arg);
7388 break;
7391 return md_ioctl(bdev, mode, cmd, arg);
7393 #endif /* CONFIG_COMPAT */
7395 static int md_open(struct block_device *bdev, fmode_t mode)
7398 * Succeed if we can lock the mddev, which confirms that
7399 * it isn't being stopped right now.
7401 struct mddev *mddev = mddev_find(bdev->bd_dev);
7402 int err;
7404 if (!mddev)
7405 return -ENODEV;
7407 if (mddev->gendisk != bdev->bd_disk) {
7408 /* we are racing with mddev_put which is discarding this
7409 * bd_disk.
7411 mddev_put(mddev);
7412 /* Wait until bdev->bd_disk is definitely gone */
7413 flush_workqueue(md_misc_wq);
7414 /* Then retry the open from the top */
7415 return -ERESTARTSYS;
7417 BUG_ON(mddev != bdev->bd_disk->private_data);
7419 if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
7420 goto out;
7422 if (test_bit(MD_CLOSING, &mddev->flags)) {
7423 mutex_unlock(&mddev->open_mutex);
7424 err = -ENODEV;
7425 goto out;
7428 err = 0;
7429 atomic_inc(&mddev->openers);
7430 mutex_unlock(&mddev->open_mutex);
7432 check_disk_change(bdev);
7433 out:
7434 if (err)
7435 mddev_put(mddev);
7436 return err;
7439 static void md_release(struct gendisk *disk, fmode_t mode)
7441 struct mddev *mddev = disk->private_data;
7443 BUG_ON(!mddev);
7444 atomic_dec(&mddev->openers);
7445 mddev_put(mddev);
7448 static int md_media_changed(struct gendisk *disk)
7450 struct mddev *mddev = disk->private_data;
7452 return mddev->changed;
7455 static int md_revalidate(struct gendisk *disk)
7457 struct mddev *mddev = disk->private_data;
7459 mddev->changed = 0;
7460 return 0;
7462 static const struct block_device_operations md_fops =
7464 .owner = THIS_MODULE,
7465 .open = md_open,
7466 .release = md_release,
7467 .ioctl = md_ioctl,
7468 #ifdef CONFIG_COMPAT
7469 .compat_ioctl = md_compat_ioctl,
7470 #endif
7471 .getgeo = md_getgeo,
7472 .media_changed = md_media_changed,
7473 .revalidate_disk= md_revalidate,
7476 static int md_thread(void *arg)
7478 struct md_thread *thread = arg;
7481 * md_thread is a 'system-thread', it's priority should be very
7482 * high. We avoid resource deadlocks individually in each
7483 * raid personality. (RAID5 does preallocation) We also use RR and
7484 * the very same RT priority as kswapd, thus we will never get
7485 * into a priority inversion deadlock.
7487 * we definitely have to have equal or higher priority than
7488 * bdflush, otherwise bdflush will deadlock if there are too
7489 * many dirty RAID5 blocks.
7492 allow_signal(SIGKILL);
7493 while (!kthread_should_stop()) {
7495 /* We need to wait INTERRUPTIBLE so that
7496 * we don't add to the load-average.
7497 * That means we need to be sure no signals are
7498 * pending
7500 if (signal_pending(current))
7501 flush_signals(current);
7503 wait_event_interruptible_timeout
7504 (thread->wqueue,
7505 test_bit(THREAD_WAKEUP, &thread->flags)
7506 || kthread_should_stop() || kthread_should_park(),
7507 thread->timeout);
7509 clear_bit(THREAD_WAKEUP, &thread->flags);
7510 if (kthread_should_park())
7511 kthread_parkme();
7512 if (!kthread_should_stop())
7513 thread->run(thread);
7516 return 0;
7519 void md_wakeup_thread(struct md_thread *thread)
7521 if (thread) {
7522 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
7523 set_bit(THREAD_WAKEUP, &thread->flags);
7524 wake_up(&thread->wqueue);
7527 EXPORT_SYMBOL(md_wakeup_thread);
7529 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
7530 struct mddev *mddev, const char *name)
7532 struct md_thread *thread;
7534 thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
7535 if (!thread)
7536 return NULL;
7538 init_waitqueue_head(&thread->wqueue);
7540 thread->run = run;
7541 thread->mddev = mddev;
7542 thread->timeout = MAX_SCHEDULE_TIMEOUT;
7543 thread->tsk = kthread_run(md_thread, thread,
7544 "%s_%s",
7545 mdname(thread->mddev),
7546 name);
7547 if (IS_ERR(thread->tsk)) {
7548 kfree(thread);
7549 return NULL;
7551 return thread;
7553 EXPORT_SYMBOL(md_register_thread);
7555 void md_unregister_thread(struct md_thread **threadp)
7557 struct md_thread *thread = *threadp;
7558 if (!thread)
7559 return;
7560 pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
7561 /* Locking ensures that mddev_unlock does not wake_up a
7562 * non-existent thread
7564 spin_lock(&pers_lock);
7565 *threadp = NULL;
7566 spin_unlock(&pers_lock);
7568 kthread_stop(thread->tsk);
7569 kfree(thread);
7571 EXPORT_SYMBOL(md_unregister_thread);
7573 void md_error(struct mddev *mddev, struct md_rdev *rdev)
7575 if (!rdev || test_bit(Faulty, &rdev->flags))
7576 return;
7578 if (!mddev->pers || !mddev->pers->error_handler)
7579 return;
7580 mddev->pers->error_handler(mddev,rdev);
7581 if (mddev->degraded)
7582 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7583 sysfs_notify_dirent_safe(rdev->sysfs_state);
7584 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7585 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7586 md_wakeup_thread(mddev->thread);
7587 if (mddev->event_work.func)
7588 queue_work(md_misc_wq, &mddev->event_work);
7589 md_new_event(mddev);
7591 EXPORT_SYMBOL(md_error);
7593 /* seq_file implementation /proc/mdstat */
7595 static void status_unused(struct seq_file *seq)
7597 int i = 0;
7598 struct md_rdev *rdev;
7600 seq_printf(seq, "unused devices: ");
7602 list_for_each_entry(rdev, &pending_raid_disks, same_set) {
7603 char b[BDEVNAME_SIZE];
7604 i++;
7605 seq_printf(seq, "%s ",
7606 bdevname(rdev->bdev,b));
7608 if (!i)
7609 seq_printf(seq, "<none>");
7611 seq_printf(seq, "\n");
7614 static int status_resync(struct seq_file *seq, struct mddev *mddev)
7616 sector_t max_sectors, resync, res;
7617 unsigned long dt, db;
7618 sector_t rt;
7619 int scale;
7620 unsigned int per_milli;
7622 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
7623 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7624 max_sectors = mddev->resync_max_sectors;
7625 else
7626 max_sectors = mddev->dev_sectors;
7628 resync = mddev->curr_resync;
7629 if (resync <= 3) {
7630 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7631 /* Still cleaning up */
7632 resync = max_sectors;
7633 } else
7634 resync -= atomic_read(&mddev->recovery_active);
7636 if (resync == 0) {
7637 if (mddev->recovery_cp < MaxSector) {
7638 seq_printf(seq, "\tresync=PENDING");
7639 return 1;
7641 return 0;
7643 if (resync < 3) {
7644 seq_printf(seq, "\tresync=DELAYED");
7645 return 1;
7648 WARN_ON(max_sectors == 0);
7649 /* Pick 'scale' such that (resync>>scale)*1000 will fit
7650 * in a sector_t, and (max_sectors>>scale) will fit in a
7651 * u32, as those are the requirements for sector_div.
7652 * Thus 'scale' must be at least 10
7654 scale = 10;
7655 if (sizeof(sector_t) > sizeof(unsigned long)) {
7656 while ( max_sectors/2 > (1ULL<<(scale+32)))
7657 scale++;
7659 res = (resync>>scale)*1000;
7660 sector_div(res, (u32)((max_sectors>>scale)+1));
7662 per_milli = res;
7664 int i, x = per_milli/50, y = 20-x;
7665 seq_printf(seq, "[");
7666 for (i = 0; i < x; i++)
7667 seq_printf(seq, "=");
7668 seq_printf(seq, ">");
7669 for (i = 0; i < y; i++)
7670 seq_printf(seq, ".");
7671 seq_printf(seq, "] ");
7673 seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
7674 (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
7675 "reshape" :
7676 (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
7677 "check" :
7678 (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
7679 "resync" : "recovery"))),
7680 per_milli/10, per_milli % 10,
7681 (unsigned long long) resync/2,
7682 (unsigned long long) max_sectors/2);
7685 * dt: time from mark until now
7686 * db: blocks written from mark until now
7687 * rt: remaining time
7689 * rt is a sector_t, so could be 32bit or 64bit.
7690 * So we divide before multiply in case it is 32bit and close
7691 * to the limit.
7692 * We scale the divisor (db) by 32 to avoid losing precision
7693 * near the end of resync when the number of remaining sectors
7694 * is close to 'db'.
7695 * We then divide rt by 32 after multiplying by db to compensate.
7696 * The '+1' avoids division by zero if db is very small.
7698 dt = ((jiffies - mddev->resync_mark) / HZ);
7699 if (!dt) dt++;
7700 db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
7701 - mddev->resync_mark_cnt;
7703 rt = max_sectors - resync; /* number of remaining sectors */
7704 sector_div(rt, db/32+1);
7705 rt *= dt;
7706 rt >>= 5;
7708 seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
7709 ((unsigned long)rt % 60)/6);
7711 seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7712 return 1;
7715 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7717 struct list_head *tmp;
7718 loff_t l = *pos;
7719 struct mddev *mddev;
7721 if (l >= 0x10000)
7722 return NULL;
7723 if (!l--)
7724 /* header */
7725 return (void*)1;
7727 spin_lock(&all_mddevs_lock);
7728 list_for_each(tmp,&all_mddevs)
7729 if (!l--) {
7730 mddev = list_entry(tmp, struct mddev, all_mddevs);
7731 mddev_get(mddev);
7732 spin_unlock(&all_mddevs_lock);
7733 return mddev;
7735 spin_unlock(&all_mddevs_lock);
7736 if (!l--)
7737 return (void*)2;/* tail */
7738 return NULL;
7741 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7743 struct list_head *tmp;
7744 struct mddev *next_mddev, *mddev = v;
7746 ++*pos;
7747 if (v == (void*)2)
7748 return NULL;
7750 spin_lock(&all_mddevs_lock);
7751 if (v == (void*)1)
7752 tmp = all_mddevs.next;
7753 else
7754 tmp = mddev->all_mddevs.next;
7755 if (tmp != &all_mddevs)
7756 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7757 else {
7758 next_mddev = (void*)2;
7759 *pos = 0x10000;
7761 spin_unlock(&all_mddevs_lock);
7763 if (v != (void*)1)
7764 mddev_put(mddev);
7765 return next_mddev;
7769 static void md_seq_stop(struct seq_file *seq, void *v)
7771 struct mddev *mddev = v;
7773 if (mddev && v != (void*)1 && v != (void*)2)
7774 mddev_put(mddev);
7777 static int md_seq_show(struct seq_file *seq, void *v)
7779 struct mddev *mddev = v;
7780 sector_t sectors;
7781 struct md_rdev *rdev;
7783 if (v == (void*)1) {
7784 struct md_personality *pers;
7785 seq_printf(seq, "Personalities : ");
7786 spin_lock(&pers_lock);
7787 list_for_each_entry(pers, &pers_list, list)
7788 seq_printf(seq, "[%s] ", pers->name);
7790 spin_unlock(&pers_lock);
7791 seq_printf(seq, "\n");
7792 seq->poll_event = atomic_read(&md_event_count);
7793 return 0;
7795 if (v == (void*)2) {
7796 status_unused(seq);
7797 return 0;
7800 spin_lock(&mddev->lock);
7801 if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7802 seq_printf(seq, "%s : %sactive", mdname(mddev),
7803 mddev->pers ? "" : "in");
7804 if (mddev->pers) {
7805 if (mddev->ro==1)
7806 seq_printf(seq, " (read-only)");
7807 if (mddev->ro==2)
7808 seq_printf(seq, " (auto-read-only)");
7809 seq_printf(seq, " %s", mddev->pers->name);
7812 sectors = 0;
7813 rcu_read_lock();
7814 rdev_for_each_rcu(rdev, mddev) {
7815 char b[BDEVNAME_SIZE];
7816 seq_printf(seq, " %s[%d]",
7817 bdevname(rdev->bdev,b), rdev->desc_nr);
7818 if (test_bit(WriteMostly, &rdev->flags))
7819 seq_printf(seq, "(W)");
7820 if (test_bit(Journal, &rdev->flags))
7821 seq_printf(seq, "(J)");
7822 if (test_bit(Faulty, &rdev->flags)) {
7823 seq_printf(seq, "(F)");
7824 continue;
7826 if (rdev->raid_disk < 0)
7827 seq_printf(seq, "(S)"); /* spare */
7828 if (test_bit(Replacement, &rdev->flags))
7829 seq_printf(seq, "(R)");
7830 sectors += rdev->sectors;
7832 rcu_read_unlock();
7834 if (!list_empty(&mddev->disks)) {
7835 if (mddev->pers)
7836 seq_printf(seq, "\n %llu blocks",
7837 (unsigned long long)
7838 mddev->array_sectors / 2);
7839 else
7840 seq_printf(seq, "\n %llu blocks",
7841 (unsigned long long)sectors / 2);
7843 if (mddev->persistent) {
7844 if (mddev->major_version != 0 ||
7845 mddev->minor_version != 90) {
7846 seq_printf(seq," super %d.%d",
7847 mddev->major_version,
7848 mddev->minor_version);
7850 } else if (mddev->external)
7851 seq_printf(seq, " super external:%s",
7852 mddev->metadata_type);
7853 else
7854 seq_printf(seq, " super non-persistent");
7856 if (mddev->pers) {
7857 mddev->pers->status(seq, mddev);
7858 seq_printf(seq, "\n ");
7859 if (mddev->pers->sync_request) {
7860 if (status_resync(seq, mddev))
7861 seq_printf(seq, "\n ");
7863 } else
7864 seq_printf(seq, "\n ");
7866 bitmap_status(seq, mddev->bitmap);
7868 seq_printf(seq, "\n");
7870 spin_unlock(&mddev->lock);
7872 return 0;
7875 static const struct seq_operations md_seq_ops = {
7876 .start = md_seq_start,
7877 .next = md_seq_next,
7878 .stop = md_seq_stop,
7879 .show = md_seq_show,
7882 static int md_seq_open(struct inode *inode, struct file *file)
7884 struct seq_file *seq;
7885 int error;
7887 error = seq_open(file, &md_seq_ops);
7888 if (error)
7889 return error;
7891 seq = file->private_data;
7892 seq->poll_event = atomic_read(&md_event_count);
7893 return error;
7896 static int md_unloading;
7897 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
7899 struct seq_file *seq = filp->private_data;
7900 int mask;
7902 if (md_unloading)
7903 return POLLIN|POLLRDNORM|POLLERR|POLLPRI;
7904 poll_wait(filp, &md_event_waiters, wait);
7906 /* always allow read */
7907 mask = POLLIN | POLLRDNORM;
7909 if (seq->poll_event != atomic_read(&md_event_count))
7910 mask |= POLLERR | POLLPRI;
7911 return mask;
7914 static const struct file_operations md_seq_fops = {
7915 .owner = THIS_MODULE,
7916 .open = md_seq_open,
7917 .read = seq_read,
7918 .llseek = seq_lseek,
7919 .release = seq_release,
7920 .poll = mdstat_poll,
7923 int register_md_personality(struct md_personality *p)
7925 pr_debug("md: %s personality registered for level %d\n",
7926 p->name, p->level);
7927 spin_lock(&pers_lock);
7928 list_add_tail(&p->list, &pers_list);
7929 spin_unlock(&pers_lock);
7930 return 0;
7932 EXPORT_SYMBOL(register_md_personality);
7934 int unregister_md_personality(struct md_personality *p)
7936 pr_debug("md: %s personality unregistered\n", p->name);
7937 spin_lock(&pers_lock);
7938 list_del_init(&p->list);
7939 spin_unlock(&pers_lock);
7940 return 0;
7942 EXPORT_SYMBOL(unregister_md_personality);
7944 int register_md_cluster_operations(struct md_cluster_operations *ops,
7945 struct module *module)
7947 int ret = 0;
7948 spin_lock(&pers_lock);
7949 if (md_cluster_ops != NULL)
7950 ret = -EALREADY;
7951 else {
7952 md_cluster_ops = ops;
7953 md_cluster_mod = module;
7955 spin_unlock(&pers_lock);
7956 return ret;
7958 EXPORT_SYMBOL(register_md_cluster_operations);
7960 int unregister_md_cluster_operations(void)
7962 spin_lock(&pers_lock);
7963 md_cluster_ops = NULL;
7964 spin_unlock(&pers_lock);
7965 return 0;
7967 EXPORT_SYMBOL(unregister_md_cluster_operations);
7969 int md_setup_cluster(struct mddev *mddev, int nodes)
7971 if (!md_cluster_ops)
7972 request_module("md-cluster");
7973 spin_lock(&pers_lock);
7974 /* ensure module won't be unloaded */
7975 if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
7976 pr_warn("can't find md-cluster module or get it's reference.\n");
7977 spin_unlock(&pers_lock);
7978 return -ENOENT;
7980 spin_unlock(&pers_lock);
7982 return md_cluster_ops->join(mddev, nodes);
7985 void md_cluster_stop(struct mddev *mddev)
7987 if (!md_cluster_ops)
7988 return;
7989 md_cluster_ops->leave(mddev);
7990 module_put(md_cluster_mod);
7993 static int is_mddev_idle(struct mddev *mddev, int init)
7995 struct md_rdev *rdev;
7996 int idle;
7997 int curr_events;
7999 idle = 1;
8000 rcu_read_lock();
8001 rdev_for_each_rcu(rdev, mddev) {
8002 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
8003 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
8004 (int)part_stat_read(&disk->part0, sectors[1]) -
8005 atomic_read(&disk->sync_io);
8006 /* sync IO will cause sync_io to increase before the disk_stats
8007 * as sync_io is counted when a request starts, and
8008 * disk_stats is counted when it completes.
8009 * So resync activity will cause curr_events to be smaller than
8010 * when there was no such activity.
8011 * non-sync IO will cause disk_stat to increase without
8012 * increasing sync_io so curr_events will (eventually)
8013 * be larger than it was before. Once it becomes
8014 * substantially larger, the test below will cause
8015 * the array to appear non-idle, and resync will slow
8016 * down.
8017 * If there is a lot of outstanding resync activity when
8018 * we set last_event to curr_events, then all that activity
8019 * completing might cause the array to appear non-idle
8020 * and resync will be slowed down even though there might
8021 * not have been non-resync activity. This will only
8022 * happen once though. 'last_events' will soon reflect
8023 * the state where there is little or no outstanding
8024 * resync requests, and further resync activity will
8025 * always make curr_events less than last_events.
8028 if (init || curr_events - rdev->last_events > 64) {
8029 rdev->last_events = curr_events;
8030 idle = 0;
8033 rcu_read_unlock();
8034 return idle;
8037 void md_done_sync(struct mddev *mddev, int blocks, int ok)
8039 /* another "blocks" (512byte) blocks have been synced */
8040 atomic_sub(blocks, &mddev->recovery_active);
8041 wake_up(&mddev->recovery_wait);
8042 if (!ok) {
8043 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8044 set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
8045 md_wakeup_thread(mddev->thread);
8046 // stop recovery, signal do_sync ....
8049 EXPORT_SYMBOL(md_done_sync);
8051 /* md_write_start(mddev, bi)
8052 * If we need to update some array metadata (e.g. 'active' flag
8053 * in superblock) before writing, schedule a superblock update
8054 * and wait for it to complete.
8055 * A return value of 'false' means that the write wasn't recorded
8056 * and cannot proceed as the array is being suspend.
8058 bool md_write_start(struct mddev *mddev, struct bio *bi)
8060 int did_change = 0;
8062 if (bio_data_dir(bi) != WRITE)
8063 return true;
8065 BUG_ON(mddev->ro == 1);
8066 if (mddev->ro == 2) {
8067 /* need to switch to read/write */
8068 mddev->ro = 0;
8069 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8070 md_wakeup_thread(mddev->thread);
8071 md_wakeup_thread(mddev->sync_thread);
8072 did_change = 1;
8074 rcu_read_lock();
8075 percpu_ref_get(&mddev->writes_pending);
8076 smp_mb(); /* Match smp_mb in set_in_sync() */
8077 if (mddev->safemode == 1)
8078 mddev->safemode = 0;
8079 /* sync_checkers is always 0 when writes_pending is in per-cpu mode */
8080 if (mddev->in_sync || mddev->sync_checkers) {
8081 spin_lock(&mddev->lock);
8082 if (mddev->in_sync) {
8083 mddev->in_sync = 0;
8084 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8085 set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8086 md_wakeup_thread(mddev->thread);
8087 did_change = 1;
8089 spin_unlock(&mddev->lock);
8091 rcu_read_unlock();
8092 if (did_change)
8093 sysfs_notify_dirent_safe(mddev->sysfs_state);
8094 if (!mddev->has_superblocks)
8095 return true;
8096 wait_event(mddev->sb_wait,
8097 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags) ||
8098 mddev->suspended);
8099 if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
8100 percpu_ref_put(&mddev->writes_pending);
8101 return false;
8103 return true;
8105 EXPORT_SYMBOL(md_write_start);
8107 /* md_write_inc can only be called when md_write_start() has
8108 * already been called at least once of the current request.
8109 * It increments the counter and is useful when a single request
8110 * is split into several parts. Each part causes an increment and
8111 * so needs a matching md_write_end().
8112 * Unlike md_write_start(), it is safe to call md_write_inc() inside
8113 * a spinlocked region.
8115 void md_write_inc(struct mddev *mddev, struct bio *bi)
8117 if (bio_data_dir(bi) != WRITE)
8118 return;
8119 WARN_ON_ONCE(mddev->in_sync || mddev->ro);
8120 percpu_ref_get(&mddev->writes_pending);
8122 EXPORT_SYMBOL(md_write_inc);
8124 void md_write_end(struct mddev *mddev)
8126 percpu_ref_put(&mddev->writes_pending);
8128 if (mddev->safemode == 2)
8129 md_wakeup_thread(mddev->thread);
8130 else if (mddev->safemode_delay)
8131 /* The roundup() ensures this only performs locking once
8132 * every ->safemode_delay jiffies
8134 mod_timer(&mddev->safemode_timer,
8135 roundup(jiffies, mddev->safemode_delay) +
8136 mddev->safemode_delay);
8139 EXPORT_SYMBOL(md_write_end);
8141 /* md_allow_write(mddev)
8142 * Calling this ensures that the array is marked 'active' so that writes
8143 * may proceed without blocking. It is important to call this before
8144 * attempting a GFP_KERNEL allocation while holding the mddev lock.
8145 * Must be called with mddev_lock held.
8147 void md_allow_write(struct mddev *mddev)
8149 if (!mddev->pers)
8150 return;
8151 if (mddev->ro)
8152 return;
8153 if (!mddev->pers->sync_request)
8154 return;
8156 spin_lock(&mddev->lock);
8157 if (mddev->in_sync) {
8158 mddev->in_sync = 0;
8159 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8160 set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8161 if (mddev->safemode_delay &&
8162 mddev->safemode == 0)
8163 mddev->safemode = 1;
8164 spin_unlock(&mddev->lock);
8165 md_update_sb(mddev, 0);
8166 sysfs_notify_dirent_safe(mddev->sysfs_state);
8167 /* wait for the dirty state to be recorded in the metadata */
8168 wait_event(mddev->sb_wait,
8169 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
8170 } else
8171 spin_unlock(&mddev->lock);
8173 EXPORT_SYMBOL_GPL(md_allow_write);
8175 #define SYNC_MARKS 10
8176 #define SYNC_MARK_STEP (3*HZ)
8177 #define UPDATE_FREQUENCY (5*60*HZ)
8178 void md_do_sync(struct md_thread *thread)
8180 struct mddev *mddev = thread->mddev;
8181 struct mddev *mddev2;
8182 unsigned int currspeed = 0,
8183 window;
8184 sector_t max_sectors,j, io_sectors, recovery_done;
8185 unsigned long mark[SYNC_MARKS];
8186 unsigned long update_time;
8187 sector_t mark_cnt[SYNC_MARKS];
8188 int last_mark,m;
8189 struct list_head *tmp;
8190 sector_t last_check;
8191 int skipped = 0;
8192 struct md_rdev *rdev;
8193 char *desc, *action = NULL;
8194 struct blk_plug plug;
8195 int ret;
8197 /* just incase thread restarts... */
8198 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
8199 return;
8200 if (mddev->ro) {/* never try to sync a read-only array */
8201 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8202 return;
8205 if (mddev_is_clustered(mddev)) {
8206 ret = md_cluster_ops->resync_start(mddev);
8207 if (ret)
8208 goto skip;
8210 set_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags);
8211 if (!(test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8212 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) ||
8213 test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
8214 && ((unsigned long long)mddev->curr_resync_completed
8215 < (unsigned long long)mddev->resync_max_sectors))
8216 goto skip;
8219 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8220 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
8221 desc = "data-check";
8222 action = "check";
8223 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8224 desc = "requested-resync";
8225 action = "repair";
8226 } else
8227 desc = "resync";
8228 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8229 desc = "reshape";
8230 else
8231 desc = "recovery";
8233 mddev->last_sync_action = action ?: desc;
8235 /* we overload curr_resync somewhat here.
8236 * 0 == not engaged in resync at all
8237 * 2 == checking that there is no conflict with another sync
8238 * 1 == like 2, but have yielded to allow conflicting resync to
8239 * commense
8240 * other == active in resync - this many blocks
8242 * Before starting a resync we must have set curr_resync to
8243 * 2, and then checked that every "conflicting" array has curr_resync
8244 * less than ours. When we find one that is the same or higher
8245 * we wait on resync_wait. To avoid deadlock, we reduce curr_resync
8246 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
8247 * This will mean we have to start checking from the beginning again.
8251 do {
8252 int mddev2_minor = -1;
8253 mddev->curr_resync = 2;
8255 try_again:
8256 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8257 goto skip;
8258 for_each_mddev(mddev2, tmp) {
8259 if (mddev2 == mddev)
8260 continue;
8261 if (!mddev->parallel_resync
8262 && mddev2->curr_resync
8263 && match_mddev_units(mddev, mddev2)) {
8264 DEFINE_WAIT(wq);
8265 if (mddev < mddev2 && mddev->curr_resync == 2) {
8266 /* arbitrarily yield */
8267 mddev->curr_resync = 1;
8268 wake_up(&resync_wait);
8270 if (mddev > mddev2 && mddev->curr_resync == 1)
8271 /* no need to wait here, we can wait the next
8272 * time 'round when curr_resync == 2
8274 continue;
8275 /* We need to wait 'interruptible' so as not to
8276 * contribute to the load average, and not to
8277 * be caught by 'softlockup'
8279 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
8280 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8281 mddev2->curr_resync >= mddev->curr_resync) {
8282 if (mddev2_minor != mddev2->md_minor) {
8283 mddev2_minor = mddev2->md_minor;
8284 pr_info("md: delaying %s of %s until %s has finished (they share one or more physical units)\n",
8285 desc, mdname(mddev),
8286 mdname(mddev2));
8288 mddev_put(mddev2);
8289 if (signal_pending(current))
8290 flush_signals(current);
8291 schedule();
8292 finish_wait(&resync_wait, &wq);
8293 goto try_again;
8295 finish_wait(&resync_wait, &wq);
8298 } while (mddev->curr_resync < 2);
8300 j = 0;
8301 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8302 /* resync follows the size requested by the personality,
8303 * which defaults to physical size, but can be virtual size
8305 max_sectors = mddev->resync_max_sectors;
8306 atomic64_set(&mddev->resync_mismatches, 0);
8307 /* we don't use the checkpoint if there's a bitmap */
8308 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8309 j = mddev->resync_min;
8310 else if (!mddev->bitmap)
8311 j = mddev->recovery_cp;
8313 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8314 max_sectors = mddev->resync_max_sectors;
8315 else {
8316 /* recovery follows the physical size of devices */
8317 max_sectors = mddev->dev_sectors;
8318 j = MaxSector;
8319 rcu_read_lock();
8320 rdev_for_each_rcu(rdev, mddev)
8321 if (rdev->raid_disk >= 0 &&
8322 !test_bit(Journal, &rdev->flags) &&
8323 !test_bit(Faulty, &rdev->flags) &&
8324 !test_bit(In_sync, &rdev->flags) &&
8325 rdev->recovery_offset < j)
8326 j = rdev->recovery_offset;
8327 rcu_read_unlock();
8329 /* If there is a bitmap, we need to make sure all
8330 * writes that started before we added a spare
8331 * complete before we start doing a recovery.
8332 * Otherwise the write might complete and (via
8333 * bitmap_endwrite) set a bit in the bitmap after the
8334 * recovery has checked that bit and skipped that
8335 * region.
8337 if (mddev->bitmap) {
8338 mddev->pers->quiesce(mddev, 1);
8339 mddev->pers->quiesce(mddev, 0);
8343 pr_info("md: %s of RAID array %s\n", desc, mdname(mddev));
8344 pr_debug("md: minimum _guaranteed_ speed: %d KB/sec/disk.\n", speed_min(mddev));
8345 pr_debug("md: using maximum available idle IO bandwidth (but not more than %d KB/sec) for %s.\n",
8346 speed_max(mddev), desc);
8348 is_mddev_idle(mddev, 1); /* this initializes IO event counters */
8350 io_sectors = 0;
8351 for (m = 0; m < SYNC_MARKS; m++) {
8352 mark[m] = jiffies;
8353 mark_cnt[m] = io_sectors;
8355 last_mark = 0;
8356 mddev->resync_mark = mark[last_mark];
8357 mddev->resync_mark_cnt = mark_cnt[last_mark];
8360 * Tune reconstruction:
8362 window = 32*(PAGE_SIZE/512);
8363 pr_debug("md: using %dk window, over a total of %lluk.\n",
8364 window/2, (unsigned long long)max_sectors/2);
8366 atomic_set(&mddev->recovery_active, 0);
8367 last_check = 0;
8369 if (j>2) {
8370 pr_debug("md: resuming %s of %s from checkpoint.\n",
8371 desc, mdname(mddev));
8372 mddev->curr_resync = j;
8373 } else
8374 mddev->curr_resync = 3; /* no longer delayed */
8375 mddev->curr_resync_completed = j;
8376 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8377 md_new_event(mddev);
8378 update_time = jiffies;
8380 blk_start_plug(&plug);
8381 while (j < max_sectors) {
8382 sector_t sectors;
8384 skipped = 0;
8386 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8387 ((mddev->curr_resync > mddev->curr_resync_completed &&
8388 (mddev->curr_resync - mddev->curr_resync_completed)
8389 > (max_sectors >> 4)) ||
8390 time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
8391 (j - mddev->curr_resync_completed)*2
8392 >= mddev->resync_max - mddev->curr_resync_completed ||
8393 mddev->curr_resync_completed > mddev->resync_max
8394 )) {
8395 /* time to update curr_resync_completed */
8396 wait_event(mddev->recovery_wait,
8397 atomic_read(&mddev->recovery_active) == 0);
8398 mddev->curr_resync_completed = j;
8399 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
8400 j > mddev->recovery_cp)
8401 mddev->recovery_cp = j;
8402 update_time = jiffies;
8403 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8404 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8407 while (j >= mddev->resync_max &&
8408 !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8409 /* As this condition is controlled by user-space,
8410 * we can block indefinitely, so use '_interruptible'
8411 * to avoid triggering warnings.
8413 flush_signals(current); /* just in case */
8414 wait_event_interruptible(mddev->recovery_wait,
8415 mddev->resync_max > j
8416 || test_bit(MD_RECOVERY_INTR,
8417 &mddev->recovery));
8420 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8421 break;
8423 sectors = mddev->pers->sync_request(mddev, j, &skipped);
8424 if (sectors == 0) {
8425 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8426 break;
8429 if (!skipped) { /* actual IO requested */
8430 io_sectors += sectors;
8431 atomic_add(sectors, &mddev->recovery_active);
8434 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8435 break;
8437 j += sectors;
8438 if (j > max_sectors)
8439 /* when skipping, extra large numbers can be returned. */
8440 j = max_sectors;
8441 if (j > 2)
8442 mddev->curr_resync = j;
8443 mddev->curr_mark_cnt = io_sectors;
8444 if (last_check == 0)
8445 /* this is the earliest that rebuild will be
8446 * visible in /proc/mdstat
8448 md_new_event(mddev);
8450 if (last_check + window > io_sectors || j == max_sectors)
8451 continue;
8453 last_check = io_sectors;
8454 repeat:
8455 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
8456 /* step marks */
8457 int next = (last_mark+1) % SYNC_MARKS;
8459 mddev->resync_mark = mark[next];
8460 mddev->resync_mark_cnt = mark_cnt[next];
8461 mark[next] = jiffies;
8462 mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
8463 last_mark = next;
8466 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8467 break;
8470 * this loop exits only if either when we are slower than
8471 * the 'hard' speed limit, or the system was IO-idle for
8472 * a jiffy.
8473 * the system might be non-idle CPU-wise, but we only care
8474 * about not overloading the IO subsystem. (things like an
8475 * e2fsck being done on the RAID array should execute fast)
8477 cond_resched();
8479 recovery_done = io_sectors - atomic_read(&mddev->recovery_active);
8480 currspeed = ((unsigned long)(recovery_done - mddev->resync_mark_cnt))/2
8481 /((jiffies-mddev->resync_mark)/HZ +1) +1;
8483 if (currspeed > speed_min(mddev)) {
8484 if (currspeed > speed_max(mddev)) {
8485 msleep(500);
8486 goto repeat;
8488 if (!is_mddev_idle(mddev, 0)) {
8490 * Give other IO more of a chance.
8491 * The faster the devices, the less we wait.
8493 wait_event(mddev->recovery_wait,
8494 !atomic_read(&mddev->recovery_active));
8498 pr_info("md: %s: %s %s.\n",mdname(mddev), desc,
8499 test_bit(MD_RECOVERY_INTR, &mddev->recovery)
8500 ? "interrupted" : "done");
8502 * this also signals 'finished resyncing' to md_stop
8504 blk_finish_plug(&plug);
8505 wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
8507 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8508 !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8509 mddev->curr_resync > 3) {
8510 mddev->curr_resync_completed = mddev->curr_resync;
8511 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8513 mddev->pers->sync_request(mddev, max_sectors, &skipped);
8515 if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
8516 mddev->curr_resync > 3) {
8517 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8518 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8519 if (mddev->curr_resync >= mddev->recovery_cp) {
8520 pr_debug("md: checkpointing %s of %s.\n",
8521 desc, mdname(mddev));
8522 if (test_bit(MD_RECOVERY_ERROR,
8523 &mddev->recovery))
8524 mddev->recovery_cp =
8525 mddev->curr_resync_completed;
8526 else
8527 mddev->recovery_cp =
8528 mddev->curr_resync;
8530 } else
8531 mddev->recovery_cp = MaxSector;
8532 } else {
8533 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8534 mddev->curr_resync = MaxSector;
8535 rcu_read_lock();
8536 rdev_for_each_rcu(rdev, mddev)
8537 if (rdev->raid_disk >= 0 &&
8538 mddev->delta_disks >= 0 &&
8539 !test_bit(Journal, &rdev->flags) &&
8540 !test_bit(Faulty, &rdev->flags) &&
8541 !test_bit(In_sync, &rdev->flags) &&
8542 rdev->recovery_offset < mddev->curr_resync)
8543 rdev->recovery_offset = mddev->curr_resync;
8544 rcu_read_unlock();
8547 skip:
8548 /* set CHANGE_PENDING here since maybe another update is needed,
8549 * so other nodes are informed. It should be harmless for normal
8550 * raid */
8551 set_mask_bits(&mddev->sb_flags, 0,
8552 BIT(MD_SB_CHANGE_PENDING) | BIT(MD_SB_CHANGE_DEVS));
8554 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8555 !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8556 mddev->delta_disks > 0 &&
8557 mddev->pers->finish_reshape &&
8558 mddev->pers->size &&
8559 mddev->queue) {
8560 mddev_lock_nointr(mddev);
8561 md_set_array_sectors(mddev, mddev->pers->size(mddev, 0, 0));
8562 mddev_unlock(mddev);
8563 set_capacity(mddev->gendisk, mddev->array_sectors);
8564 revalidate_disk(mddev->gendisk);
8567 spin_lock(&mddev->lock);
8568 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8569 /* We completed so min/max setting can be forgotten if used. */
8570 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8571 mddev->resync_min = 0;
8572 mddev->resync_max = MaxSector;
8573 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8574 mddev->resync_min = mddev->curr_resync_completed;
8575 set_bit(MD_RECOVERY_DONE, &mddev->recovery);
8576 mddev->curr_resync = 0;
8577 spin_unlock(&mddev->lock);
8579 wake_up(&resync_wait);
8580 md_wakeup_thread(mddev->thread);
8581 return;
8583 EXPORT_SYMBOL_GPL(md_do_sync);
8585 static int remove_and_add_spares(struct mddev *mddev,
8586 struct md_rdev *this)
8588 struct md_rdev *rdev;
8589 int spares = 0;
8590 int removed = 0;
8591 bool remove_some = false;
8593 if (this && test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
8594 /* Mustn't remove devices when resync thread is running */
8595 return 0;
8597 rdev_for_each(rdev, mddev) {
8598 if ((this == NULL || rdev == this) &&
8599 rdev->raid_disk >= 0 &&
8600 !test_bit(Blocked, &rdev->flags) &&
8601 test_bit(Faulty, &rdev->flags) &&
8602 atomic_read(&rdev->nr_pending)==0) {
8603 /* Faulty non-Blocked devices with nr_pending == 0
8604 * never get nr_pending incremented,
8605 * never get Faulty cleared, and never get Blocked set.
8606 * So we can synchronize_rcu now rather than once per device
8608 remove_some = true;
8609 set_bit(RemoveSynchronized, &rdev->flags);
8613 if (remove_some)
8614 synchronize_rcu();
8615 rdev_for_each(rdev, mddev) {
8616 if ((this == NULL || rdev == this) &&
8617 rdev->raid_disk >= 0 &&
8618 !test_bit(Blocked, &rdev->flags) &&
8619 ((test_bit(RemoveSynchronized, &rdev->flags) ||
8620 (!test_bit(In_sync, &rdev->flags) &&
8621 !test_bit(Journal, &rdev->flags))) &&
8622 atomic_read(&rdev->nr_pending)==0)) {
8623 if (mddev->pers->hot_remove_disk(
8624 mddev, rdev) == 0) {
8625 sysfs_unlink_rdev(mddev, rdev);
8626 rdev->saved_raid_disk = rdev->raid_disk;
8627 rdev->raid_disk = -1;
8628 removed++;
8631 if (remove_some && test_bit(RemoveSynchronized, &rdev->flags))
8632 clear_bit(RemoveSynchronized, &rdev->flags);
8635 if (removed && mddev->kobj.sd)
8636 sysfs_notify(&mddev->kobj, NULL, "degraded");
8638 if (this && removed)
8639 goto no_add;
8641 rdev_for_each(rdev, mddev) {
8642 if (this && this != rdev)
8643 continue;
8644 if (test_bit(Candidate, &rdev->flags))
8645 continue;
8646 if (rdev->raid_disk >= 0 &&
8647 !test_bit(In_sync, &rdev->flags) &&
8648 !test_bit(Journal, &rdev->flags) &&
8649 !test_bit(Faulty, &rdev->flags))
8650 spares++;
8651 if (rdev->raid_disk >= 0)
8652 continue;
8653 if (test_bit(Faulty, &rdev->flags))
8654 continue;
8655 if (!test_bit(Journal, &rdev->flags)) {
8656 if (mddev->ro &&
8657 ! (rdev->saved_raid_disk >= 0 &&
8658 !test_bit(Bitmap_sync, &rdev->flags)))
8659 continue;
8661 rdev->recovery_offset = 0;
8663 if (mddev->pers->
8664 hot_add_disk(mddev, rdev) == 0) {
8665 if (sysfs_link_rdev(mddev, rdev))
8666 /* failure here is OK */;
8667 if (!test_bit(Journal, &rdev->flags))
8668 spares++;
8669 md_new_event(mddev);
8670 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8673 no_add:
8674 if (removed)
8675 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8676 return spares;
8679 static void md_start_sync(struct work_struct *ws)
8681 struct mddev *mddev = container_of(ws, struct mddev, del_work);
8683 mddev->sync_thread = md_register_thread(md_do_sync,
8684 mddev,
8685 "resync");
8686 if (!mddev->sync_thread) {
8687 pr_warn("%s: could not start resync thread...\n",
8688 mdname(mddev));
8689 /* leave the spares where they are, it shouldn't hurt */
8690 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8691 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8692 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8693 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8694 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8695 wake_up(&resync_wait);
8696 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8697 &mddev->recovery))
8698 if (mddev->sysfs_action)
8699 sysfs_notify_dirent_safe(mddev->sysfs_action);
8700 } else
8701 md_wakeup_thread(mddev->sync_thread);
8702 sysfs_notify_dirent_safe(mddev->sysfs_action);
8703 md_new_event(mddev);
8707 * This routine is regularly called by all per-raid-array threads to
8708 * deal with generic issues like resync and super-block update.
8709 * Raid personalities that don't have a thread (linear/raid0) do not
8710 * need this as they never do any recovery or update the superblock.
8712 * It does not do any resync itself, but rather "forks" off other threads
8713 * to do that as needed.
8714 * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
8715 * "->recovery" and create a thread at ->sync_thread.
8716 * When the thread finishes it sets MD_RECOVERY_DONE
8717 * and wakeups up this thread which will reap the thread and finish up.
8718 * This thread also removes any faulty devices (with nr_pending == 0).
8720 * The overall approach is:
8721 * 1/ if the superblock needs updating, update it.
8722 * 2/ If a recovery thread is running, don't do anything else.
8723 * 3/ If recovery has finished, clean up, possibly marking spares active.
8724 * 4/ If there are any faulty devices, remove them.
8725 * 5/ If array is degraded, try to add spares devices
8726 * 6/ If array has spares or is not in-sync, start a resync thread.
8728 void md_check_recovery(struct mddev *mddev)
8730 if (mddev->suspended)
8731 return;
8733 if (mddev->bitmap)
8734 bitmap_daemon_work(mddev);
8736 if (signal_pending(current)) {
8737 if (mddev->pers->sync_request && !mddev->external) {
8738 pr_debug("md: %s in immediate safe mode\n",
8739 mdname(mddev));
8740 mddev->safemode = 2;
8742 flush_signals(current);
8745 if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
8746 return;
8747 if ( ! (
8748 (mddev->sb_flags & ~ (1<<MD_SB_CHANGE_PENDING)) ||
8749 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8750 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8751 (mddev->external == 0 && mddev->safemode == 1) ||
8752 (mddev->safemode == 2
8753 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
8755 return;
8757 if (mddev_trylock(mddev)) {
8758 int spares = 0;
8760 if (!mddev->external && mddev->safemode == 1)
8761 mddev->safemode = 0;
8763 if (mddev->ro) {
8764 struct md_rdev *rdev;
8765 if (!mddev->external && mddev->in_sync)
8766 /* 'Blocked' flag not needed as failed devices
8767 * will be recorded if array switched to read/write.
8768 * Leaving it set will prevent the device
8769 * from being removed.
8771 rdev_for_each(rdev, mddev)
8772 clear_bit(Blocked, &rdev->flags);
8773 /* On a read-only array we can:
8774 * - remove failed devices
8775 * - add already-in_sync devices if the array itself
8776 * is in-sync.
8777 * As we only add devices that are already in-sync,
8778 * we can activate the spares immediately.
8780 remove_and_add_spares(mddev, NULL);
8781 /* There is no thread, but we need to call
8782 * ->spare_active and clear saved_raid_disk
8784 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8785 md_reap_sync_thread(mddev);
8786 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8787 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8788 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8789 goto unlock;
8792 if (mddev_is_clustered(mddev)) {
8793 struct md_rdev *rdev;
8794 /* kick the device if another node issued a
8795 * remove disk.
8797 rdev_for_each(rdev, mddev) {
8798 if (test_and_clear_bit(ClusterRemove, &rdev->flags) &&
8799 rdev->raid_disk < 0)
8800 md_kick_rdev_from_array(rdev);
8804 if (!mddev->external && !mddev->in_sync) {
8805 spin_lock(&mddev->lock);
8806 set_in_sync(mddev);
8807 spin_unlock(&mddev->lock);
8810 if (mddev->sb_flags)
8811 md_update_sb(mddev, 0);
8813 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
8814 !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
8815 /* resync/recovery still happening */
8816 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8817 goto unlock;
8819 if (mddev->sync_thread) {
8820 md_reap_sync_thread(mddev);
8821 goto unlock;
8823 /* Set RUNNING before clearing NEEDED to avoid
8824 * any transients in the value of "sync_action".
8826 mddev->curr_resync_completed = 0;
8827 spin_lock(&mddev->lock);
8828 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8829 spin_unlock(&mddev->lock);
8830 /* Clear some bits that don't mean anything, but
8831 * might be left set
8833 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
8834 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8836 if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8837 test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
8838 goto not_running;
8839 /* no recovery is running.
8840 * remove any failed drives, then
8841 * add spares if possible.
8842 * Spares are also removed and re-added, to allow
8843 * the personality to fail the re-add.
8846 if (mddev->reshape_position != MaxSector) {
8847 if (mddev->pers->check_reshape == NULL ||
8848 mddev->pers->check_reshape(mddev) != 0)
8849 /* Cannot proceed */
8850 goto not_running;
8851 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8852 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8853 } else if ((spares = remove_and_add_spares(mddev, NULL))) {
8854 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8855 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8856 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8857 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8858 } else if (mddev->recovery_cp < MaxSector) {
8859 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8860 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8861 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
8862 /* nothing to be done ... */
8863 goto not_running;
8865 if (mddev->pers->sync_request) {
8866 if (spares) {
8867 /* We are adding a device or devices to an array
8868 * which has the bitmap stored on all devices.
8869 * So make sure all bitmap pages get written
8871 bitmap_write_all(mddev->bitmap);
8873 INIT_WORK(&mddev->del_work, md_start_sync);
8874 queue_work(md_misc_wq, &mddev->del_work);
8875 goto unlock;
8877 not_running:
8878 if (!mddev->sync_thread) {
8879 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8880 wake_up(&resync_wait);
8881 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8882 &mddev->recovery))
8883 if (mddev->sysfs_action)
8884 sysfs_notify_dirent_safe(mddev->sysfs_action);
8886 unlock:
8887 wake_up(&mddev->sb_wait);
8888 mddev_unlock(mddev);
8889 } else if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags) && mddev->sb_flags) {
8890 /* Write superblock - thread that called mddev_suspend()
8891 * holds reconfig_mutex for us.
8893 set_bit(MD_UPDATING_SB, &mddev->flags);
8894 smp_mb__after_atomic();
8895 if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags))
8896 md_update_sb(mddev, 0);
8897 clear_bit_unlock(MD_UPDATING_SB, &mddev->flags);
8898 wake_up(&mddev->sb_wait);
8901 EXPORT_SYMBOL(md_check_recovery);
8903 void md_reap_sync_thread(struct mddev *mddev)
8905 struct md_rdev *rdev;
8907 /* resync has finished, collect result */
8908 md_unregister_thread(&mddev->sync_thread);
8909 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8910 !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8911 /* success...*/
8912 /* activate any spares */
8913 if (mddev->pers->spare_active(mddev)) {
8914 sysfs_notify(&mddev->kobj, NULL,
8915 "degraded");
8916 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8919 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8920 mddev->pers->finish_reshape)
8921 mddev->pers->finish_reshape(mddev);
8923 /* If array is no-longer degraded, then any saved_raid_disk
8924 * information must be scrapped.
8926 if (!mddev->degraded)
8927 rdev_for_each(rdev, mddev)
8928 rdev->saved_raid_disk = -1;
8930 md_update_sb(mddev, 1);
8931 /* MD_SB_CHANGE_PENDING should be cleared by md_update_sb, so we can
8932 * call resync_finish here if MD_CLUSTER_RESYNC_LOCKED is set by
8933 * clustered raid */
8934 if (test_and_clear_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags))
8935 md_cluster_ops->resync_finish(mddev);
8936 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8937 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8938 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8939 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8940 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8941 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8942 wake_up(&resync_wait);
8943 /* flag recovery needed just to double check */
8944 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8945 sysfs_notify_dirent_safe(mddev->sysfs_action);
8946 md_new_event(mddev);
8947 if (mddev->event_work.func)
8948 queue_work(md_misc_wq, &mddev->event_work);
8950 EXPORT_SYMBOL(md_reap_sync_thread);
8952 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
8954 sysfs_notify_dirent_safe(rdev->sysfs_state);
8955 wait_event_timeout(rdev->blocked_wait,
8956 !test_bit(Blocked, &rdev->flags) &&
8957 !test_bit(BlockedBadBlocks, &rdev->flags),
8958 msecs_to_jiffies(5000));
8959 rdev_dec_pending(rdev, mddev);
8961 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
8963 void md_finish_reshape(struct mddev *mddev)
8965 /* called be personality module when reshape completes. */
8966 struct md_rdev *rdev;
8968 rdev_for_each(rdev, mddev) {
8969 if (rdev->data_offset > rdev->new_data_offset)
8970 rdev->sectors += rdev->data_offset - rdev->new_data_offset;
8971 else
8972 rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
8973 rdev->data_offset = rdev->new_data_offset;
8976 EXPORT_SYMBOL(md_finish_reshape);
8978 /* Bad block management */
8980 /* Returns 1 on success, 0 on failure */
8981 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8982 int is_new)
8984 struct mddev *mddev = rdev->mddev;
8985 int rv;
8986 if (is_new)
8987 s += rdev->new_data_offset;
8988 else
8989 s += rdev->data_offset;
8990 rv = badblocks_set(&rdev->badblocks, s, sectors, 0);
8991 if (rv == 0) {
8992 /* Make sure they get written out promptly */
8993 if (test_bit(ExternalBbl, &rdev->flags))
8994 sysfs_notify(&rdev->kobj, NULL,
8995 "unacknowledged_bad_blocks");
8996 sysfs_notify_dirent_safe(rdev->sysfs_state);
8997 set_mask_bits(&mddev->sb_flags, 0,
8998 BIT(MD_SB_CHANGE_CLEAN) | BIT(MD_SB_CHANGE_PENDING));
8999 md_wakeup_thread(rdev->mddev->thread);
9000 return 1;
9001 } else
9002 return 0;
9004 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
9006 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
9007 int is_new)
9009 int rv;
9010 if (is_new)
9011 s += rdev->new_data_offset;
9012 else
9013 s += rdev->data_offset;
9014 rv = badblocks_clear(&rdev->badblocks, s, sectors);
9015 if ((rv == 0) && test_bit(ExternalBbl, &rdev->flags))
9016 sysfs_notify(&rdev->kobj, NULL, "bad_blocks");
9017 return rv;
9019 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
9021 static int md_notify_reboot(struct notifier_block *this,
9022 unsigned long code, void *x)
9024 struct list_head *tmp;
9025 struct mddev *mddev;
9026 int need_delay = 0;
9028 for_each_mddev(mddev, tmp) {
9029 if (mddev_trylock(mddev)) {
9030 if (mddev->pers)
9031 __md_stop_writes(mddev);
9032 if (mddev->persistent)
9033 mddev->safemode = 2;
9034 mddev_unlock(mddev);
9036 need_delay = 1;
9039 * certain more exotic SCSI devices are known to be
9040 * volatile wrt too early system reboots. While the
9041 * right place to handle this issue is the given
9042 * driver, we do want to have a safe RAID driver ...
9044 if (need_delay)
9045 mdelay(1000*1);
9047 return NOTIFY_DONE;
9050 static struct notifier_block md_notifier = {
9051 .notifier_call = md_notify_reboot,
9052 .next = NULL,
9053 .priority = INT_MAX, /* before any real devices */
9056 static void md_geninit(void)
9058 pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
9060 proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
9063 static int __init md_init(void)
9065 int ret = -ENOMEM;
9067 md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
9068 if (!md_wq)
9069 goto err_wq;
9071 md_misc_wq = alloc_workqueue("md_misc", 0, 0);
9072 if (!md_misc_wq)
9073 goto err_misc_wq;
9075 if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
9076 goto err_md;
9078 if ((ret = register_blkdev(0, "mdp")) < 0)
9079 goto err_mdp;
9080 mdp_major = ret;
9082 blk_register_region(MKDEV(MD_MAJOR, 0), 512, THIS_MODULE,
9083 md_probe, NULL, NULL);
9084 blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
9085 md_probe, NULL, NULL);
9087 register_reboot_notifier(&md_notifier);
9088 raid_table_header = register_sysctl_table(raid_root_table);
9090 md_geninit();
9091 return 0;
9093 err_mdp:
9094 unregister_blkdev(MD_MAJOR, "md");
9095 err_md:
9096 destroy_workqueue(md_misc_wq);
9097 err_misc_wq:
9098 destroy_workqueue(md_wq);
9099 err_wq:
9100 return ret;
9103 static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
9105 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
9106 struct md_rdev *rdev2;
9107 int role, ret;
9108 char b[BDEVNAME_SIZE];
9111 * If size is changed in another node then we need to
9112 * do resize as well.
9114 if (mddev->dev_sectors != le64_to_cpu(sb->size)) {
9115 ret = mddev->pers->resize(mddev, le64_to_cpu(sb->size));
9116 if (ret)
9117 pr_info("md-cluster: resize failed\n");
9118 else
9119 bitmap_update_sb(mddev->bitmap);
9122 /* Check for change of roles in the active devices */
9123 rdev_for_each(rdev2, mddev) {
9124 if (test_bit(Faulty, &rdev2->flags))
9125 continue;
9127 /* Check if the roles changed */
9128 role = le16_to_cpu(sb->dev_roles[rdev2->desc_nr]);
9130 if (test_bit(Candidate, &rdev2->flags)) {
9131 if (role == 0xfffe) {
9132 pr_info("md: Removing Candidate device %s because add failed\n", bdevname(rdev2->bdev,b));
9133 md_kick_rdev_from_array(rdev2);
9134 continue;
9136 else
9137 clear_bit(Candidate, &rdev2->flags);
9140 if (role != rdev2->raid_disk) {
9141 /* got activated */
9142 if (rdev2->raid_disk == -1 && role != 0xffff) {
9143 rdev2->saved_raid_disk = role;
9144 ret = remove_and_add_spares(mddev, rdev2);
9145 pr_info("Activated spare: %s\n",
9146 bdevname(rdev2->bdev,b));
9147 /* wakeup mddev->thread here, so array could
9148 * perform resync with the new activated disk */
9149 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9150 md_wakeup_thread(mddev->thread);
9153 /* device faulty
9154 * We just want to do the minimum to mark the disk
9155 * as faulty. The recovery is performed by the
9156 * one who initiated the error.
9158 if ((role == 0xfffe) || (role == 0xfffd)) {
9159 md_error(mddev, rdev2);
9160 clear_bit(Blocked, &rdev2->flags);
9165 if (mddev->raid_disks != le32_to_cpu(sb->raid_disks))
9166 update_raid_disks(mddev, le32_to_cpu(sb->raid_disks));
9168 /* Finally set the event to be up to date */
9169 mddev->events = le64_to_cpu(sb->events);
9172 static int read_rdev(struct mddev *mddev, struct md_rdev *rdev)
9174 int err;
9175 struct page *swapout = rdev->sb_page;
9176 struct mdp_superblock_1 *sb;
9178 /* Store the sb page of the rdev in the swapout temporary
9179 * variable in case we err in the future
9181 rdev->sb_page = NULL;
9182 err = alloc_disk_sb(rdev);
9183 if (err == 0) {
9184 ClearPageUptodate(rdev->sb_page);
9185 rdev->sb_loaded = 0;
9186 err = super_types[mddev->major_version].
9187 load_super(rdev, NULL, mddev->minor_version);
9189 if (err < 0) {
9190 pr_warn("%s: %d Could not reload rdev(%d) err: %d. Restoring old values\n",
9191 __func__, __LINE__, rdev->desc_nr, err);
9192 if (rdev->sb_page)
9193 put_page(rdev->sb_page);
9194 rdev->sb_page = swapout;
9195 rdev->sb_loaded = 1;
9196 return err;
9199 sb = page_address(rdev->sb_page);
9200 /* Read the offset unconditionally, even if MD_FEATURE_RECOVERY_OFFSET
9201 * is not set
9204 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET))
9205 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
9207 /* The other node finished recovery, call spare_active to set
9208 * device In_sync and mddev->degraded
9210 if (rdev->recovery_offset == MaxSector &&
9211 !test_bit(In_sync, &rdev->flags) &&
9212 mddev->pers->spare_active(mddev))
9213 sysfs_notify(&mddev->kobj, NULL, "degraded");
9215 put_page(swapout);
9216 return 0;
9219 void md_reload_sb(struct mddev *mddev, int nr)
9221 struct md_rdev *rdev;
9222 int err;
9224 /* Find the rdev */
9225 rdev_for_each_rcu(rdev, mddev) {
9226 if (rdev->desc_nr == nr)
9227 break;
9230 if (!rdev || rdev->desc_nr != nr) {
9231 pr_warn("%s: %d Could not find rdev with nr %d\n", __func__, __LINE__, nr);
9232 return;
9235 err = read_rdev(mddev, rdev);
9236 if (err < 0)
9237 return;
9239 check_sb_changes(mddev, rdev);
9241 /* Read all rdev's to update recovery_offset */
9242 rdev_for_each_rcu(rdev, mddev)
9243 read_rdev(mddev, rdev);
9245 EXPORT_SYMBOL(md_reload_sb);
9247 #ifndef MODULE
9250 * Searches all registered partitions for autorun RAID arrays
9251 * at boot time.
9254 static DEFINE_MUTEX(detected_devices_mutex);
9255 static LIST_HEAD(all_detected_devices);
9256 struct detected_devices_node {
9257 struct list_head list;
9258 dev_t dev;
9261 void md_autodetect_dev(dev_t dev)
9263 struct detected_devices_node *node_detected_dev;
9265 node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
9266 if (node_detected_dev) {
9267 node_detected_dev->dev = dev;
9268 mutex_lock(&detected_devices_mutex);
9269 list_add_tail(&node_detected_dev->list, &all_detected_devices);
9270 mutex_unlock(&detected_devices_mutex);
9274 static void autostart_arrays(int part)
9276 struct md_rdev *rdev;
9277 struct detected_devices_node *node_detected_dev;
9278 dev_t dev;
9279 int i_scanned, i_passed;
9281 i_scanned = 0;
9282 i_passed = 0;
9284 pr_info("md: Autodetecting RAID arrays.\n");
9286 mutex_lock(&detected_devices_mutex);
9287 while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
9288 i_scanned++;
9289 node_detected_dev = list_entry(all_detected_devices.next,
9290 struct detected_devices_node, list);
9291 list_del(&node_detected_dev->list);
9292 dev = node_detected_dev->dev;
9293 kfree(node_detected_dev);
9294 mutex_unlock(&detected_devices_mutex);
9295 rdev = md_import_device(dev,0, 90);
9296 mutex_lock(&detected_devices_mutex);
9297 if (IS_ERR(rdev))
9298 continue;
9300 if (test_bit(Faulty, &rdev->flags))
9301 continue;
9303 set_bit(AutoDetected, &rdev->flags);
9304 list_add(&rdev->same_set, &pending_raid_disks);
9305 i_passed++;
9307 mutex_unlock(&detected_devices_mutex);
9309 pr_debug("md: Scanned %d and added %d devices.\n", i_scanned, i_passed);
9311 autorun_devices(part);
9314 #endif /* !MODULE */
9316 static __exit void md_exit(void)
9318 struct mddev *mddev;
9319 struct list_head *tmp;
9320 int delay = 1;
9322 blk_unregister_region(MKDEV(MD_MAJOR,0), 512);
9323 blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
9325 unregister_blkdev(MD_MAJOR,"md");
9326 unregister_blkdev(mdp_major, "mdp");
9327 unregister_reboot_notifier(&md_notifier);
9328 unregister_sysctl_table(raid_table_header);
9330 /* We cannot unload the modules while some process is
9331 * waiting for us in select() or poll() - wake them up
9333 md_unloading = 1;
9334 while (waitqueue_active(&md_event_waiters)) {
9335 /* not safe to leave yet */
9336 wake_up(&md_event_waiters);
9337 msleep(delay);
9338 delay += delay;
9340 remove_proc_entry("mdstat", NULL);
9342 for_each_mddev(mddev, tmp) {
9343 export_array(mddev);
9344 mddev->ctime = 0;
9345 mddev->hold_active = 0;
9347 * for_each_mddev() will call mddev_put() at the end of each
9348 * iteration. As the mddev is now fully clear, this will
9349 * schedule the mddev for destruction by a workqueue, and the
9350 * destroy_workqueue() below will wait for that to complete.
9353 destroy_workqueue(md_misc_wq);
9354 destroy_workqueue(md_wq);
9357 subsys_initcall(md_init);
9358 module_exit(md_exit)
9360 static int get_ro(char *buffer, struct kernel_param *kp)
9362 return sprintf(buffer, "%d", start_readonly);
9364 static int set_ro(const char *val, struct kernel_param *kp)
9366 return kstrtouint(val, 10, (unsigned int *)&start_readonly);
9369 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
9370 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
9371 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
9372 module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
9374 MODULE_LICENSE("GPL");
9375 MODULE_DESCRIPTION("MD RAID framework");
9376 MODULE_ALIAS("md");
9377 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);