x86/topology: Fix function name in documentation
[cris-mirror.git] / drivers / md / md.c
blobbc67ab6844f02d540cf4ae3725ebdad13ee568b8
1 /*
2 md.c : Multiple Devices driver for Linux
3 Copyright (C) 1998, 1999, 2000 Ingo Molnar
5 completely rewritten, based on the MD driver code from Marc Zyngier
7 Changes:
9 - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
10 - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
11 - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
12 - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
13 - kmod support by: Cyrus Durgin
14 - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
15 - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
17 - lots of fixes and improvements to the RAID1/RAID5 and generic
18 RAID code (such as request based resynchronization):
20 Neil Brown <neilb@cse.unsw.edu.au>.
22 - persistent bitmap code
23 Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
25 This program is free software; you can redistribute it and/or modify
26 it under the terms of the GNU General Public License as published by
27 the Free Software Foundation; either version 2, or (at your option)
28 any later version.
30 You should have received a copy of the GNU General Public License
31 (for example /usr/src/linux/COPYING); if not, write to the Free
32 Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
34 Errors, Warnings, etc.
35 Please use:
36 pr_crit() for error conditions that risk data loss
37 pr_err() for error conditions that are unexpected, like an IO error
38 or internal inconsistency
39 pr_warn() for error conditions that could have been predicated, like
40 adding a device to an array when it has incompatible metadata
41 pr_info() for every interesting, very rare events, like an array starting
42 or stopping, or resync starting or stopping
43 pr_debug() for everything else.
47 #include <linux/sched/signal.h>
48 #include <linux/kthread.h>
49 #include <linux/blkdev.h>
50 #include <linux/badblocks.h>
51 #include <linux/sysctl.h>
52 #include <linux/seq_file.h>
53 #include <linux/fs.h>
54 #include <linux/poll.h>
55 #include <linux/ctype.h>
56 #include <linux/string.h>
57 #include <linux/hdreg.h>
58 #include <linux/proc_fs.h>
59 #include <linux/random.h>
60 #include <linux/module.h>
61 #include <linux/reboot.h>
62 #include <linux/file.h>
63 #include <linux/compat.h>
64 #include <linux/delay.h>
65 #include <linux/raid/md_p.h>
66 #include <linux/raid/md_u.h>
67 #include <linux/slab.h>
68 #include <linux/percpu-refcount.h>
70 #include <trace/events/block.h>
71 #include "md.h"
72 #include "md-bitmap.h"
73 #include "md-cluster.h"
75 #ifndef MODULE
76 static void autostart_arrays(int part);
77 #endif
79 /* pers_list is a list of registered personalities protected
80 * by pers_lock.
81 * pers_lock does extra service to protect accesses to
82 * mddev->thread when the mutex cannot be held.
84 static LIST_HEAD(pers_list);
85 static DEFINE_SPINLOCK(pers_lock);
87 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(struct timer_list *t);
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 timer_setup(&mddev->safemode_timer, md_safemode_timeout, 0);
554 atomic_set(&mddev->active, 1);
555 atomic_set(&mddev->openers, 0);
556 atomic_set(&mddev->active_io, 0);
557 spin_lock_init(&mddev->lock);
558 atomic_set(&mddev->flush_pending, 0);
559 init_waitqueue_head(&mddev->sb_wait);
560 init_waitqueue_head(&mddev->recovery_wait);
561 mddev->reshape_position = MaxSector;
562 mddev->reshape_backwards = 0;
563 mddev->last_sync_action = "none";
564 mddev->resync_min = 0;
565 mddev->resync_max = MaxSector;
566 mddev->level = LEVEL_NONE;
568 EXPORT_SYMBOL_GPL(mddev_init);
570 static struct mddev *mddev_find(dev_t unit)
572 struct mddev *mddev, *new = NULL;
574 if (unit && MAJOR(unit) != MD_MAJOR)
575 unit &= ~((1<<MdpMinorShift)-1);
577 retry:
578 spin_lock(&all_mddevs_lock);
580 if (unit) {
581 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
582 if (mddev->unit == unit) {
583 mddev_get(mddev);
584 spin_unlock(&all_mddevs_lock);
585 kfree(new);
586 return mddev;
589 if (new) {
590 list_add(&new->all_mddevs, &all_mddevs);
591 spin_unlock(&all_mddevs_lock);
592 new->hold_active = UNTIL_IOCTL;
593 return new;
595 } else if (new) {
596 /* find an unused unit number */
597 static int next_minor = 512;
598 int start = next_minor;
599 int is_free = 0;
600 int dev = 0;
601 while (!is_free) {
602 dev = MKDEV(MD_MAJOR, next_minor);
603 next_minor++;
604 if (next_minor > MINORMASK)
605 next_minor = 0;
606 if (next_minor == start) {
607 /* Oh dear, all in use. */
608 spin_unlock(&all_mddevs_lock);
609 kfree(new);
610 return NULL;
613 is_free = 1;
614 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
615 if (mddev->unit == dev) {
616 is_free = 0;
617 break;
620 new->unit = dev;
621 new->md_minor = MINOR(dev);
622 new->hold_active = UNTIL_STOP;
623 list_add(&new->all_mddevs, &all_mddevs);
624 spin_unlock(&all_mddevs_lock);
625 return new;
627 spin_unlock(&all_mddevs_lock);
629 new = kzalloc(sizeof(*new), GFP_KERNEL);
630 if (!new)
631 return NULL;
633 new->unit = unit;
634 if (MAJOR(unit) == MD_MAJOR)
635 new->md_minor = MINOR(unit);
636 else
637 new->md_minor = MINOR(unit) >> MdpMinorShift;
639 mddev_init(new);
641 goto retry;
644 static struct attribute_group md_redundancy_group;
646 void mddev_unlock(struct mddev *mddev)
648 if (mddev->to_remove) {
649 /* These cannot be removed under reconfig_mutex as
650 * an access to the files will try to take reconfig_mutex
651 * while holding the file unremovable, which leads to
652 * a deadlock.
653 * So hold set sysfs_active while the remove in happeing,
654 * and anything else which might set ->to_remove or my
655 * otherwise change the sysfs namespace will fail with
656 * -EBUSY if sysfs_active is still set.
657 * We set sysfs_active under reconfig_mutex and elsewhere
658 * test it under the same mutex to ensure its correct value
659 * is seen.
661 struct attribute_group *to_remove = mddev->to_remove;
662 mddev->to_remove = NULL;
663 mddev->sysfs_active = 1;
664 mutex_unlock(&mddev->reconfig_mutex);
666 if (mddev->kobj.sd) {
667 if (to_remove != &md_redundancy_group)
668 sysfs_remove_group(&mddev->kobj, to_remove);
669 if (mddev->pers == NULL ||
670 mddev->pers->sync_request == NULL) {
671 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
672 if (mddev->sysfs_action)
673 sysfs_put(mddev->sysfs_action);
674 mddev->sysfs_action = NULL;
677 mddev->sysfs_active = 0;
678 } else
679 mutex_unlock(&mddev->reconfig_mutex);
681 /* As we've dropped the mutex we need a spinlock to
682 * make sure the thread doesn't disappear
684 spin_lock(&pers_lock);
685 md_wakeup_thread(mddev->thread);
686 wake_up(&mddev->sb_wait);
687 spin_unlock(&pers_lock);
689 EXPORT_SYMBOL_GPL(mddev_unlock);
691 struct md_rdev *md_find_rdev_nr_rcu(struct mddev *mddev, int nr)
693 struct md_rdev *rdev;
695 rdev_for_each_rcu(rdev, mddev)
696 if (rdev->desc_nr == nr)
697 return rdev;
699 return NULL;
701 EXPORT_SYMBOL_GPL(md_find_rdev_nr_rcu);
703 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
705 struct md_rdev *rdev;
707 rdev_for_each(rdev, mddev)
708 if (rdev->bdev->bd_dev == dev)
709 return rdev;
711 return NULL;
714 struct md_rdev *md_find_rdev_rcu(struct mddev *mddev, dev_t dev)
716 struct md_rdev *rdev;
718 rdev_for_each_rcu(rdev, mddev)
719 if (rdev->bdev->bd_dev == dev)
720 return rdev;
722 return NULL;
724 EXPORT_SYMBOL_GPL(md_find_rdev_rcu);
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 (test_bit(Faulty, &rdev->flags))
805 return;
807 bio = md_bio_alloc_sync(mddev);
809 atomic_inc(&rdev->nr_pending);
811 bio_set_dev(bio, rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev);
812 bio->bi_iter.bi_sector = sector;
813 bio_add_page(bio, page, size, 0);
814 bio->bi_private = rdev;
815 bio->bi_end_io = super_written;
817 if (test_bit(MD_FAILFAST_SUPPORTED, &mddev->flags) &&
818 test_bit(FailFast, &rdev->flags) &&
819 !test_bit(LastDev, &rdev->flags))
820 ff = MD_FAILFAST;
821 bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH | REQ_FUA | ff;
823 atomic_inc(&mddev->pending_writes);
824 submit_bio(bio);
827 int md_super_wait(struct mddev *mddev)
829 /* wait for all superblock writes that were scheduled to complete */
830 wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
831 if (test_and_clear_bit(MD_SB_NEED_REWRITE, &mddev->sb_flags))
832 return -EAGAIN;
833 return 0;
836 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
837 struct page *page, int op, int op_flags, bool metadata_op)
839 struct bio *bio = md_bio_alloc_sync(rdev->mddev);
840 int ret;
842 if (metadata_op && rdev->meta_bdev)
843 bio_set_dev(bio, rdev->meta_bdev);
844 else
845 bio_set_dev(bio, rdev->bdev);
846 bio_set_op_attrs(bio, op, op_flags);
847 if (metadata_op)
848 bio->bi_iter.bi_sector = sector + rdev->sb_start;
849 else if (rdev->mddev->reshape_position != MaxSector &&
850 (rdev->mddev->reshape_backwards ==
851 (sector >= rdev->mddev->reshape_position)))
852 bio->bi_iter.bi_sector = sector + rdev->new_data_offset;
853 else
854 bio->bi_iter.bi_sector = sector + rdev->data_offset;
855 bio_add_page(bio, page, size, 0);
857 submit_bio_wait(bio);
859 ret = !bio->bi_status;
860 bio_put(bio);
861 return ret;
863 EXPORT_SYMBOL_GPL(sync_page_io);
865 static int read_disk_sb(struct md_rdev *rdev, int size)
867 char b[BDEVNAME_SIZE];
869 if (rdev->sb_loaded)
870 return 0;
872 if (!sync_page_io(rdev, 0, size, rdev->sb_page, REQ_OP_READ, 0, true))
873 goto fail;
874 rdev->sb_loaded = 1;
875 return 0;
877 fail:
878 pr_err("md: disabled device %s, could not read superblock.\n",
879 bdevname(rdev->bdev,b));
880 return -EINVAL;
883 static int md_uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
885 return sb1->set_uuid0 == sb2->set_uuid0 &&
886 sb1->set_uuid1 == sb2->set_uuid1 &&
887 sb1->set_uuid2 == sb2->set_uuid2 &&
888 sb1->set_uuid3 == sb2->set_uuid3;
891 static int md_sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
893 int ret;
894 mdp_super_t *tmp1, *tmp2;
896 tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
897 tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
899 if (!tmp1 || !tmp2) {
900 ret = 0;
901 goto abort;
904 *tmp1 = *sb1;
905 *tmp2 = *sb2;
908 * nr_disks is not constant
910 tmp1->nr_disks = 0;
911 tmp2->nr_disks = 0;
913 ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
914 abort:
915 kfree(tmp1);
916 kfree(tmp2);
917 return ret;
920 static u32 md_csum_fold(u32 csum)
922 csum = (csum & 0xffff) + (csum >> 16);
923 return (csum & 0xffff) + (csum >> 16);
926 static unsigned int calc_sb_csum(mdp_super_t *sb)
928 u64 newcsum = 0;
929 u32 *sb32 = (u32*)sb;
930 int i;
931 unsigned int disk_csum, csum;
933 disk_csum = sb->sb_csum;
934 sb->sb_csum = 0;
936 for (i = 0; i < MD_SB_BYTES/4 ; i++)
937 newcsum += sb32[i];
938 csum = (newcsum & 0xffffffff) + (newcsum>>32);
940 #ifdef CONFIG_ALPHA
941 /* This used to use csum_partial, which was wrong for several
942 * reasons including that different results are returned on
943 * different architectures. It isn't critical that we get exactly
944 * the same return value as before (we always csum_fold before
945 * testing, and that removes any differences). However as we
946 * know that csum_partial always returned a 16bit value on
947 * alphas, do a fold to maximise conformity to previous behaviour.
949 sb->sb_csum = md_csum_fold(disk_csum);
950 #else
951 sb->sb_csum = disk_csum;
952 #endif
953 return csum;
957 * Handle superblock details.
958 * We want to be able to handle multiple superblock formats
959 * so we have a common interface to them all, and an array of
960 * different handlers.
961 * We rely on user-space to write the initial superblock, and support
962 * reading and updating of superblocks.
963 * Interface methods are:
964 * int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
965 * loads and validates a superblock on dev.
966 * if refdev != NULL, compare superblocks on both devices
967 * Return:
968 * 0 - dev has a superblock that is compatible with refdev
969 * 1 - dev has a superblock that is compatible and newer than refdev
970 * so dev should be used as the refdev in future
971 * -EINVAL superblock incompatible or invalid
972 * -othererror e.g. -EIO
974 * int validate_super(struct mddev *mddev, struct md_rdev *dev)
975 * Verify that dev is acceptable into mddev.
976 * The first time, mddev->raid_disks will be 0, and data from
977 * dev should be merged in. Subsequent calls check that dev
978 * is new enough. Return 0 or -EINVAL
980 * void sync_super(struct mddev *mddev, struct md_rdev *dev)
981 * Update the superblock for rdev with data in mddev
982 * This does not write to disc.
986 struct super_type {
987 char *name;
988 struct module *owner;
989 int (*load_super)(struct md_rdev *rdev,
990 struct md_rdev *refdev,
991 int minor_version);
992 int (*validate_super)(struct mddev *mddev,
993 struct md_rdev *rdev);
994 void (*sync_super)(struct mddev *mddev,
995 struct md_rdev *rdev);
996 unsigned long long (*rdev_size_change)(struct md_rdev *rdev,
997 sector_t num_sectors);
998 int (*allow_new_offset)(struct md_rdev *rdev,
999 unsigned long long new_offset);
1003 * Check that the given mddev has no bitmap.
1005 * This function is called from the run method of all personalities that do not
1006 * support bitmaps. It prints an error message and returns non-zero if mddev
1007 * has a bitmap. Otherwise, it returns 0.
1010 int md_check_no_bitmap(struct mddev *mddev)
1012 if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1013 return 0;
1014 pr_warn("%s: bitmaps are not supported for %s\n",
1015 mdname(mddev), mddev->pers->name);
1016 return 1;
1018 EXPORT_SYMBOL(md_check_no_bitmap);
1021 * load_super for 0.90.0
1023 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1025 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1026 mdp_super_t *sb;
1027 int ret;
1030 * Calculate the position of the superblock (512byte sectors),
1031 * it's at the end of the disk.
1033 * It also happens to be a multiple of 4Kb.
1035 rdev->sb_start = calc_dev_sboffset(rdev);
1037 ret = read_disk_sb(rdev, MD_SB_BYTES);
1038 if (ret)
1039 return ret;
1041 ret = -EINVAL;
1043 bdevname(rdev->bdev, b);
1044 sb = page_address(rdev->sb_page);
1046 if (sb->md_magic != MD_SB_MAGIC) {
1047 pr_warn("md: invalid raid superblock magic on %s\n", b);
1048 goto abort;
1051 if (sb->major_version != 0 ||
1052 sb->minor_version < 90 ||
1053 sb->minor_version > 91) {
1054 pr_warn("Bad version number %d.%d on %s\n",
1055 sb->major_version, sb->minor_version, b);
1056 goto abort;
1059 if (sb->raid_disks <= 0)
1060 goto abort;
1062 if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1063 pr_warn("md: invalid superblock checksum on %s\n", b);
1064 goto abort;
1067 rdev->preferred_minor = sb->md_minor;
1068 rdev->data_offset = 0;
1069 rdev->new_data_offset = 0;
1070 rdev->sb_size = MD_SB_BYTES;
1071 rdev->badblocks.shift = -1;
1073 if (sb->level == LEVEL_MULTIPATH)
1074 rdev->desc_nr = -1;
1075 else
1076 rdev->desc_nr = sb->this_disk.number;
1078 if (!refdev) {
1079 ret = 1;
1080 } else {
1081 __u64 ev1, ev2;
1082 mdp_super_t *refsb = page_address(refdev->sb_page);
1083 if (!md_uuid_equal(refsb, sb)) {
1084 pr_warn("md: %s has different UUID to %s\n",
1085 b, bdevname(refdev->bdev,b2));
1086 goto abort;
1088 if (!md_sb_equal(refsb, sb)) {
1089 pr_warn("md: %s has same UUID but different superblock to %s\n",
1090 b, bdevname(refdev->bdev, b2));
1091 goto abort;
1093 ev1 = md_event(sb);
1094 ev2 = md_event(refsb);
1095 if (ev1 > ev2)
1096 ret = 1;
1097 else
1098 ret = 0;
1100 rdev->sectors = rdev->sb_start;
1101 /* Limit to 4TB as metadata cannot record more than that.
1102 * (not needed for Linear and RAID0 as metadata doesn't
1103 * record this size)
1105 if (IS_ENABLED(CONFIG_LBDAF) && (u64)rdev->sectors >= (2ULL << 32) &&
1106 sb->level >= 1)
1107 rdev->sectors = (sector_t)(2ULL << 32) - 2;
1109 if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1110 /* "this cannot possibly happen" ... */
1111 ret = -EINVAL;
1113 abort:
1114 return ret;
1118 * validate_super for 0.90.0
1120 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1122 mdp_disk_t *desc;
1123 mdp_super_t *sb = page_address(rdev->sb_page);
1124 __u64 ev1 = md_event(sb);
1126 rdev->raid_disk = -1;
1127 clear_bit(Faulty, &rdev->flags);
1128 clear_bit(In_sync, &rdev->flags);
1129 clear_bit(Bitmap_sync, &rdev->flags);
1130 clear_bit(WriteMostly, &rdev->flags);
1132 if (mddev->raid_disks == 0) {
1133 mddev->major_version = 0;
1134 mddev->minor_version = sb->minor_version;
1135 mddev->patch_version = sb->patch_version;
1136 mddev->external = 0;
1137 mddev->chunk_sectors = sb->chunk_size >> 9;
1138 mddev->ctime = sb->ctime;
1139 mddev->utime = sb->utime;
1140 mddev->level = sb->level;
1141 mddev->clevel[0] = 0;
1142 mddev->layout = sb->layout;
1143 mddev->raid_disks = sb->raid_disks;
1144 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1145 mddev->events = ev1;
1146 mddev->bitmap_info.offset = 0;
1147 mddev->bitmap_info.space = 0;
1148 /* bitmap can use 60 K after the 4K superblocks */
1149 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1150 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1151 mddev->reshape_backwards = 0;
1153 if (mddev->minor_version >= 91) {
1154 mddev->reshape_position = sb->reshape_position;
1155 mddev->delta_disks = sb->delta_disks;
1156 mddev->new_level = sb->new_level;
1157 mddev->new_layout = sb->new_layout;
1158 mddev->new_chunk_sectors = sb->new_chunk >> 9;
1159 if (mddev->delta_disks < 0)
1160 mddev->reshape_backwards = 1;
1161 } else {
1162 mddev->reshape_position = MaxSector;
1163 mddev->delta_disks = 0;
1164 mddev->new_level = mddev->level;
1165 mddev->new_layout = mddev->layout;
1166 mddev->new_chunk_sectors = mddev->chunk_sectors;
1169 if (sb->state & (1<<MD_SB_CLEAN))
1170 mddev->recovery_cp = MaxSector;
1171 else {
1172 if (sb->events_hi == sb->cp_events_hi &&
1173 sb->events_lo == sb->cp_events_lo) {
1174 mddev->recovery_cp = sb->recovery_cp;
1175 } else
1176 mddev->recovery_cp = 0;
1179 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1180 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1181 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1182 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1184 mddev->max_disks = MD_SB_DISKS;
1186 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1187 mddev->bitmap_info.file == NULL) {
1188 mddev->bitmap_info.offset =
1189 mddev->bitmap_info.default_offset;
1190 mddev->bitmap_info.space =
1191 mddev->bitmap_info.default_space;
1194 } else if (mddev->pers == NULL) {
1195 /* Insist on good event counter while assembling, except
1196 * for spares (which don't need an event count) */
1197 ++ev1;
1198 if (sb->disks[rdev->desc_nr].state & (
1199 (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1200 if (ev1 < mddev->events)
1201 return -EINVAL;
1202 } else if (mddev->bitmap) {
1203 /* if adding to array with a bitmap, then we can accept an
1204 * older device ... but not too old.
1206 if (ev1 < mddev->bitmap->events_cleared)
1207 return 0;
1208 if (ev1 < mddev->events)
1209 set_bit(Bitmap_sync, &rdev->flags);
1210 } else {
1211 if (ev1 < mddev->events)
1212 /* just a hot-add of a new device, leave raid_disk at -1 */
1213 return 0;
1216 if (mddev->level != LEVEL_MULTIPATH) {
1217 desc = sb->disks + rdev->desc_nr;
1219 if (desc->state & (1<<MD_DISK_FAULTY))
1220 set_bit(Faulty, &rdev->flags);
1221 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1222 desc->raid_disk < mddev->raid_disks */) {
1223 set_bit(In_sync, &rdev->flags);
1224 rdev->raid_disk = desc->raid_disk;
1225 rdev->saved_raid_disk = desc->raid_disk;
1226 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1227 /* active but not in sync implies recovery up to
1228 * reshape position. We don't know exactly where
1229 * that is, so set to zero for now */
1230 if (mddev->minor_version >= 91) {
1231 rdev->recovery_offset = 0;
1232 rdev->raid_disk = desc->raid_disk;
1235 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1236 set_bit(WriteMostly, &rdev->flags);
1237 if (desc->state & (1<<MD_DISK_FAILFAST))
1238 set_bit(FailFast, &rdev->flags);
1239 } else /* MULTIPATH are always insync */
1240 set_bit(In_sync, &rdev->flags);
1241 return 0;
1245 * sync_super for 0.90.0
1247 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1249 mdp_super_t *sb;
1250 struct md_rdev *rdev2;
1251 int next_spare = mddev->raid_disks;
1253 /* make rdev->sb match mddev data..
1255 * 1/ zero out disks
1256 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1257 * 3/ any empty disks < next_spare become removed
1259 * disks[0] gets initialised to REMOVED because
1260 * we cannot be sure from other fields if it has
1261 * been initialised or not.
1263 int i;
1264 int active=0, working=0,failed=0,spare=0,nr_disks=0;
1266 rdev->sb_size = MD_SB_BYTES;
1268 sb = page_address(rdev->sb_page);
1270 memset(sb, 0, sizeof(*sb));
1272 sb->md_magic = MD_SB_MAGIC;
1273 sb->major_version = mddev->major_version;
1274 sb->patch_version = mddev->patch_version;
1275 sb->gvalid_words = 0; /* ignored */
1276 memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1277 memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1278 memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1279 memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1281 sb->ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
1282 sb->level = mddev->level;
1283 sb->size = mddev->dev_sectors / 2;
1284 sb->raid_disks = mddev->raid_disks;
1285 sb->md_minor = mddev->md_minor;
1286 sb->not_persistent = 0;
1287 sb->utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
1288 sb->state = 0;
1289 sb->events_hi = (mddev->events>>32);
1290 sb->events_lo = (u32)mddev->events;
1292 if (mddev->reshape_position == MaxSector)
1293 sb->minor_version = 90;
1294 else {
1295 sb->minor_version = 91;
1296 sb->reshape_position = mddev->reshape_position;
1297 sb->new_level = mddev->new_level;
1298 sb->delta_disks = mddev->delta_disks;
1299 sb->new_layout = mddev->new_layout;
1300 sb->new_chunk = mddev->new_chunk_sectors << 9;
1302 mddev->minor_version = sb->minor_version;
1303 if (mddev->in_sync)
1305 sb->recovery_cp = mddev->recovery_cp;
1306 sb->cp_events_hi = (mddev->events>>32);
1307 sb->cp_events_lo = (u32)mddev->events;
1308 if (mddev->recovery_cp == MaxSector)
1309 sb->state = (1<< MD_SB_CLEAN);
1310 } else
1311 sb->recovery_cp = 0;
1313 sb->layout = mddev->layout;
1314 sb->chunk_size = mddev->chunk_sectors << 9;
1316 if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1317 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1319 sb->disks[0].state = (1<<MD_DISK_REMOVED);
1320 rdev_for_each(rdev2, mddev) {
1321 mdp_disk_t *d;
1322 int desc_nr;
1323 int is_active = test_bit(In_sync, &rdev2->flags);
1325 if (rdev2->raid_disk >= 0 &&
1326 sb->minor_version >= 91)
1327 /* we have nowhere to store the recovery_offset,
1328 * but if it is not below the reshape_position,
1329 * we can piggy-back on that.
1331 is_active = 1;
1332 if (rdev2->raid_disk < 0 ||
1333 test_bit(Faulty, &rdev2->flags))
1334 is_active = 0;
1335 if (is_active)
1336 desc_nr = rdev2->raid_disk;
1337 else
1338 desc_nr = next_spare++;
1339 rdev2->desc_nr = desc_nr;
1340 d = &sb->disks[rdev2->desc_nr];
1341 nr_disks++;
1342 d->number = rdev2->desc_nr;
1343 d->major = MAJOR(rdev2->bdev->bd_dev);
1344 d->minor = MINOR(rdev2->bdev->bd_dev);
1345 if (is_active)
1346 d->raid_disk = rdev2->raid_disk;
1347 else
1348 d->raid_disk = rdev2->desc_nr; /* compatibility */
1349 if (test_bit(Faulty, &rdev2->flags))
1350 d->state = (1<<MD_DISK_FAULTY);
1351 else if (is_active) {
1352 d->state = (1<<MD_DISK_ACTIVE);
1353 if (test_bit(In_sync, &rdev2->flags))
1354 d->state |= (1<<MD_DISK_SYNC);
1355 active++;
1356 working++;
1357 } else {
1358 d->state = 0;
1359 spare++;
1360 working++;
1362 if (test_bit(WriteMostly, &rdev2->flags))
1363 d->state |= (1<<MD_DISK_WRITEMOSTLY);
1364 if (test_bit(FailFast, &rdev2->flags))
1365 d->state |= (1<<MD_DISK_FAILFAST);
1367 /* now set the "removed" and "faulty" bits on any missing devices */
1368 for (i=0 ; i < mddev->raid_disks ; i++) {
1369 mdp_disk_t *d = &sb->disks[i];
1370 if (d->state == 0 && d->number == 0) {
1371 d->number = i;
1372 d->raid_disk = i;
1373 d->state = (1<<MD_DISK_REMOVED);
1374 d->state |= (1<<MD_DISK_FAULTY);
1375 failed++;
1378 sb->nr_disks = nr_disks;
1379 sb->active_disks = active;
1380 sb->working_disks = working;
1381 sb->failed_disks = failed;
1382 sb->spare_disks = spare;
1384 sb->this_disk = sb->disks[rdev->desc_nr];
1385 sb->sb_csum = calc_sb_csum(sb);
1389 * rdev_size_change for 0.90.0
1391 static unsigned long long
1392 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1394 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1395 return 0; /* component must fit device */
1396 if (rdev->mddev->bitmap_info.offset)
1397 return 0; /* can't move bitmap */
1398 rdev->sb_start = calc_dev_sboffset(rdev);
1399 if (!num_sectors || num_sectors > rdev->sb_start)
1400 num_sectors = rdev->sb_start;
1401 /* Limit to 4TB as metadata cannot record more than that.
1402 * 4TB == 2^32 KB, or 2*2^32 sectors.
1404 if (IS_ENABLED(CONFIG_LBDAF) && (u64)num_sectors >= (2ULL << 32) &&
1405 rdev->mddev->level >= 1)
1406 num_sectors = (sector_t)(2ULL << 32) - 2;
1407 do {
1408 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1409 rdev->sb_page);
1410 } while (md_super_wait(rdev->mddev) < 0);
1411 return num_sectors;
1414 static int
1415 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1417 /* non-zero offset changes not possible with v0.90 */
1418 return new_offset == 0;
1422 * version 1 superblock
1425 static __le32 calc_sb_1_csum(struct mdp_superblock_1 *sb)
1427 __le32 disk_csum;
1428 u32 csum;
1429 unsigned long long newcsum;
1430 int size = 256 + le32_to_cpu(sb->max_dev)*2;
1431 __le32 *isuper = (__le32*)sb;
1433 disk_csum = sb->sb_csum;
1434 sb->sb_csum = 0;
1435 newcsum = 0;
1436 for (; size >= 4; size -= 4)
1437 newcsum += le32_to_cpu(*isuper++);
1439 if (size == 2)
1440 newcsum += le16_to_cpu(*(__le16*) isuper);
1442 csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1443 sb->sb_csum = disk_csum;
1444 return cpu_to_le32(csum);
1447 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1449 struct mdp_superblock_1 *sb;
1450 int ret;
1451 sector_t sb_start;
1452 sector_t sectors;
1453 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1454 int bmask;
1457 * Calculate the position of the superblock in 512byte sectors.
1458 * It is always aligned to a 4K boundary and
1459 * depeding on minor_version, it can be:
1460 * 0: At least 8K, but less than 12K, from end of device
1461 * 1: At start of device
1462 * 2: 4K from start of device.
1464 switch(minor_version) {
1465 case 0:
1466 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1467 sb_start -= 8*2;
1468 sb_start &= ~(sector_t)(4*2-1);
1469 break;
1470 case 1:
1471 sb_start = 0;
1472 break;
1473 case 2:
1474 sb_start = 8;
1475 break;
1476 default:
1477 return -EINVAL;
1479 rdev->sb_start = sb_start;
1481 /* superblock is rarely larger than 1K, but it can be larger,
1482 * and it is safe to read 4k, so we do that
1484 ret = read_disk_sb(rdev, 4096);
1485 if (ret) return ret;
1487 sb = page_address(rdev->sb_page);
1489 if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1490 sb->major_version != cpu_to_le32(1) ||
1491 le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1492 le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1493 (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1494 return -EINVAL;
1496 if (calc_sb_1_csum(sb) != sb->sb_csum) {
1497 pr_warn("md: invalid superblock checksum on %s\n",
1498 bdevname(rdev->bdev,b));
1499 return -EINVAL;
1501 if (le64_to_cpu(sb->data_size) < 10) {
1502 pr_warn("md: data_size too small on %s\n",
1503 bdevname(rdev->bdev,b));
1504 return -EINVAL;
1506 if (sb->pad0 ||
1507 sb->pad3[0] ||
1508 memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1509 /* Some padding is non-zero, might be a new feature */
1510 return -EINVAL;
1512 rdev->preferred_minor = 0xffff;
1513 rdev->data_offset = le64_to_cpu(sb->data_offset);
1514 rdev->new_data_offset = rdev->data_offset;
1515 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1516 (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1517 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1518 atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1520 rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1521 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1522 if (rdev->sb_size & bmask)
1523 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1525 if (minor_version
1526 && rdev->data_offset < sb_start + (rdev->sb_size/512))
1527 return -EINVAL;
1528 if (minor_version
1529 && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1530 return -EINVAL;
1532 if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1533 rdev->desc_nr = -1;
1534 else
1535 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1537 if (!rdev->bb_page) {
1538 rdev->bb_page = alloc_page(GFP_KERNEL);
1539 if (!rdev->bb_page)
1540 return -ENOMEM;
1542 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1543 rdev->badblocks.count == 0) {
1544 /* need to load the bad block list.
1545 * Currently we limit it to one page.
1547 s32 offset;
1548 sector_t bb_sector;
1549 u64 *bbp;
1550 int i;
1551 int sectors = le16_to_cpu(sb->bblog_size);
1552 if (sectors > (PAGE_SIZE / 512))
1553 return -EINVAL;
1554 offset = le32_to_cpu(sb->bblog_offset);
1555 if (offset == 0)
1556 return -EINVAL;
1557 bb_sector = (long long)offset;
1558 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1559 rdev->bb_page, REQ_OP_READ, 0, true))
1560 return -EIO;
1561 bbp = (u64 *)page_address(rdev->bb_page);
1562 rdev->badblocks.shift = sb->bblog_shift;
1563 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1564 u64 bb = le64_to_cpu(*bbp);
1565 int count = bb & (0x3ff);
1566 u64 sector = bb >> 10;
1567 sector <<= sb->bblog_shift;
1568 count <<= sb->bblog_shift;
1569 if (bb + 1 == 0)
1570 break;
1571 if (badblocks_set(&rdev->badblocks, sector, count, 1))
1572 return -EINVAL;
1574 } else if (sb->bblog_offset != 0)
1575 rdev->badblocks.shift = 0;
1577 if ((le32_to_cpu(sb->feature_map) &
1578 (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS))) {
1579 rdev->ppl.offset = (__s16)le16_to_cpu(sb->ppl.offset);
1580 rdev->ppl.size = le16_to_cpu(sb->ppl.size);
1581 rdev->ppl.sector = rdev->sb_start + rdev->ppl.offset;
1584 if (!refdev) {
1585 ret = 1;
1586 } else {
1587 __u64 ev1, ev2;
1588 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1590 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1591 sb->level != refsb->level ||
1592 sb->layout != refsb->layout ||
1593 sb->chunksize != refsb->chunksize) {
1594 pr_warn("md: %s has strangely different superblock to %s\n",
1595 bdevname(rdev->bdev,b),
1596 bdevname(refdev->bdev,b2));
1597 return -EINVAL;
1599 ev1 = le64_to_cpu(sb->events);
1600 ev2 = le64_to_cpu(refsb->events);
1602 if (ev1 > ev2)
1603 ret = 1;
1604 else
1605 ret = 0;
1607 if (minor_version) {
1608 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1609 sectors -= rdev->data_offset;
1610 } else
1611 sectors = rdev->sb_start;
1612 if (sectors < le64_to_cpu(sb->data_size))
1613 return -EINVAL;
1614 rdev->sectors = le64_to_cpu(sb->data_size);
1615 return ret;
1618 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1620 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1621 __u64 ev1 = le64_to_cpu(sb->events);
1623 rdev->raid_disk = -1;
1624 clear_bit(Faulty, &rdev->flags);
1625 clear_bit(In_sync, &rdev->flags);
1626 clear_bit(Bitmap_sync, &rdev->flags);
1627 clear_bit(WriteMostly, &rdev->flags);
1629 if (mddev->raid_disks == 0) {
1630 mddev->major_version = 1;
1631 mddev->patch_version = 0;
1632 mddev->external = 0;
1633 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1634 mddev->ctime = le64_to_cpu(sb->ctime);
1635 mddev->utime = le64_to_cpu(sb->utime);
1636 mddev->level = le32_to_cpu(sb->level);
1637 mddev->clevel[0] = 0;
1638 mddev->layout = le32_to_cpu(sb->layout);
1639 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1640 mddev->dev_sectors = le64_to_cpu(sb->size);
1641 mddev->events = ev1;
1642 mddev->bitmap_info.offset = 0;
1643 mddev->bitmap_info.space = 0;
1644 /* Default location for bitmap is 1K after superblock
1645 * using 3K - total of 4K
1647 mddev->bitmap_info.default_offset = 1024 >> 9;
1648 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1649 mddev->reshape_backwards = 0;
1651 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1652 memcpy(mddev->uuid, sb->set_uuid, 16);
1654 mddev->max_disks = (4096-256)/2;
1656 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1657 mddev->bitmap_info.file == NULL) {
1658 mddev->bitmap_info.offset =
1659 (__s32)le32_to_cpu(sb->bitmap_offset);
1660 /* Metadata doesn't record how much space is available.
1661 * For 1.0, we assume we can use up to the superblock
1662 * if before, else to 4K beyond superblock.
1663 * For others, assume no change is possible.
1665 if (mddev->minor_version > 0)
1666 mddev->bitmap_info.space = 0;
1667 else if (mddev->bitmap_info.offset > 0)
1668 mddev->bitmap_info.space =
1669 8 - mddev->bitmap_info.offset;
1670 else
1671 mddev->bitmap_info.space =
1672 -mddev->bitmap_info.offset;
1675 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1676 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1677 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1678 mddev->new_level = le32_to_cpu(sb->new_level);
1679 mddev->new_layout = le32_to_cpu(sb->new_layout);
1680 mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1681 if (mddev->delta_disks < 0 ||
1682 (mddev->delta_disks == 0 &&
1683 (le32_to_cpu(sb->feature_map)
1684 & MD_FEATURE_RESHAPE_BACKWARDS)))
1685 mddev->reshape_backwards = 1;
1686 } else {
1687 mddev->reshape_position = MaxSector;
1688 mddev->delta_disks = 0;
1689 mddev->new_level = mddev->level;
1690 mddev->new_layout = mddev->layout;
1691 mddev->new_chunk_sectors = mddev->chunk_sectors;
1694 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)
1695 set_bit(MD_HAS_JOURNAL, &mddev->flags);
1697 if (le32_to_cpu(sb->feature_map) &
1698 (MD_FEATURE_PPL | MD_FEATURE_MULTIPLE_PPLS)) {
1699 if (le32_to_cpu(sb->feature_map) &
1700 (MD_FEATURE_BITMAP_OFFSET | MD_FEATURE_JOURNAL))
1701 return -EINVAL;
1702 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_PPL) &&
1703 (le32_to_cpu(sb->feature_map) &
1704 MD_FEATURE_MULTIPLE_PPLS))
1705 return -EINVAL;
1706 set_bit(MD_HAS_PPL, &mddev->flags);
1708 } else if (mddev->pers == NULL) {
1709 /* Insist of good event counter while assembling, except for
1710 * spares (which don't need an event count) */
1711 ++ev1;
1712 if (rdev->desc_nr >= 0 &&
1713 rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1714 (le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < MD_DISK_ROLE_MAX ||
1715 le16_to_cpu(sb->dev_roles[rdev->desc_nr]) == MD_DISK_ROLE_JOURNAL))
1716 if (ev1 < mddev->events)
1717 return -EINVAL;
1718 } else if (mddev->bitmap) {
1719 /* If adding to array with a bitmap, then we can accept an
1720 * older device, but not too old.
1722 if (ev1 < mddev->bitmap->events_cleared)
1723 return 0;
1724 if (ev1 < mddev->events)
1725 set_bit(Bitmap_sync, &rdev->flags);
1726 } else {
1727 if (ev1 < mddev->events)
1728 /* just a hot-add of a new device, leave raid_disk at -1 */
1729 return 0;
1731 if (mddev->level != LEVEL_MULTIPATH) {
1732 int role;
1733 if (rdev->desc_nr < 0 ||
1734 rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1735 role = MD_DISK_ROLE_SPARE;
1736 rdev->desc_nr = -1;
1737 } else
1738 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1739 switch(role) {
1740 case MD_DISK_ROLE_SPARE: /* spare */
1741 break;
1742 case MD_DISK_ROLE_FAULTY: /* faulty */
1743 set_bit(Faulty, &rdev->flags);
1744 break;
1745 case MD_DISK_ROLE_JOURNAL: /* journal device */
1746 if (!(le32_to_cpu(sb->feature_map) & MD_FEATURE_JOURNAL)) {
1747 /* journal device without journal feature */
1748 pr_warn("md: journal device provided without journal feature, ignoring the device\n");
1749 return -EINVAL;
1751 set_bit(Journal, &rdev->flags);
1752 rdev->journal_tail = le64_to_cpu(sb->journal_tail);
1753 rdev->raid_disk = 0;
1754 break;
1755 default:
1756 rdev->saved_raid_disk = role;
1757 if ((le32_to_cpu(sb->feature_map) &
1758 MD_FEATURE_RECOVERY_OFFSET)) {
1759 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1760 if (!(le32_to_cpu(sb->feature_map) &
1761 MD_FEATURE_RECOVERY_BITMAP))
1762 rdev->saved_raid_disk = -1;
1763 } else
1764 set_bit(In_sync, &rdev->flags);
1765 rdev->raid_disk = role;
1766 break;
1768 if (sb->devflags & WriteMostly1)
1769 set_bit(WriteMostly, &rdev->flags);
1770 if (sb->devflags & FailFast1)
1771 set_bit(FailFast, &rdev->flags);
1772 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1773 set_bit(Replacement, &rdev->flags);
1774 } else /* MULTIPATH are always insync */
1775 set_bit(In_sync, &rdev->flags);
1777 return 0;
1780 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1782 struct mdp_superblock_1 *sb;
1783 struct md_rdev *rdev2;
1784 int max_dev, i;
1785 /* make rdev->sb match mddev and rdev data. */
1787 sb = page_address(rdev->sb_page);
1789 sb->feature_map = 0;
1790 sb->pad0 = 0;
1791 sb->recovery_offset = cpu_to_le64(0);
1792 memset(sb->pad3, 0, sizeof(sb->pad3));
1794 sb->utime = cpu_to_le64((__u64)mddev->utime);
1795 sb->events = cpu_to_le64(mddev->events);
1796 if (mddev->in_sync)
1797 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1798 else if (test_bit(MD_JOURNAL_CLEAN, &mddev->flags))
1799 sb->resync_offset = cpu_to_le64(MaxSector);
1800 else
1801 sb->resync_offset = cpu_to_le64(0);
1803 sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1805 sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1806 sb->size = cpu_to_le64(mddev->dev_sectors);
1807 sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1808 sb->level = cpu_to_le32(mddev->level);
1809 sb->layout = cpu_to_le32(mddev->layout);
1810 if (test_bit(FailFast, &rdev->flags))
1811 sb->devflags |= FailFast1;
1812 else
1813 sb->devflags &= ~FailFast1;
1815 if (test_bit(WriteMostly, &rdev->flags))
1816 sb->devflags |= WriteMostly1;
1817 else
1818 sb->devflags &= ~WriteMostly1;
1819 sb->data_offset = cpu_to_le64(rdev->data_offset);
1820 sb->data_size = cpu_to_le64(rdev->sectors);
1822 if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1823 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1824 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1827 if (rdev->raid_disk >= 0 && !test_bit(Journal, &rdev->flags) &&
1828 !test_bit(In_sync, &rdev->flags)) {
1829 sb->feature_map |=
1830 cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1831 sb->recovery_offset =
1832 cpu_to_le64(rdev->recovery_offset);
1833 if (rdev->saved_raid_disk >= 0 && mddev->bitmap)
1834 sb->feature_map |=
1835 cpu_to_le32(MD_FEATURE_RECOVERY_BITMAP);
1837 /* Note: recovery_offset and journal_tail share space */
1838 if (test_bit(Journal, &rdev->flags))
1839 sb->journal_tail = cpu_to_le64(rdev->journal_tail);
1840 if (test_bit(Replacement, &rdev->flags))
1841 sb->feature_map |=
1842 cpu_to_le32(MD_FEATURE_REPLACEMENT);
1844 if (mddev->reshape_position != MaxSector) {
1845 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1846 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1847 sb->new_layout = cpu_to_le32(mddev->new_layout);
1848 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1849 sb->new_level = cpu_to_le32(mddev->new_level);
1850 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1851 if (mddev->delta_disks == 0 &&
1852 mddev->reshape_backwards)
1853 sb->feature_map
1854 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1855 if (rdev->new_data_offset != rdev->data_offset) {
1856 sb->feature_map
1857 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1858 sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1859 - rdev->data_offset));
1863 if (mddev_is_clustered(mddev))
1864 sb->feature_map |= cpu_to_le32(MD_FEATURE_CLUSTERED);
1866 if (rdev->badblocks.count == 0)
1867 /* Nothing to do for bad blocks*/ ;
1868 else if (sb->bblog_offset == 0)
1869 /* Cannot record bad blocks on this device */
1870 md_error(mddev, rdev);
1871 else {
1872 struct badblocks *bb = &rdev->badblocks;
1873 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1874 u64 *p = bb->page;
1875 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1876 if (bb->changed) {
1877 unsigned seq;
1879 retry:
1880 seq = read_seqbegin(&bb->lock);
1882 memset(bbp, 0xff, PAGE_SIZE);
1884 for (i = 0 ; i < bb->count ; i++) {
1885 u64 internal_bb = p[i];
1886 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1887 | BB_LEN(internal_bb));
1888 bbp[i] = cpu_to_le64(store_bb);
1890 bb->changed = 0;
1891 if (read_seqretry(&bb->lock, seq))
1892 goto retry;
1894 bb->sector = (rdev->sb_start +
1895 (int)le32_to_cpu(sb->bblog_offset));
1896 bb->size = le16_to_cpu(sb->bblog_size);
1900 max_dev = 0;
1901 rdev_for_each(rdev2, mddev)
1902 if (rdev2->desc_nr+1 > max_dev)
1903 max_dev = rdev2->desc_nr+1;
1905 if (max_dev > le32_to_cpu(sb->max_dev)) {
1906 int bmask;
1907 sb->max_dev = cpu_to_le32(max_dev);
1908 rdev->sb_size = max_dev * 2 + 256;
1909 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1910 if (rdev->sb_size & bmask)
1911 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1912 } else
1913 max_dev = le32_to_cpu(sb->max_dev);
1915 for (i=0; i<max_dev;i++)
1916 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1918 if (test_bit(MD_HAS_JOURNAL, &mddev->flags))
1919 sb->feature_map |= cpu_to_le32(MD_FEATURE_JOURNAL);
1921 if (test_bit(MD_HAS_PPL, &mddev->flags)) {
1922 if (test_bit(MD_HAS_MULTIPLE_PPLS, &mddev->flags))
1923 sb->feature_map |=
1924 cpu_to_le32(MD_FEATURE_MULTIPLE_PPLS);
1925 else
1926 sb->feature_map |= cpu_to_le32(MD_FEATURE_PPL);
1927 sb->ppl.offset = cpu_to_le16(rdev->ppl.offset);
1928 sb->ppl.size = cpu_to_le16(rdev->ppl.size);
1931 rdev_for_each(rdev2, mddev) {
1932 i = rdev2->desc_nr;
1933 if (test_bit(Faulty, &rdev2->flags))
1934 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_FAULTY);
1935 else if (test_bit(In_sync, &rdev2->flags))
1936 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1937 else if (test_bit(Journal, &rdev2->flags))
1938 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_JOURNAL);
1939 else if (rdev2->raid_disk >= 0)
1940 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1941 else
1942 sb->dev_roles[i] = cpu_to_le16(MD_DISK_ROLE_SPARE);
1945 sb->sb_csum = calc_sb_1_csum(sb);
1948 static unsigned long long
1949 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1951 struct mdp_superblock_1 *sb;
1952 sector_t max_sectors;
1953 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1954 return 0; /* component must fit device */
1955 if (rdev->data_offset != rdev->new_data_offset)
1956 return 0; /* too confusing */
1957 if (rdev->sb_start < rdev->data_offset) {
1958 /* minor versions 1 and 2; superblock before data */
1959 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1960 max_sectors -= rdev->data_offset;
1961 if (!num_sectors || num_sectors > max_sectors)
1962 num_sectors = max_sectors;
1963 } else if (rdev->mddev->bitmap_info.offset) {
1964 /* minor version 0 with bitmap we can't move */
1965 return 0;
1966 } else {
1967 /* minor version 0; superblock after data */
1968 sector_t sb_start;
1969 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1970 sb_start &= ~(sector_t)(4*2 - 1);
1971 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1972 if (!num_sectors || num_sectors > max_sectors)
1973 num_sectors = max_sectors;
1974 rdev->sb_start = sb_start;
1976 sb = page_address(rdev->sb_page);
1977 sb->data_size = cpu_to_le64(num_sectors);
1978 sb->super_offset = cpu_to_le64(rdev->sb_start);
1979 sb->sb_csum = calc_sb_1_csum(sb);
1980 do {
1981 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1982 rdev->sb_page);
1983 } while (md_super_wait(rdev->mddev) < 0);
1984 return num_sectors;
1988 static int
1989 super_1_allow_new_offset(struct md_rdev *rdev,
1990 unsigned long long new_offset)
1992 /* All necessary checks on new >= old have been done */
1993 struct bitmap *bitmap;
1994 if (new_offset >= rdev->data_offset)
1995 return 1;
1997 /* with 1.0 metadata, there is no metadata to tread on
1998 * so we can always move back */
1999 if (rdev->mddev->minor_version == 0)
2000 return 1;
2002 /* otherwise we must be sure not to step on
2003 * any metadata, so stay:
2004 * 36K beyond start of superblock
2005 * beyond end of badblocks
2006 * beyond write-intent bitmap
2008 if (rdev->sb_start + (32+4)*2 > new_offset)
2009 return 0;
2010 bitmap = rdev->mddev->bitmap;
2011 if (bitmap && !rdev->mddev->bitmap_info.file &&
2012 rdev->sb_start + rdev->mddev->bitmap_info.offset +
2013 bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
2014 return 0;
2015 if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
2016 return 0;
2018 return 1;
2021 static struct super_type super_types[] = {
2022 [0] = {
2023 .name = "0.90.0",
2024 .owner = THIS_MODULE,
2025 .load_super = super_90_load,
2026 .validate_super = super_90_validate,
2027 .sync_super = super_90_sync,
2028 .rdev_size_change = super_90_rdev_size_change,
2029 .allow_new_offset = super_90_allow_new_offset,
2031 [1] = {
2032 .name = "md-1",
2033 .owner = THIS_MODULE,
2034 .load_super = super_1_load,
2035 .validate_super = super_1_validate,
2036 .sync_super = super_1_sync,
2037 .rdev_size_change = super_1_rdev_size_change,
2038 .allow_new_offset = super_1_allow_new_offset,
2042 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
2044 if (mddev->sync_super) {
2045 mddev->sync_super(mddev, rdev);
2046 return;
2049 BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
2051 super_types[mddev->major_version].sync_super(mddev, rdev);
2054 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
2056 struct md_rdev *rdev, *rdev2;
2058 rcu_read_lock();
2059 rdev_for_each_rcu(rdev, mddev1) {
2060 if (test_bit(Faulty, &rdev->flags) ||
2061 test_bit(Journal, &rdev->flags) ||
2062 rdev->raid_disk == -1)
2063 continue;
2064 rdev_for_each_rcu(rdev2, mddev2) {
2065 if (test_bit(Faulty, &rdev2->flags) ||
2066 test_bit(Journal, &rdev2->flags) ||
2067 rdev2->raid_disk == -1)
2068 continue;
2069 if (rdev->bdev->bd_contains ==
2070 rdev2->bdev->bd_contains) {
2071 rcu_read_unlock();
2072 return 1;
2076 rcu_read_unlock();
2077 return 0;
2080 static LIST_HEAD(pending_raid_disks);
2083 * Try to register data integrity profile for an mddev
2085 * This is called when an array is started and after a disk has been kicked
2086 * from the array. It only succeeds if all working and active component devices
2087 * are integrity capable with matching profiles.
2089 int md_integrity_register(struct mddev *mddev)
2091 struct md_rdev *rdev, *reference = NULL;
2093 if (list_empty(&mddev->disks))
2094 return 0; /* nothing to do */
2095 if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
2096 return 0; /* shouldn't register, or already is */
2097 rdev_for_each(rdev, mddev) {
2098 /* skip spares and non-functional disks */
2099 if (test_bit(Faulty, &rdev->flags))
2100 continue;
2101 if (rdev->raid_disk < 0)
2102 continue;
2103 if (!reference) {
2104 /* Use the first rdev as the reference */
2105 reference = rdev;
2106 continue;
2108 /* does this rdev's profile match the reference profile? */
2109 if (blk_integrity_compare(reference->bdev->bd_disk,
2110 rdev->bdev->bd_disk) < 0)
2111 return -EINVAL;
2113 if (!reference || !bdev_get_integrity(reference->bdev))
2114 return 0;
2116 * All component devices are integrity capable and have matching
2117 * profiles, register the common profile for the md device.
2119 blk_integrity_register(mddev->gendisk,
2120 bdev_get_integrity(reference->bdev));
2122 pr_debug("md: data integrity enabled on %s\n", mdname(mddev));
2123 if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
2124 pr_err("md: failed to create integrity pool for %s\n",
2125 mdname(mddev));
2126 return -EINVAL;
2128 return 0;
2130 EXPORT_SYMBOL(md_integrity_register);
2133 * Attempt to add an rdev, but only if it is consistent with the current
2134 * integrity profile
2136 int md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2138 struct blk_integrity *bi_rdev;
2139 struct blk_integrity *bi_mddev;
2140 char name[BDEVNAME_SIZE];
2142 if (!mddev->gendisk)
2143 return 0;
2145 bi_rdev = bdev_get_integrity(rdev->bdev);
2146 bi_mddev = blk_get_integrity(mddev->gendisk);
2148 if (!bi_mddev) /* nothing to do */
2149 return 0;
2151 if (blk_integrity_compare(mddev->gendisk, rdev->bdev->bd_disk) != 0) {
2152 pr_err("%s: incompatible integrity profile for %s\n",
2153 mdname(mddev), bdevname(rdev->bdev, name));
2154 return -ENXIO;
2157 return 0;
2159 EXPORT_SYMBOL(md_integrity_add_rdev);
2161 static int bind_rdev_to_array(struct md_rdev *rdev, struct mddev *mddev)
2163 char b[BDEVNAME_SIZE];
2164 struct kobject *ko;
2165 int err;
2167 /* prevent duplicates */
2168 if (find_rdev(mddev, rdev->bdev->bd_dev))
2169 return -EEXIST;
2171 if ((bdev_read_only(rdev->bdev) || bdev_read_only(rdev->meta_bdev)) &&
2172 mddev->pers)
2173 return -EROFS;
2175 /* make sure rdev->sectors exceeds mddev->dev_sectors */
2176 if (!test_bit(Journal, &rdev->flags) &&
2177 rdev->sectors &&
2178 (mddev->dev_sectors == 0 || rdev->sectors < mddev->dev_sectors)) {
2179 if (mddev->pers) {
2180 /* Cannot change size, so fail
2181 * If mddev->level <= 0, then we don't care
2182 * about aligning sizes (e.g. linear)
2184 if (mddev->level > 0)
2185 return -ENOSPC;
2186 } else
2187 mddev->dev_sectors = rdev->sectors;
2190 /* Verify rdev->desc_nr is unique.
2191 * If it is -1, assign a free number, else
2192 * check number is not in use
2194 rcu_read_lock();
2195 if (rdev->desc_nr < 0) {
2196 int choice = 0;
2197 if (mddev->pers)
2198 choice = mddev->raid_disks;
2199 while (md_find_rdev_nr_rcu(mddev, choice))
2200 choice++;
2201 rdev->desc_nr = choice;
2202 } else {
2203 if (md_find_rdev_nr_rcu(mddev, rdev->desc_nr)) {
2204 rcu_read_unlock();
2205 return -EBUSY;
2208 rcu_read_unlock();
2209 if (!test_bit(Journal, &rdev->flags) &&
2210 mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2211 pr_warn("md: %s: array is limited to %d devices\n",
2212 mdname(mddev), mddev->max_disks);
2213 return -EBUSY;
2215 bdevname(rdev->bdev,b);
2216 strreplace(b, '/', '!');
2218 rdev->mddev = mddev;
2219 pr_debug("md: bind<%s>\n", b);
2221 if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2222 goto fail;
2224 ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2225 if (sysfs_create_link(&rdev->kobj, ko, "block"))
2226 /* failure here is OK */;
2227 rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2229 list_add_rcu(&rdev->same_set, &mddev->disks);
2230 bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2232 /* May as well allow recovery to be retried once */
2233 mddev->recovery_disabled++;
2235 return 0;
2237 fail:
2238 pr_warn("md: failed to register dev-%s for %s\n",
2239 b, mdname(mddev));
2240 return err;
2243 static void md_delayed_delete(struct work_struct *ws)
2245 struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2246 kobject_del(&rdev->kobj);
2247 kobject_put(&rdev->kobj);
2250 static void unbind_rdev_from_array(struct md_rdev *rdev)
2252 char b[BDEVNAME_SIZE];
2254 bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2255 list_del_rcu(&rdev->same_set);
2256 pr_debug("md: unbind<%s>\n", bdevname(rdev->bdev,b));
2257 rdev->mddev = NULL;
2258 sysfs_remove_link(&rdev->kobj, "block");
2259 sysfs_put(rdev->sysfs_state);
2260 rdev->sysfs_state = NULL;
2261 rdev->badblocks.count = 0;
2262 /* We need to delay this, otherwise we can deadlock when
2263 * writing to 'remove' to "dev/state". We also need
2264 * to delay it due to rcu usage.
2266 synchronize_rcu();
2267 INIT_WORK(&rdev->del_work, md_delayed_delete);
2268 kobject_get(&rdev->kobj);
2269 queue_work(md_misc_wq, &rdev->del_work);
2273 * prevent the device from being mounted, repartitioned or
2274 * otherwise reused by a RAID array (or any other kernel
2275 * subsystem), by bd_claiming the device.
2277 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2279 int err = 0;
2280 struct block_device *bdev;
2281 char b[BDEVNAME_SIZE];
2283 bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2284 shared ? (struct md_rdev *)lock_rdev : rdev);
2285 if (IS_ERR(bdev)) {
2286 pr_warn("md: could not open %s.\n", __bdevname(dev, b));
2287 return PTR_ERR(bdev);
2289 rdev->bdev = bdev;
2290 return err;
2293 static void unlock_rdev(struct md_rdev *rdev)
2295 struct block_device *bdev = rdev->bdev;
2296 rdev->bdev = NULL;
2297 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2300 void md_autodetect_dev(dev_t dev);
2302 static void export_rdev(struct md_rdev *rdev)
2304 char b[BDEVNAME_SIZE];
2306 pr_debug("md: export_rdev(%s)\n", bdevname(rdev->bdev,b));
2307 md_rdev_clear(rdev);
2308 #ifndef MODULE
2309 if (test_bit(AutoDetected, &rdev->flags))
2310 md_autodetect_dev(rdev->bdev->bd_dev);
2311 #endif
2312 unlock_rdev(rdev);
2313 kobject_put(&rdev->kobj);
2316 void md_kick_rdev_from_array(struct md_rdev *rdev)
2318 unbind_rdev_from_array(rdev);
2319 export_rdev(rdev);
2321 EXPORT_SYMBOL_GPL(md_kick_rdev_from_array);
2323 static void export_array(struct mddev *mddev)
2325 struct md_rdev *rdev;
2327 while (!list_empty(&mddev->disks)) {
2328 rdev = list_first_entry(&mddev->disks, struct md_rdev,
2329 same_set);
2330 md_kick_rdev_from_array(rdev);
2332 mddev->raid_disks = 0;
2333 mddev->major_version = 0;
2336 static bool set_in_sync(struct mddev *mddev)
2338 lockdep_assert_held(&mddev->lock);
2339 if (!mddev->in_sync) {
2340 mddev->sync_checkers++;
2341 spin_unlock(&mddev->lock);
2342 percpu_ref_switch_to_atomic_sync(&mddev->writes_pending);
2343 spin_lock(&mddev->lock);
2344 if (!mddev->in_sync &&
2345 percpu_ref_is_zero(&mddev->writes_pending)) {
2346 mddev->in_sync = 1;
2348 * Ensure ->in_sync is visible before we clear
2349 * ->sync_checkers.
2351 smp_mb();
2352 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2353 sysfs_notify_dirent_safe(mddev->sysfs_state);
2355 if (--mddev->sync_checkers == 0)
2356 percpu_ref_switch_to_percpu(&mddev->writes_pending);
2358 if (mddev->safemode == 1)
2359 mddev->safemode = 0;
2360 return mddev->in_sync;
2363 static void sync_sbs(struct mddev *mddev, int nospares)
2365 /* Update each superblock (in-memory image), but
2366 * if we are allowed to, skip spares which already
2367 * have the right event counter, or have one earlier
2368 * (which would mean they aren't being marked as dirty
2369 * with the rest of the array)
2371 struct md_rdev *rdev;
2372 rdev_for_each(rdev, mddev) {
2373 if (rdev->sb_events == mddev->events ||
2374 (nospares &&
2375 rdev->raid_disk < 0 &&
2376 rdev->sb_events+1 == mddev->events)) {
2377 /* Don't update this superblock */
2378 rdev->sb_loaded = 2;
2379 } else {
2380 sync_super(mddev, rdev);
2381 rdev->sb_loaded = 1;
2386 static bool does_sb_need_changing(struct mddev *mddev)
2388 struct md_rdev *rdev;
2389 struct mdp_superblock_1 *sb;
2390 int role;
2392 /* Find a good rdev */
2393 rdev_for_each(rdev, mddev)
2394 if ((rdev->raid_disk >= 0) && !test_bit(Faulty, &rdev->flags))
2395 break;
2397 /* No good device found. */
2398 if (!rdev)
2399 return false;
2401 sb = page_address(rdev->sb_page);
2402 /* Check if a device has become faulty or a spare become active */
2403 rdev_for_each(rdev, mddev) {
2404 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
2405 /* Device activated? */
2406 if (role == 0xffff && rdev->raid_disk >=0 &&
2407 !test_bit(Faulty, &rdev->flags))
2408 return true;
2409 /* Device turned faulty? */
2410 if (test_bit(Faulty, &rdev->flags) && (role < 0xfffd))
2411 return true;
2414 /* Check if any mddev parameters have changed */
2415 if ((mddev->dev_sectors != le64_to_cpu(sb->size)) ||
2416 (mddev->reshape_position != le64_to_cpu(sb->reshape_position)) ||
2417 (mddev->layout != le32_to_cpu(sb->layout)) ||
2418 (mddev->raid_disks != le32_to_cpu(sb->raid_disks)) ||
2419 (mddev->chunk_sectors != le32_to_cpu(sb->chunksize)))
2420 return true;
2422 return false;
2425 void md_update_sb(struct mddev *mddev, int force_change)
2427 struct md_rdev *rdev;
2428 int sync_req;
2429 int nospares = 0;
2430 int any_badblocks_changed = 0;
2431 int ret = -1;
2433 if (mddev->ro) {
2434 if (force_change)
2435 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2436 return;
2439 repeat:
2440 if (mddev_is_clustered(mddev)) {
2441 if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2442 force_change = 1;
2443 if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2444 nospares = 1;
2445 ret = md_cluster_ops->metadata_update_start(mddev);
2446 /* Has someone else has updated the sb */
2447 if (!does_sb_need_changing(mddev)) {
2448 if (ret == 0)
2449 md_cluster_ops->metadata_update_cancel(mddev);
2450 bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2451 BIT(MD_SB_CHANGE_DEVS) |
2452 BIT(MD_SB_CHANGE_CLEAN));
2453 return;
2458 * First make sure individual recovery_offsets are correct
2459 * curr_resync_completed can only be used during recovery.
2460 * During reshape/resync it might use array-addresses rather
2461 * that device addresses.
2463 rdev_for_each(rdev, mddev) {
2464 if (rdev->raid_disk >= 0 &&
2465 mddev->delta_disks >= 0 &&
2466 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
2467 test_bit(MD_RECOVERY_RECOVER, &mddev->recovery) &&
2468 !test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
2469 !test_bit(Journal, &rdev->flags) &&
2470 !test_bit(In_sync, &rdev->flags) &&
2471 mddev->curr_resync_completed > rdev->recovery_offset)
2472 rdev->recovery_offset = mddev->curr_resync_completed;
2475 if (!mddev->persistent) {
2476 clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
2477 clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2478 if (!mddev->external) {
2479 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
2480 rdev_for_each(rdev, mddev) {
2481 if (rdev->badblocks.changed) {
2482 rdev->badblocks.changed = 0;
2483 ack_all_badblocks(&rdev->badblocks);
2484 md_error(mddev, rdev);
2486 clear_bit(Blocked, &rdev->flags);
2487 clear_bit(BlockedBadBlocks, &rdev->flags);
2488 wake_up(&rdev->blocked_wait);
2491 wake_up(&mddev->sb_wait);
2492 return;
2495 spin_lock(&mddev->lock);
2497 mddev->utime = ktime_get_real_seconds();
2499 if (test_and_clear_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags))
2500 force_change = 1;
2501 if (test_and_clear_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags))
2502 /* just a clean<-> dirty transition, possibly leave spares alone,
2503 * though if events isn't the right even/odd, we will have to do
2504 * spares after all
2506 nospares = 1;
2507 if (force_change)
2508 nospares = 0;
2509 if (mddev->degraded)
2510 /* If the array is degraded, then skipping spares is both
2511 * dangerous and fairly pointless.
2512 * Dangerous because a device that was removed from the array
2513 * might have a event_count that still looks up-to-date,
2514 * so it can be re-added without a resync.
2515 * Pointless because if there are any spares to skip,
2516 * then a recovery will happen and soon that array won't
2517 * be degraded any more and the spare can go back to sleep then.
2519 nospares = 0;
2521 sync_req = mddev->in_sync;
2523 /* If this is just a dirty<->clean transition, and the array is clean
2524 * and 'events' is odd, we can roll back to the previous clean state */
2525 if (nospares
2526 && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2527 && mddev->can_decrease_events
2528 && mddev->events != 1) {
2529 mddev->events--;
2530 mddev->can_decrease_events = 0;
2531 } else {
2532 /* otherwise we have to go forward and ... */
2533 mddev->events ++;
2534 mddev->can_decrease_events = nospares;
2538 * This 64-bit counter should never wrap.
2539 * Either we are in around ~1 trillion A.C., assuming
2540 * 1 reboot per second, or we have a bug...
2542 WARN_ON(mddev->events == 0);
2544 rdev_for_each(rdev, mddev) {
2545 if (rdev->badblocks.changed)
2546 any_badblocks_changed++;
2547 if (test_bit(Faulty, &rdev->flags))
2548 set_bit(FaultRecorded, &rdev->flags);
2551 sync_sbs(mddev, nospares);
2552 spin_unlock(&mddev->lock);
2554 pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2555 mdname(mddev), mddev->in_sync);
2557 if (mddev->queue)
2558 blk_add_trace_msg(mddev->queue, "md md_update_sb");
2559 rewrite:
2560 bitmap_update_sb(mddev->bitmap);
2561 rdev_for_each(rdev, mddev) {
2562 char b[BDEVNAME_SIZE];
2564 if (rdev->sb_loaded != 1)
2565 continue; /* no noise on spare devices */
2567 if (!test_bit(Faulty, &rdev->flags)) {
2568 md_super_write(mddev,rdev,
2569 rdev->sb_start, rdev->sb_size,
2570 rdev->sb_page);
2571 pr_debug("md: (write) %s's sb offset: %llu\n",
2572 bdevname(rdev->bdev, b),
2573 (unsigned long long)rdev->sb_start);
2574 rdev->sb_events = mddev->events;
2575 if (rdev->badblocks.size) {
2576 md_super_write(mddev, rdev,
2577 rdev->badblocks.sector,
2578 rdev->badblocks.size << 9,
2579 rdev->bb_page);
2580 rdev->badblocks.size = 0;
2583 } else
2584 pr_debug("md: %s (skipping faulty)\n",
2585 bdevname(rdev->bdev, b));
2587 if (mddev->level == LEVEL_MULTIPATH)
2588 /* only need to write one superblock... */
2589 break;
2591 if (md_super_wait(mddev) < 0)
2592 goto rewrite;
2593 /* if there was a failure, MD_SB_CHANGE_DEVS was set, and we re-write super */
2595 if (mddev_is_clustered(mddev) && ret == 0)
2596 md_cluster_ops->metadata_update_finish(mddev);
2598 if (mddev->in_sync != sync_req ||
2599 !bit_clear_unless(&mddev->sb_flags, BIT(MD_SB_CHANGE_PENDING),
2600 BIT(MD_SB_CHANGE_DEVS) | BIT(MD_SB_CHANGE_CLEAN)))
2601 /* have to write it out again */
2602 goto repeat;
2603 wake_up(&mddev->sb_wait);
2604 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2605 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2607 rdev_for_each(rdev, mddev) {
2608 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2609 clear_bit(Blocked, &rdev->flags);
2611 if (any_badblocks_changed)
2612 ack_all_badblocks(&rdev->badblocks);
2613 clear_bit(BlockedBadBlocks, &rdev->flags);
2614 wake_up(&rdev->blocked_wait);
2617 EXPORT_SYMBOL(md_update_sb);
2619 static int add_bound_rdev(struct md_rdev *rdev)
2621 struct mddev *mddev = rdev->mddev;
2622 int err = 0;
2623 bool add_journal = test_bit(Journal, &rdev->flags);
2625 if (!mddev->pers->hot_remove_disk || add_journal) {
2626 /* If there is hot_add_disk but no hot_remove_disk
2627 * then added disks for geometry changes,
2628 * and should be added immediately.
2630 super_types[mddev->major_version].
2631 validate_super(mddev, rdev);
2632 if (add_journal)
2633 mddev_suspend(mddev);
2634 err = mddev->pers->hot_add_disk(mddev, rdev);
2635 if (add_journal)
2636 mddev_resume(mddev);
2637 if (err) {
2638 md_kick_rdev_from_array(rdev);
2639 return err;
2642 sysfs_notify_dirent_safe(rdev->sysfs_state);
2644 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2645 if (mddev->degraded)
2646 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
2647 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2648 md_new_event(mddev);
2649 md_wakeup_thread(mddev->thread);
2650 return 0;
2653 /* words written to sysfs files may, or may not, be \n terminated.
2654 * We want to accept with case. For this we use cmd_match.
2656 static int cmd_match(const char *cmd, const char *str)
2658 /* See if cmd, written into a sysfs file, matches
2659 * str. They must either be the same, or cmd can
2660 * have a trailing newline
2662 while (*cmd && *str && *cmd == *str) {
2663 cmd++;
2664 str++;
2666 if (*cmd == '\n')
2667 cmd++;
2668 if (*str || *cmd)
2669 return 0;
2670 return 1;
2673 struct rdev_sysfs_entry {
2674 struct attribute attr;
2675 ssize_t (*show)(struct md_rdev *, char *);
2676 ssize_t (*store)(struct md_rdev *, const char *, size_t);
2679 static ssize_t
2680 state_show(struct md_rdev *rdev, char *page)
2682 char *sep = ",";
2683 size_t len = 0;
2684 unsigned long flags = READ_ONCE(rdev->flags);
2686 if (test_bit(Faulty, &flags) ||
2687 (!test_bit(ExternalBbl, &flags) &&
2688 rdev->badblocks.unacked_exist))
2689 len += sprintf(page+len, "faulty%s", sep);
2690 if (test_bit(In_sync, &flags))
2691 len += sprintf(page+len, "in_sync%s", sep);
2692 if (test_bit(Journal, &flags))
2693 len += sprintf(page+len, "journal%s", sep);
2694 if (test_bit(WriteMostly, &flags))
2695 len += sprintf(page+len, "write_mostly%s", sep);
2696 if (test_bit(Blocked, &flags) ||
2697 (rdev->badblocks.unacked_exist
2698 && !test_bit(Faulty, &flags)))
2699 len += sprintf(page+len, "blocked%s", sep);
2700 if (!test_bit(Faulty, &flags) &&
2701 !test_bit(Journal, &flags) &&
2702 !test_bit(In_sync, &flags))
2703 len += sprintf(page+len, "spare%s", sep);
2704 if (test_bit(WriteErrorSeen, &flags))
2705 len += sprintf(page+len, "write_error%s", sep);
2706 if (test_bit(WantReplacement, &flags))
2707 len += sprintf(page+len, "want_replacement%s", sep);
2708 if (test_bit(Replacement, &flags))
2709 len += sprintf(page+len, "replacement%s", sep);
2710 if (test_bit(ExternalBbl, &flags))
2711 len += sprintf(page+len, "external_bbl%s", sep);
2712 if (test_bit(FailFast, &flags))
2713 len += sprintf(page+len, "failfast%s", sep);
2715 if (len)
2716 len -= strlen(sep);
2718 return len+sprintf(page+len, "\n");
2721 static ssize_t
2722 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2724 /* can write
2725 * faulty - simulates an error
2726 * remove - disconnects the device
2727 * writemostly - sets write_mostly
2728 * -writemostly - clears write_mostly
2729 * blocked - sets the Blocked flags
2730 * -blocked - clears the Blocked and possibly simulates an error
2731 * insync - sets Insync providing device isn't active
2732 * -insync - clear Insync for a device with a slot assigned,
2733 * so that it gets rebuilt based on bitmap
2734 * write_error - sets WriteErrorSeen
2735 * -write_error - clears WriteErrorSeen
2736 * {,-}failfast - set/clear FailFast
2738 int err = -EINVAL;
2739 if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2740 md_error(rdev->mddev, rdev);
2741 if (test_bit(Faulty, &rdev->flags))
2742 err = 0;
2743 else
2744 err = -EBUSY;
2745 } else if (cmd_match(buf, "remove")) {
2746 if (rdev->mddev->pers) {
2747 clear_bit(Blocked, &rdev->flags);
2748 remove_and_add_spares(rdev->mddev, rdev);
2750 if (rdev->raid_disk >= 0)
2751 err = -EBUSY;
2752 else {
2753 struct mddev *mddev = rdev->mddev;
2754 err = 0;
2755 if (mddev_is_clustered(mddev))
2756 err = md_cluster_ops->remove_disk(mddev, rdev);
2758 if (err == 0) {
2759 md_kick_rdev_from_array(rdev);
2760 if (mddev->pers) {
2761 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
2762 md_wakeup_thread(mddev->thread);
2764 md_new_event(mddev);
2767 } else if (cmd_match(buf, "writemostly")) {
2768 set_bit(WriteMostly, &rdev->flags);
2769 err = 0;
2770 } else if (cmd_match(buf, "-writemostly")) {
2771 clear_bit(WriteMostly, &rdev->flags);
2772 err = 0;
2773 } else if (cmd_match(buf, "blocked")) {
2774 set_bit(Blocked, &rdev->flags);
2775 err = 0;
2776 } else if (cmd_match(buf, "-blocked")) {
2777 if (!test_bit(Faulty, &rdev->flags) &&
2778 !test_bit(ExternalBbl, &rdev->flags) &&
2779 rdev->badblocks.unacked_exist) {
2780 /* metadata handler doesn't understand badblocks,
2781 * so we need to fail the device
2783 md_error(rdev->mddev, rdev);
2785 clear_bit(Blocked, &rdev->flags);
2786 clear_bit(BlockedBadBlocks, &rdev->flags);
2787 wake_up(&rdev->blocked_wait);
2788 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2789 md_wakeup_thread(rdev->mddev->thread);
2791 err = 0;
2792 } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2793 set_bit(In_sync, &rdev->flags);
2794 err = 0;
2795 } else if (cmd_match(buf, "failfast")) {
2796 set_bit(FailFast, &rdev->flags);
2797 err = 0;
2798 } else if (cmd_match(buf, "-failfast")) {
2799 clear_bit(FailFast, &rdev->flags);
2800 err = 0;
2801 } else if (cmd_match(buf, "-insync") && rdev->raid_disk >= 0 &&
2802 !test_bit(Journal, &rdev->flags)) {
2803 if (rdev->mddev->pers == NULL) {
2804 clear_bit(In_sync, &rdev->flags);
2805 rdev->saved_raid_disk = rdev->raid_disk;
2806 rdev->raid_disk = -1;
2807 err = 0;
2809 } else if (cmd_match(buf, "write_error")) {
2810 set_bit(WriteErrorSeen, &rdev->flags);
2811 err = 0;
2812 } else if (cmd_match(buf, "-write_error")) {
2813 clear_bit(WriteErrorSeen, &rdev->flags);
2814 err = 0;
2815 } else if (cmd_match(buf, "want_replacement")) {
2816 /* Any non-spare device that is not a replacement can
2817 * become want_replacement at any time, but we then need to
2818 * check if recovery is needed.
2820 if (rdev->raid_disk >= 0 &&
2821 !test_bit(Journal, &rdev->flags) &&
2822 !test_bit(Replacement, &rdev->flags))
2823 set_bit(WantReplacement, &rdev->flags);
2824 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2825 md_wakeup_thread(rdev->mddev->thread);
2826 err = 0;
2827 } else if (cmd_match(buf, "-want_replacement")) {
2828 /* Clearing 'want_replacement' is always allowed.
2829 * Once replacements starts it is too late though.
2831 err = 0;
2832 clear_bit(WantReplacement, &rdev->flags);
2833 } else if (cmd_match(buf, "replacement")) {
2834 /* Can only set a device as a replacement when array has not
2835 * yet been started. Once running, replacement is automatic
2836 * from spares, or by assigning 'slot'.
2838 if (rdev->mddev->pers)
2839 err = -EBUSY;
2840 else {
2841 set_bit(Replacement, &rdev->flags);
2842 err = 0;
2844 } else if (cmd_match(buf, "-replacement")) {
2845 /* Similarly, can only clear Replacement before start */
2846 if (rdev->mddev->pers)
2847 err = -EBUSY;
2848 else {
2849 clear_bit(Replacement, &rdev->flags);
2850 err = 0;
2852 } else if (cmd_match(buf, "re-add")) {
2853 if (test_bit(Faulty, &rdev->flags) && (rdev->raid_disk == -1)) {
2854 /* clear_bit is performed _after_ all the devices
2855 * have their local Faulty bit cleared. If any writes
2856 * happen in the meantime in the local node, they
2857 * will land in the local bitmap, which will be synced
2858 * by this node eventually
2860 if (!mddev_is_clustered(rdev->mddev) ||
2861 (err = md_cluster_ops->gather_bitmaps(rdev)) == 0) {
2862 clear_bit(Faulty, &rdev->flags);
2863 err = add_bound_rdev(rdev);
2865 } else
2866 err = -EBUSY;
2867 } else if (cmd_match(buf, "external_bbl") && (rdev->mddev->external)) {
2868 set_bit(ExternalBbl, &rdev->flags);
2869 rdev->badblocks.shift = 0;
2870 err = 0;
2871 } else if (cmd_match(buf, "-external_bbl") && (rdev->mddev->external)) {
2872 clear_bit(ExternalBbl, &rdev->flags);
2873 err = 0;
2875 if (!err)
2876 sysfs_notify_dirent_safe(rdev->sysfs_state);
2877 return err ? err : len;
2879 static struct rdev_sysfs_entry rdev_state =
2880 __ATTR_PREALLOC(state, S_IRUGO|S_IWUSR, state_show, state_store);
2882 static ssize_t
2883 errors_show(struct md_rdev *rdev, char *page)
2885 return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2888 static ssize_t
2889 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2891 unsigned int n;
2892 int rv;
2894 rv = kstrtouint(buf, 10, &n);
2895 if (rv < 0)
2896 return rv;
2897 atomic_set(&rdev->corrected_errors, n);
2898 return len;
2900 static struct rdev_sysfs_entry rdev_errors =
2901 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2903 static ssize_t
2904 slot_show(struct md_rdev *rdev, char *page)
2906 if (test_bit(Journal, &rdev->flags))
2907 return sprintf(page, "journal\n");
2908 else if (rdev->raid_disk < 0)
2909 return sprintf(page, "none\n");
2910 else
2911 return sprintf(page, "%d\n", rdev->raid_disk);
2914 static ssize_t
2915 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2917 int slot;
2918 int err;
2920 if (test_bit(Journal, &rdev->flags))
2921 return -EBUSY;
2922 if (strncmp(buf, "none", 4)==0)
2923 slot = -1;
2924 else {
2925 err = kstrtouint(buf, 10, (unsigned int *)&slot);
2926 if (err < 0)
2927 return err;
2929 if (rdev->mddev->pers && slot == -1) {
2930 /* Setting 'slot' on an active array requires also
2931 * updating the 'rd%d' link, and communicating
2932 * with the personality with ->hot_*_disk.
2933 * For now we only support removing
2934 * failed/spare devices. This normally happens automatically,
2935 * but not when the metadata is externally managed.
2937 if (rdev->raid_disk == -1)
2938 return -EEXIST;
2939 /* personality does all needed checks */
2940 if (rdev->mddev->pers->hot_remove_disk == NULL)
2941 return -EINVAL;
2942 clear_bit(Blocked, &rdev->flags);
2943 remove_and_add_spares(rdev->mddev, rdev);
2944 if (rdev->raid_disk >= 0)
2945 return -EBUSY;
2946 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2947 md_wakeup_thread(rdev->mddev->thread);
2948 } else if (rdev->mddev->pers) {
2949 /* Activating a spare .. or possibly reactivating
2950 * if we ever get bitmaps working here.
2952 int err;
2954 if (rdev->raid_disk != -1)
2955 return -EBUSY;
2957 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2958 return -EBUSY;
2960 if (rdev->mddev->pers->hot_add_disk == NULL)
2961 return -EINVAL;
2963 if (slot >= rdev->mddev->raid_disks &&
2964 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2965 return -ENOSPC;
2967 rdev->raid_disk = slot;
2968 if (test_bit(In_sync, &rdev->flags))
2969 rdev->saved_raid_disk = slot;
2970 else
2971 rdev->saved_raid_disk = -1;
2972 clear_bit(In_sync, &rdev->flags);
2973 clear_bit(Bitmap_sync, &rdev->flags);
2974 err = rdev->mddev->pers->
2975 hot_add_disk(rdev->mddev, rdev);
2976 if (err) {
2977 rdev->raid_disk = -1;
2978 return err;
2979 } else
2980 sysfs_notify_dirent_safe(rdev->sysfs_state);
2981 if (sysfs_link_rdev(rdev->mddev, rdev))
2982 /* failure here is OK */;
2983 /* don't wakeup anyone, leave that to userspace. */
2984 } else {
2985 if (slot >= rdev->mddev->raid_disks &&
2986 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2987 return -ENOSPC;
2988 rdev->raid_disk = slot;
2989 /* assume it is working */
2990 clear_bit(Faulty, &rdev->flags);
2991 clear_bit(WriteMostly, &rdev->flags);
2992 set_bit(In_sync, &rdev->flags);
2993 sysfs_notify_dirent_safe(rdev->sysfs_state);
2995 return len;
2998 static struct rdev_sysfs_entry rdev_slot =
2999 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
3001 static ssize_t
3002 offset_show(struct md_rdev *rdev, char *page)
3004 return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
3007 static ssize_t
3008 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
3010 unsigned long long offset;
3011 if (kstrtoull(buf, 10, &offset) < 0)
3012 return -EINVAL;
3013 if (rdev->mddev->pers && rdev->raid_disk >= 0)
3014 return -EBUSY;
3015 if (rdev->sectors && rdev->mddev->external)
3016 /* Must set offset before size, so overlap checks
3017 * can be sane */
3018 return -EBUSY;
3019 rdev->data_offset = offset;
3020 rdev->new_data_offset = offset;
3021 return len;
3024 static struct rdev_sysfs_entry rdev_offset =
3025 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
3027 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
3029 return sprintf(page, "%llu\n",
3030 (unsigned long long)rdev->new_data_offset);
3033 static ssize_t new_offset_store(struct md_rdev *rdev,
3034 const char *buf, size_t len)
3036 unsigned long long new_offset;
3037 struct mddev *mddev = rdev->mddev;
3039 if (kstrtoull(buf, 10, &new_offset) < 0)
3040 return -EINVAL;
3042 if (mddev->sync_thread ||
3043 test_bit(MD_RECOVERY_RUNNING,&mddev->recovery))
3044 return -EBUSY;
3045 if (new_offset == rdev->data_offset)
3046 /* reset is always permitted */
3048 else if (new_offset > rdev->data_offset) {
3049 /* must not push array size beyond rdev_sectors */
3050 if (new_offset - rdev->data_offset
3051 + mddev->dev_sectors > rdev->sectors)
3052 return -E2BIG;
3054 /* Metadata worries about other space details. */
3056 /* decreasing the offset is inconsistent with a backwards
3057 * reshape.
3059 if (new_offset < rdev->data_offset &&
3060 mddev->reshape_backwards)
3061 return -EINVAL;
3062 /* Increasing offset is inconsistent with forwards
3063 * reshape. reshape_direction should be set to
3064 * 'backwards' first.
3066 if (new_offset > rdev->data_offset &&
3067 !mddev->reshape_backwards)
3068 return -EINVAL;
3070 if (mddev->pers && mddev->persistent &&
3071 !super_types[mddev->major_version]
3072 .allow_new_offset(rdev, new_offset))
3073 return -E2BIG;
3074 rdev->new_data_offset = new_offset;
3075 if (new_offset > rdev->data_offset)
3076 mddev->reshape_backwards = 1;
3077 else if (new_offset < rdev->data_offset)
3078 mddev->reshape_backwards = 0;
3080 return len;
3082 static struct rdev_sysfs_entry rdev_new_offset =
3083 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
3085 static ssize_t
3086 rdev_size_show(struct md_rdev *rdev, char *page)
3088 return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
3091 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
3093 /* check if two start/length pairs overlap */
3094 if (s1+l1 <= s2)
3095 return 0;
3096 if (s2+l2 <= s1)
3097 return 0;
3098 return 1;
3101 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
3103 unsigned long long blocks;
3104 sector_t new;
3106 if (kstrtoull(buf, 10, &blocks) < 0)
3107 return -EINVAL;
3109 if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
3110 return -EINVAL; /* sector conversion overflow */
3112 new = blocks * 2;
3113 if (new != blocks * 2)
3114 return -EINVAL; /* unsigned long long to sector_t overflow */
3116 *sectors = new;
3117 return 0;
3120 static ssize_t
3121 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3123 struct mddev *my_mddev = rdev->mddev;
3124 sector_t oldsectors = rdev->sectors;
3125 sector_t sectors;
3127 if (test_bit(Journal, &rdev->flags))
3128 return -EBUSY;
3129 if (strict_blocks_to_sectors(buf, &sectors) < 0)
3130 return -EINVAL;
3131 if (rdev->data_offset != rdev->new_data_offset)
3132 return -EINVAL; /* too confusing */
3133 if (my_mddev->pers && rdev->raid_disk >= 0) {
3134 if (my_mddev->persistent) {
3135 sectors = super_types[my_mddev->major_version].
3136 rdev_size_change(rdev, sectors);
3137 if (!sectors)
3138 return -EBUSY;
3139 } else if (!sectors)
3140 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
3141 rdev->data_offset;
3142 if (!my_mddev->pers->resize)
3143 /* Cannot change size for RAID0 or Linear etc */
3144 return -EINVAL;
3146 if (sectors < my_mddev->dev_sectors)
3147 return -EINVAL; /* component must fit device */
3149 rdev->sectors = sectors;
3150 if (sectors > oldsectors && my_mddev->external) {
3151 /* Need to check that all other rdevs with the same
3152 * ->bdev do not overlap. 'rcu' is sufficient to walk
3153 * the rdev lists safely.
3154 * This check does not provide a hard guarantee, it
3155 * just helps avoid dangerous mistakes.
3157 struct mddev *mddev;
3158 int overlap = 0;
3159 struct list_head *tmp;
3161 rcu_read_lock();
3162 for_each_mddev(mddev, tmp) {
3163 struct md_rdev *rdev2;
3165 rdev_for_each(rdev2, mddev)
3166 if (rdev->bdev == rdev2->bdev &&
3167 rdev != rdev2 &&
3168 overlaps(rdev->data_offset, rdev->sectors,
3169 rdev2->data_offset,
3170 rdev2->sectors)) {
3171 overlap = 1;
3172 break;
3174 if (overlap) {
3175 mddev_put(mddev);
3176 break;
3179 rcu_read_unlock();
3180 if (overlap) {
3181 /* Someone else could have slipped in a size
3182 * change here, but doing so is just silly.
3183 * We put oldsectors back because we *know* it is
3184 * safe, and trust userspace not to race with
3185 * itself
3187 rdev->sectors = oldsectors;
3188 return -EBUSY;
3191 return len;
3194 static struct rdev_sysfs_entry rdev_size =
3195 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3197 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3199 unsigned long long recovery_start = rdev->recovery_offset;
3201 if (test_bit(In_sync, &rdev->flags) ||
3202 recovery_start == MaxSector)
3203 return sprintf(page, "none\n");
3205 return sprintf(page, "%llu\n", recovery_start);
3208 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3210 unsigned long long recovery_start;
3212 if (cmd_match(buf, "none"))
3213 recovery_start = MaxSector;
3214 else if (kstrtoull(buf, 10, &recovery_start))
3215 return -EINVAL;
3217 if (rdev->mddev->pers &&
3218 rdev->raid_disk >= 0)
3219 return -EBUSY;
3221 rdev->recovery_offset = recovery_start;
3222 if (recovery_start == MaxSector)
3223 set_bit(In_sync, &rdev->flags);
3224 else
3225 clear_bit(In_sync, &rdev->flags);
3226 return len;
3229 static struct rdev_sysfs_entry rdev_recovery_start =
3230 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3232 /* sysfs access to bad-blocks list.
3233 * We present two files.
3234 * 'bad-blocks' lists sector numbers and lengths of ranges that
3235 * are recorded as bad. The list is truncated to fit within
3236 * the one-page limit of sysfs.
3237 * Writing "sector length" to this file adds an acknowledged
3238 * bad block list.
3239 * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
3240 * been acknowledged. Writing to this file adds bad blocks
3241 * without acknowledging them. This is largely for testing.
3243 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3245 return badblocks_show(&rdev->badblocks, page, 0);
3247 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3249 int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3250 /* Maybe that ack was all we needed */
3251 if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3252 wake_up(&rdev->blocked_wait);
3253 return rv;
3255 static struct rdev_sysfs_entry rdev_bad_blocks =
3256 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3258 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3260 return badblocks_show(&rdev->badblocks, page, 1);
3262 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3264 return badblocks_store(&rdev->badblocks, page, len, 1);
3266 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3267 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3269 static ssize_t
3270 ppl_sector_show(struct md_rdev *rdev, char *page)
3272 return sprintf(page, "%llu\n", (unsigned long long)rdev->ppl.sector);
3275 static ssize_t
3276 ppl_sector_store(struct md_rdev *rdev, const char *buf, size_t len)
3278 unsigned long long sector;
3280 if (kstrtoull(buf, 10, &sector) < 0)
3281 return -EINVAL;
3282 if (sector != (sector_t)sector)
3283 return -EINVAL;
3285 if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3286 rdev->raid_disk >= 0)
3287 return -EBUSY;
3289 if (rdev->mddev->persistent) {
3290 if (rdev->mddev->major_version == 0)
3291 return -EINVAL;
3292 if ((sector > rdev->sb_start &&
3293 sector - rdev->sb_start > S16_MAX) ||
3294 (sector < rdev->sb_start &&
3295 rdev->sb_start - sector > -S16_MIN))
3296 return -EINVAL;
3297 rdev->ppl.offset = sector - rdev->sb_start;
3298 } else if (!rdev->mddev->external) {
3299 return -EBUSY;
3301 rdev->ppl.sector = sector;
3302 return len;
3305 static struct rdev_sysfs_entry rdev_ppl_sector =
3306 __ATTR(ppl_sector, S_IRUGO|S_IWUSR, ppl_sector_show, ppl_sector_store);
3308 static ssize_t
3309 ppl_size_show(struct md_rdev *rdev, char *page)
3311 return sprintf(page, "%u\n", rdev->ppl.size);
3314 static ssize_t
3315 ppl_size_store(struct md_rdev *rdev, const char *buf, size_t len)
3317 unsigned int size;
3319 if (kstrtouint(buf, 10, &size) < 0)
3320 return -EINVAL;
3322 if (rdev->mddev->pers && test_bit(MD_HAS_PPL, &rdev->mddev->flags) &&
3323 rdev->raid_disk >= 0)
3324 return -EBUSY;
3326 if (rdev->mddev->persistent) {
3327 if (rdev->mddev->major_version == 0)
3328 return -EINVAL;
3329 if (size > U16_MAX)
3330 return -EINVAL;
3331 } else if (!rdev->mddev->external) {
3332 return -EBUSY;
3334 rdev->ppl.size = size;
3335 return len;
3338 static struct rdev_sysfs_entry rdev_ppl_size =
3339 __ATTR(ppl_size, S_IRUGO|S_IWUSR, ppl_size_show, ppl_size_store);
3341 static struct attribute *rdev_default_attrs[] = {
3342 &rdev_state.attr,
3343 &rdev_errors.attr,
3344 &rdev_slot.attr,
3345 &rdev_offset.attr,
3346 &rdev_new_offset.attr,
3347 &rdev_size.attr,
3348 &rdev_recovery_start.attr,
3349 &rdev_bad_blocks.attr,
3350 &rdev_unack_bad_blocks.attr,
3351 &rdev_ppl_sector.attr,
3352 &rdev_ppl_size.attr,
3353 NULL,
3355 static ssize_t
3356 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3358 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3359 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3361 if (!entry->show)
3362 return -EIO;
3363 if (!rdev->mddev)
3364 return -EBUSY;
3365 return entry->show(rdev, page);
3368 static ssize_t
3369 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3370 const char *page, size_t length)
3372 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3373 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3374 ssize_t rv;
3375 struct mddev *mddev = rdev->mddev;
3377 if (!entry->store)
3378 return -EIO;
3379 if (!capable(CAP_SYS_ADMIN))
3380 return -EACCES;
3381 rv = mddev ? mddev_lock(mddev): -EBUSY;
3382 if (!rv) {
3383 if (rdev->mddev == NULL)
3384 rv = -EBUSY;
3385 else
3386 rv = entry->store(rdev, page, length);
3387 mddev_unlock(mddev);
3389 return rv;
3392 static void rdev_free(struct kobject *ko)
3394 struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3395 kfree(rdev);
3397 static const struct sysfs_ops rdev_sysfs_ops = {
3398 .show = rdev_attr_show,
3399 .store = rdev_attr_store,
3401 static struct kobj_type rdev_ktype = {
3402 .release = rdev_free,
3403 .sysfs_ops = &rdev_sysfs_ops,
3404 .default_attrs = rdev_default_attrs,
3407 int md_rdev_init(struct md_rdev *rdev)
3409 rdev->desc_nr = -1;
3410 rdev->saved_raid_disk = -1;
3411 rdev->raid_disk = -1;
3412 rdev->flags = 0;
3413 rdev->data_offset = 0;
3414 rdev->new_data_offset = 0;
3415 rdev->sb_events = 0;
3416 rdev->last_read_error = 0;
3417 rdev->sb_loaded = 0;
3418 rdev->bb_page = NULL;
3419 atomic_set(&rdev->nr_pending, 0);
3420 atomic_set(&rdev->read_errors, 0);
3421 atomic_set(&rdev->corrected_errors, 0);
3423 INIT_LIST_HEAD(&rdev->same_set);
3424 init_waitqueue_head(&rdev->blocked_wait);
3426 /* Add space to store bad block list.
3427 * This reserves the space even on arrays where it cannot
3428 * be used - I wonder if that matters
3430 return badblocks_init(&rdev->badblocks, 0);
3432 EXPORT_SYMBOL_GPL(md_rdev_init);
3434 * Import a device. If 'super_format' >= 0, then sanity check the superblock
3436 * mark the device faulty if:
3438 * - the device is nonexistent (zero size)
3439 * - the device has no valid superblock
3441 * a faulty rdev _never_ has rdev->sb set.
3443 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3445 char b[BDEVNAME_SIZE];
3446 int err;
3447 struct md_rdev *rdev;
3448 sector_t size;
3450 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3451 if (!rdev)
3452 return ERR_PTR(-ENOMEM);
3454 err = md_rdev_init(rdev);
3455 if (err)
3456 goto abort_free;
3457 err = alloc_disk_sb(rdev);
3458 if (err)
3459 goto abort_free;
3461 err = lock_rdev(rdev, newdev, super_format == -2);
3462 if (err)
3463 goto abort_free;
3465 kobject_init(&rdev->kobj, &rdev_ktype);
3467 size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3468 if (!size) {
3469 pr_warn("md: %s has zero or unknown size, marking faulty!\n",
3470 bdevname(rdev->bdev,b));
3471 err = -EINVAL;
3472 goto abort_free;
3475 if (super_format >= 0) {
3476 err = super_types[super_format].
3477 load_super(rdev, NULL, super_minor);
3478 if (err == -EINVAL) {
3479 pr_warn("md: %s does not have a valid v%d.%d superblock, not importing!\n",
3480 bdevname(rdev->bdev,b),
3481 super_format, super_minor);
3482 goto abort_free;
3484 if (err < 0) {
3485 pr_warn("md: could not read %s's sb, not importing!\n",
3486 bdevname(rdev->bdev,b));
3487 goto abort_free;
3491 return rdev;
3493 abort_free:
3494 if (rdev->bdev)
3495 unlock_rdev(rdev);
3496 md_rdev_clear(rdev);
3497 kfree(rdev);
3498 return ERR_PTR(err);
3502 * Check a full RAID array for plausibility
3505 static void analyze_sbs(struct mddev *mddev)
3507 int i;
3508 struct md_rdev *rdev, *freshest, *tmp;
3509 char b[BDEVNAME_SIZE];
3511 freshest = NULL;
3512 rdev_for_each_safe(rdev, tmp, mddev)
3513 switch (super_types[mddev->major_version].
3514 load_super(rdev, freshest, mddev->minor_version)) {
3515 case 1:
3516 freshest = rdev;
3517 break;
3518 case 0:
3519 break;
3520 default:
3521 pr_warn("md: fatal superblock inconsistency in %s -- removing from array\n",
3522 bdevname(rdev->bdev,b));
3523 md_kick_rdev_from_array(rdev);
3526 super_types[mddev->major_version].
3527 validate_super(mddev, freshest);
3529 i = 0;
3530 rdev_for_each_safe(rdev, tmp, mddev) {
3531 if (mddev->max_disks &&
3532 (rdev->desc_nr >= mddev->max_disks ||
3533 i > mddev->max_disks)) {
3534 pr_warn("md: %s: %s: only %d devices permitted\n",
3535 mdname(mddev), bdevname(rdev->bdev, b),
3536 mddev->max_disks);
3537 md_kick_rdev_from_array(rdev);
3538 continue;
3540 if (rdev != freshest) {
3541 if (super_types[mddev->major_version].
3542 validate_super(mddev, rdev)) {
3543 pr_warn("md: kicking non-fresh %s from array!\n",
3544 bdevname(rdev->bdev,b));
3545 md_kick_rdev_from_array(rdev);
3546 continue;
3549 if (mddev->level == LEVEL_MULTIPATH) {
3550 rdev->desc_nr = i++;
3551 rdev->raid_disk = rdev->desc_nr;
3552 set_bit(In_sync, &rdev->flags);
3553 } else if (rdev->raid_disk >=
3554 (mddev->raid_disks - min(0, mddev->delta_disks)) &&
3555 !test_bit(Journal, &rdev->flags)) {
3556 rdev->raid_disk = -1;
3557 clear_bit(In_sync, &rdev->flags);
3562 /* Read a fixed-point number.
3563 * Numbers in sysfs attributes should be in "standard" units where
3564 * possible, so time should be in seconds.
3565 * However we internally use a a much smaller unit such as
3566 * milliseconds or jiffies.
3567 * This function takes a decimal number with a possible fractional
3568 * component, and produces an integer which is the result of
3569 * multiplying that number by 10^'scale'.
3570 * all without any floating-point arithmetic.
3572 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3574 unsigned long result = 0;
3575 long decimals = -1;
3576 while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3577 if (*cp == '.')
3578 decimals = 0;
3579 else if (decimals < scale) {
3580 unsigned int value;
3581 value = *cp - '0';
3582 result = result * 10 + value;
3583 if (decimals >= 0)
3584 decimals++;
3586 cp++;
3588 if (*cp == '\n')
3589 cp++;
3590 if (*cp)
3591 return -EINVAL;
3592 if (decimals < 0)
3593 decimals = 0;
3594 while (decimals < scale) {
3595 result *= 10;
3596 decimals ++;
3598 *res = result;
3599 return 0;
3602 static ssize_t
3603 safe_delay_show(struct mddev *mddev, char *page)
3605 int msec = (mddev->safemode_delay*1000)/HZ;
3606 return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3608 static ssize_t
3609 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3611 unsigned long msec;
3613 if (mddev_is_clustered(mddev)) {
3614 pr_warn("md: Safemode is disabled for clustered mode\n");
3615 return -EINVAL;
3618 if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3619 return -EINVAL;
3620 if (msec == 0)
3621 mddev->safemode_delay = 0;
3622 else {
3623 unsigned long old_delay = mddev->safemode_delay;
3624 unsigned long new_delay = (msec*HZ)/1000;
3626 if (new_delay == 0)
3627 new_delay = 1;
3628 mddev->safemode_delay = new_delay;
3629 if (new_delay < old_delay || old_delay == 0)
3630 mod_timer(&mddev->safemode_timer, jiffies+1);
3632 return len;
3634 static struct md_sysfs_entry md_safe_delay =
3635 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3637 static ssize_t
3638 level_show(struct mddev *mddev, char *page)
3640 struct md_personality *p;
3641 int ret;
3642 spin_lock(&mddev->lock);
3643 p = mddev->pers;
3644 if (p)
3645 ret = sprintf(page, "%s\n", p->name);
3646 else if (mddev->clevel[0])
3647 ret = sprintf(page, "%s\n", mddev->clevel);
3648 else if (mddev->level != LEVEL_NONE)
3649 ret = sprintf(page, "%d\n", mddev->level);
3650 else
3651 ret = 0;
3652 spin_unlock(&mddev->lock);
3653 return ret;
3656 static ssize_t
3657 level_store(struct mddev *mddev, const char *buf, size_t len)
3659 char clevel[16];
3660 ssize_t rv;
3661 size_t slen = len;
3662 struct md_personality *pers, *oldpers;
3663 long level;
3664 void *priv, *oldpriv;
3665 struct md_rdev *rdev;
3667 if (slen == 0 || slen >= sizeof(clevel))
3668 return -EINVAL;
3670 rv = mddev_lock(mddev);
3671 if (rv)
3672 return rv;
3674 if (mddev->pers == NULL) {
3675 strncpy(mddev->clevel, buf, slen);
3676 if (mddev->clevel[slen-1] == '\n')
3677 slen--;
3678 mddev->clevel[slen] = 0;
3679 mddev->level = LEVEL_NONE;
3680 rv = len;
3681 goto out_unlock;
3683 rv = -EROFS;
3684 if (mddev->ro)
3685 goto out_unlock;
3687 /* request to change the personality. Need to ensure:
3688 * - array is not engaged in resync/recovery/reshape
3689 * - old personality can be suspended
3690 * - new personality will access other array.
3693 rv = -EBUSY;
3694 if (mddev->sync_thread ||
3695 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3696 mddev->reshape_position != MaxSector ||
3697 mddev->sysfs_active)
3698 goto out_unlock;
3700 rv = -EINVAL;
3701 if (!mddev->pers->quiesce) {
3702 pr_warn("md: %s: %s does not support online personality change\n",
3703 mdname(mddev), mddev->pers->name);
3704 goto out_unlock;
3707 /* Now find the new personality */
3708 strncpy(clevel, buf, slen);
3709 if (clevel[slen-1] == '\n')
3710 slen--;
3711 clevel[slen] = 0;
3712 if (kstrtol(clevel, 10, &level))
3713 level = LEVEL_NONE;
3715 if (request_module("md-%s", clevel) != 0)
3716 request_module("md-level-%s", clevel);
3717 spin_lock(&pers_lock);
3718 pers = find_pers(level, clevel);
3719 if (!pers || !try_module_get(pers->owner)) {
3720 spin_unlock(&pers_lock);
3721 pr_warn("md: personality %s not loaded\n", clevel);
3722 rv = -EINVAL;
3723 goto out_unlock;
3725 spin_unlock(&pers_lock);
3727 if (pers == mddev->pers) {
3728 /* Nothing to do! */
3729 module_put(pers->owner);
3730 rv = len;
3731 goto out_unlock;
3733 if (!pers->takeover) {
3734 module_put(pers->owner);
3735 pr_warn("md: %s: %s does not support personality takeover\n",
3736 mdname(mddev), clevel);
3737 rv = -EINVAL;
3738 goto out_unlock;
3741 rdev_for_each(rdev, mddev)
3742 rdev->new_raid_disk = rdev->raid_disk;
3744 /* ->takeover must set new_* and/or delta_disks
3745 * if it succeeds, and may set them when it fails.
3747 priv = pers->takeover(mddev);
3748 if (IS_ERR(priv)) {
3749 mddev->new_level = mddev->level;
3750 mddev->new_layout = mddev->layout;
3751 mddev->new_chunk_sectors = mddev->chunk_sectors;
3752 mddev->raid_disks -= mddev->delta_disks;
3753 mddev->delta_disks = 0;
3754 mddev->reshape_backwards = 0;
3755 module_put(pers->owner);
3756 pr_warn("md: %s: %s would not accept array\n",
3757 mdname(mddev), clevel);
3758 rv = PTR_ERR(priv);
3759 goto out_unlock;
3762 /* Looks like we have a winner */
3763 mddev_suspend(mddev);
3764 mddev_detach(mddev);
3766 spin_lock(&mddev->lock);
3767 oldpers = mddev->pers;
3768 oldpriv = mddev->private;
3769 mddev->pers = pers;
3770 mddev->private = priv;
3771 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3772 mddev->level = mddev->new_level;
3773 mddev->layout = mddev->new_layout;
3774 mddev->chunk_sectors = mddev->new_chunk_sectors;
3775 mddev->delta_disks = 0;
3776 mddev->reshape_backwards = 0;
3777 mddev->degraded = 0;
3778 spin_unlock(&mddev->lock);
3780 if (oldpers->sync_request == NULL &&
3781 mddev->external) {
3782 /* We are converting from a no-redundancy array
3783 * to a redundancy array and metadata is managed
3784 * externally so we need to be sure that writes
3785 * won't block due to a need to transition
3786 * clean->dirty
3787 * until external management is started.
3789 mddev->in_sync = 0;
3790 mddev->safemode_delay = 0;
3791 mddev->safemode = 0;
3794 oldpers->free(mddev, oldpriv);
3796 if (oldpers->sync_request == NULL &&
3797 pers->sync_request != NULL) {
3798 /* need to add the md_redundancy_group */
3799 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3800 pr_warn("md: cannot register extra attributes for %s\n",
3801 mdname(mddev));
3802 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, "sync_action");
3804 if (oldpers->sync_request != NULL &&
3805 pers->sync_request == NULL) {
3806 /* need to remove the md_redundancy_group */
3807 if (mddev->to_remove == NULL)
3808 mddev->to_remove = &md_redundancy_group;
3811 module_put(oldpers->owner);
3813 rdev_for_each(rdev, mddev) {
3814 if (rdev->raid_disk < 0)
3815 continue;
3816 if (rdev->new_raid_disk >= mddev->raid_disks)
3817 rdev->new_raid_disk = -1;
3818 if (rdev->new_raid_disk == rdev->raid_disk)
3819 continue;
3820 sysfs_unlink_rdev(mddev, rdev);
3822 rdev_for_each(rdev, mddev) {
3823 if (rdev->raid_disk < 0)
3824 continue;
3825 if (rdev->new_raid_disk == rdev->raid_disk)
3826 continue;
3827 rdev->raid_disk = rdev->new_raid_disk;
3828 if (rdev->raid_disk < 0)
3829 clear_bit(In_sync, &rdev->flags);
3830 else {
3831 if (sysfs_link_rdev(mddev, rdev))
3832 pr_warn("md: cannot register rd%d for %s after level change\n",
3833 rdev->raid_disk, mdname(mddev));
3837 if (pers->sync_request == NULL) {
3838 /* this is now an array without redundancy, so
3839 * it must always be in_sync
3841 mddev->in_sync = 1;
3842 del_timer_sync(&mddev->safemode_timer);
3844 blk_set_stacking_limits(&mddev->queue->limits);
3845 pers->run(mddev);
3846 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
3847 mddev_resume(mddev);
3848 if (!mddev->thread)
3849 md_update_sb(mddev, 1);
3850 sysfs_notify(&mddev->kobj, NULL, "level");
3851 md_new_event(mddev);
3852 rv = len;
3853 out_unlock:
3854 mddev_unlock(mddev);
3855 return rv;
3858 static struct md_sysfs_entry md_level =
3859 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3861 static ssize_t
3862 layout_show(struct mddev *mddev, char *page)
3864 /* just a number, not meaningful for all levels */
3865 if (mddev->reshape_position != MaxSector &&
3866 mddev->layout != mddev->new_layout)
3867 return sprintf(page, "%d (%d)\n",
3868 mddev->new_layout, mddev->layout);
3869 return sprintf(page, "%d\n", mddev->layout);
3872 static ssize_t
3873 layout_store(struct mddev *mddev, const char *buf, size_t len)
3875 unsigned int n;
3876 int err;
3878 err = kstrtouint(buf, 10, &n);
3879 if (err < 0)
3880 return err;
3881 err = mddev_lock(mddev);
3882 if (err)
3883 return err;
3885 if (mddev->pers) {
3886 if (mddev->pers->check_reshape == NULL)
3887 err = -EBUSY;
3888 else if (mddev->ro)
3889 err = -EROFS;
3890 else {
3891 mddev->new_layout = n;
3892 err = mddev->pers->check_reshape(mddev);
3893 if (err)
3894 mddev->new_layout = mddev->layout;
3896 } else {
3897 mddev->new_layout = n;
3898 if (mddev->reshape_position == MaxSector)
3899 mddev->layout = n;
3901 mddev_unlock(mddev);
3902 return err ?: len;
3904 static struct md_sysfs_entry md_layout =
3905 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3907 static ssize_t
3908 raid_disks_show(struct mddev *mddev, char *page)
3910 if (mddev->raid_disks == 0)
3911 return 0;
3912 if (mddev->reshape_position != MaxSector &&
3913 mddev->delta_disks != 0)
3914 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3915 mddev->raid_disks - mddev->delta_disks);
3916 return sprintf(page, "%d\n", mddev->raid_disks);
3919 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3921 static ssize_t
3922 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3924 unsigned int n;
3925 int err;
3927 err = kstrtouint(buf, 10, &n);
3928 if (err < 0)
3929 return err;
3931 err = mddev_lock(mddev);
3932 if (err)
3933 return err;
3934 if (mddev->pers)
3935 err = update_raid_disks(mddev, n);
3936 else if (mddev->reshape_position != MaxSector) {
3937 struct md_rdev *rdev;
3938 int olddisks = mddev->raid_disks - mddev->delta_disks;
3940 err = -EINVAL;
3941 rdev_for_each(rdev, mddev) {
3942 if (olddisks < n &&
3943 rdev->data_offset < rdev->new_data_offset)
3944 goto out_unlock;
3945 if (olddisks > n &&
3946 rdev->data_offset > rdev->new_data_offset)
3947 goto out_unlock;
3949 err = 0;
3950 mddev->delta_disks = n - olddisks;
3951 mddev->raid_disks = n;
3952 mddev->reshape_backwards = (mddev->delta_disks < 0);
3953 } else
3954 mddev->raid_disks = n;
3955 out_unlock:
3956 mddev_unlock(mddev);
3957 return err ? err : len;
3959 static struct md_sysfs_entry md_raid_disks =
3960 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3962 static ssize_t
3963 chunk_size_show(struct mddev *mddev, char *page)
3965 if (mddev->reshape_position != MaxSector &&
3966 mddev->chunk_sectors != mddev->new_chunk_sectors)
3967 return sprintf(page, "%d (%d)\n",
3968 mddev->new_chunk_sectors << 9,
3969 mddev->chunk_sectors << 9);
3970 return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3973 static ssize_t
3974 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3976 unsigned long n;
3977 int err;
3979 err = kstrtoul(buf, 10, &n);
3980 if (err < 0)
3981 return err;
3983 err = mddev_lock(mddev);
3984 if (err)
3985 return err;
3986 if (mddev->pers) {
3987 if (mddev->pers->check_reshape == NULL)
3988 err = -EBUSY;
3989 else if (mddev->ro)
3990 err = -EROFS;
3991 else {
3992 mddev->new_chunk_sectors = n >> 9;
3993 err = mddev->pers->check_reshape(mddev);
3994 if (err)
3995 mddev->new_chunk_sectors = mddev->chunk_sectors;
3997 } else {
3998 mddev->new_chunk_sectors = n >> 9;
3999 if (mddev->reshape_position == MaxSector)
4000 mddev->chunk_sectors = n >> 9;
4002 mddev_unlock(mddev);
4003 return err ?: len;
4005 static struct md_sysfs_entry md_chunk_size =
4006 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
4008 static ssize_t
4009 resync_start_show(struct mddev *mddev, char *page)
4011 if (mddev->recovery_cp == MaxSector)
4012 return sprintf(page, "none\n");
4013 return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
4016 static ssize_t
4017 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
4019 unsigned long long n;
4020 int err;
4022 if (cmd_match(buf, "none"))
4023 n = MaxSector;
4024 else {
4025 err = kstrtoull(buf, 10, &n);
4026 if (err < 0)
4027 return err;
4028 if (n != (sector_t)n)
4029 return -EINVAL;
4032 err = mddev_lock(mddev);
4033 if (err)
4034 return err;
4035 if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4036 err = -EBUSY;
4038 if (!err) {
4039 mddev->recovery_cp = n;
4040 if (mddev->pers)
4041 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
4043 mddev_unlock(mddev);
4044 return err ?: len;
4046 static struct md_sysfs_entry md_resync_start =
4047 __ATTR_PREALLOC(resync_start, S_IRUGO|S_IWUSR,
4048 resync_start_show, resync_start_store);
4051 * The array state can be:
4053 * clear
4054 * No devices, no size, no level
4055 * Equivalent to STOP_ARRAY ioctl
4056 * inactive
4057 * May have some settings, but array is not active
4058 * all IO results in error
4059 * When written, doesn't tear down array, but just stops it
4060 * suspended (not supported yet)
4061 * All IO requests will block. The array can be reconfigured.
4062 * Writing this, if accepted, will block until array is quiescent
4063 * readonly
4064 * no resync can happen. no superblocks get written.
4065 * write requests fail
4066 * read-auto
4067 * like readonly, but behaves like 'clean' on a write request.
4069 * clean - no pending writes, but otherwise active.
4070 * When written to inactive array, starts without resync
4071 * If a write request arrives then
4072 * if metadata is known, mark 'dirty' and switch to 'active'.
4073 * if not known, block and switch to write-pending
4074 * If written to an active array that has pending writes, then fails.
4075 * active
4076 * fully active: IO and resync can be happening.
4077 * When written to inactive array, starts with resync
4079 * write-pending
4080 * clean, but writes are blocked waiting for 'active' to be written.
4082 * active-idle
4083 * like active, but no writes have been seen for a while (100msec).
4086 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
4087 write_pending, active_idle, bad_word};
4088 static char *array_states[] = {
4089 "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
4090 "write-pending", "active-idle", NULL };
4092 static int match_word(const char *word, char **list)
4094 int n;
4095 for (n=0; list[n]; n++)
4096 if (cmd_match(word, list[n]))
4097 break;
4098 return n;
4101 static ssize_t
4102 array_state_show(struct mddev *mddev, char *page)
4104 enum array_state st = inactive;
4106 if (mddev->pers)
4107 switch(mddev->ro) {
4108 case 1:
4109 st = readonly;
4110 break;
4111 case 2:
4112 st = read_auto;
4113 break;
4114 case 0:
4115 spin_lock(&mddev->lock);
4116 if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
4117 st = write_pending;
4118 else if (mddev->in_sync)
4119 st = clean;
4120 else if (mddev->safemode)
4121 st = active_idle;
4122 else
4123 st = active;
4124 spin_unlock(&mddev->lock);
4126 else {
4127 if (list_empty(&mddev->disks) &&
4128 mddev->raid_disks == 0 &&
4129 mddev->dev_sectors == 0)
4130 st = clear;
4131 else
4132 st = inactive;
4134 return sprintf(page, "%s\n", array_states[st]);
4137 static int do_md_stop(struct mddev *mddev, int ro, struct block_device *bdev);
4138 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev);
4139 static int do_md_run(struct mddev *mddev);
4140 static int restart_array(struct mddev *mddev);
4142 static ssize_t
4143 array_state_store(struct mddev *mddev, const char *buf, size_t len)
4145 int err = 0;
4146 enum array_state st = match_word(buf, array_states);
4148 if (mddev->pers && (st == active || st == clean) && mddev->ro != 1) {
4149 /* don't take reconfig_mutex when toggling between
4150 * clean and active
4152 spin_lock(&mddev->lock);
4153 if (st == active) {
4154 restart_array(mddev);
4155 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4156 md_wakeup_thread(mddev->thread);
4157 wake_up(&mddev->sb_wait);
4158 } else /* st == clean */ {
4159 restart_array(mddev);
4160 if (!set_in_sync(mddev))
4161 err = -EBUSY;
4163 if (!err)
4164 sysfs_notify_dirent_safe(mddev->sysfs_state);
4165 spin_unlock(&mddev->lock);
4166 return err ?: len;
4168 err = mddev_lock(mddev);
4169 if (err)
4170 return err;
4171 err = -EINVAL;
4172 switch(st) {
4173 case bad_word:
4174 break;
4175 case clear:
4176 /* stopping an active array */
4177 err = do_md_stop(mddev, 0, NULL);
4178 break;
4179 case inactive:
4180 /* stopping an active array */
4181 if (mddev->pers)
4182 err = do_md_stop(mddev, 2, NULL);
4183 else
4184 err = 0; /* already inactive */
4185 break;
4186 case suspended:
4187 break; /* not supported yet */
4188 case readonly:
4189 if (mddev->pers)
4190 err = md_set_readonly(mddev, NULL);
4191 else {
4192 mddev->ro = 1;
4193 set_disk_ro(mddev->gendisk, 1);
4194 err = do_md_run(mddev);
4196 break;
4197 case read_auto:
4198 if (mddev->pers) {
4199 if (mddev->ro == 0)
4200 err = md_set_readonly(mddev, NULL);
4201 else if (mddev->ro == 1)
4202 err = restart_array(mddev);
4203 if (err == 0) {
4204 mddev->ro = 2;
4205 set_disk_ro(mddev->gendisk, 0);
4207 } else {
4208 mddev->ro = 2;
4209 err = do_md_run(mddev);
4211 break;
4212 case clean:
4213 if (mddev->pers) {
4214 err = restart_array(mddev);
4215 if (err)
4216 break;
4217 spin_lock(&mddev->lock);
4218 if (!set_in_sync(mddev))
4219 err = -EBUSY;
4220 spin_unlock(&mddev->lock);
4221 } else
4222 err = -EINVAL;
4223 break;
4224 case active:
4225 if (mddev->pers) {
4226 err = restart_array(mddev);
4227 if (err)
4228 break;
4229 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
4230 wake_up(&mddev->sb_wait);
4231 err = 0;
4232 } else {
4233 mddev->ro = 0;
4234 set_disk_ro(mddev->gendisk, 0);
4235 err = do_md_run(mddev);
4237 break;
4238 case write_pending:
4239 case active_idle:
4240 /* these cannot be set */
4241 break;
4244 if (!err) {
4245 if (mddev->hold_active == UNTIL_IOCTL)
4246 mddev->hold_active = 0;
4247 sysfs_notify_dirent_safe(mddev->sysfs_state);
4249 mddev_unlock(mddev);
4250 return err ?: len;
4252 static struct md_sysfs_entry md_array_state =
4253 __ATTR_PREALLOC(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
4255 static ssize_t
4256 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
4257 return sprintf(page, "%d\n",
4258 atomic_read(&mddev->max_corr_read_errors));
4261 static ssize_t
4262 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
4264 unsigned int n;
4265 int rv;
4267 rv = kstrtouint(buf, 10, &n);
4268 if (rv < 0)
4269 return rv;
4270 atomic_set(&mddev->max_corr_read_errors, n);
4271 return len;
4274 static struct md_sysfs_entry max_corr_read_errors =
4275 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
4276 max_corrected_read_errors_store);
4278 static ssize_t
4279 null_show(struct mddev *mddev, char *page)
4281 return -EINVAL;
4284 static ssize_t
4285 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
4287 /* buf must be %d:%d\n? giving major and minor numbers */
4288 /* The new device is added to the array.
4289 * If the array has a persistent superblock, we read the
4290 * superblock to initialise info and check validity.
4291 * Otherwise, only checking done is that in bind_rdev_to_array,
4292 * which mainly checks size.
4294 char *e;
4295 int major = simple_strtoul(buf, &e, 10);
4296 int minor;
4297 dev_t dev;
4298 struct md_rdev *rdev;
4299 int err;
4301 if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
4302 return -EINVAL;
4303 minor = simple_strtoul(e+1, &e, 10);
4304 if (*e && *e != '\n')
4305 return -EINVAL;
4306 dev = MKDEV(major, minor);
4307 if (major != MAJOR(dev) ||
4308 minor != MINOR(dev))
4309 return -EOVERFLOW;
4311 flush_workqueue(md_misc_wq);
4313 err = mddev_lock(mddev);
4314 if (err)
4315 return err;
4316 if (mddev->persistent) {
4317 rdev = md_import_device(dev, mddev->major_version,
4318 mddev->minor_version);
4319 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
4320 struct md_rdev *rdev0
4321 = list_entry(mddev->disks.next,
4322 struct md_rdev, same_set);
4323 err = super_types[mddev->major_version]
4324 .load_super(rdev, rdev0, mddev->minor_version);
4325 if (err < 0)
4326 goto out;
4328 } else if (mddev->external)
4329 rdev = md_import_device(dev, -2, -1);
4330 else
4331 rdev = md_import_device(dev, -1, -1);
4333 if (IS_ERR(rdev)) {
4334 mddev_unlock(mddev);
4335 return PTR_ERR(rdev);
4337 err = bind_rdev_to_array(rdev, mddev);
4338 out:
4339 if (err)
4340 export_rdev(rdev);
4341 mddev_unlock(mddev);
4342 if (!err)
4343 md_new_event(mddev);
4344 return err ? err : len;
4347 static struct md_sysfs_entry md_new_device =
4348 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4350 static ssize_t
4351 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4353 char *end;
4354 unsigned long chunk, end_chunk;
4355 int err;
4357 err = mddev_lock(mddev);
4358 if (err)
4359 return err;
4360 if (!mddev->bitmap)
4361 goto out;
4362 /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4363 while (*buf) {
4364 chunk = end_chunk = simple_strtoul(buf, &end, 0);
4365 if (buf == end) break;
4366 if (*end == '-') { /* range */
4367 buf = end + 1;
4368 end_chunk = simple_strtoul(buf, &end, 0);
4369 if (buf == end) break;
4371 if (*end && !isspace(*end)) break;
4372 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4373 buf = skip_spaces(end);
4375 bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4376 out:
4377 mddev_unlock(mddev);
4378 return len;
4381 static struct md_sysfs_entry md_bitmap =
4382 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4384 static ssize_t
4385 size_show(struct mddev *mddev, char *page)
4387 return sprintf(page, "%llu\n",
4388 (unsigned long long)mddev->dev_sectors / 2);
4391 static int update_size(struct mddev *mddev, sector_t num_sectors);
4393 static ssize_t
4394 size_store(struct mddev *mddev, const char *buf, size_t len)
4396 /* If array is inactive, we can reduce the component size, but
4397 * not increase it (except from 0).
4398 * If array is active, we can try an on-line resize
4400 sector_t sectors;
4401 int err = strict_blocks_to_sectors(buf, &sectors);
4403 if (err < 0)
4404 return err;
4405 err = mddev_lock(mddev);
4406 if (err)
4407 return err;
4408 if (mddev->pers) {
4409 err = update_size(mddev, sectors);
4410 if (err == 0)
4411 md_update_sb(mddev, 1);
4412 } else {
4413 if (mddev->dev_sectors == 0 ||
4414 mddev->dev_sectors > sectors)
4415 mddev->dev_sectors = sectors;
4416 else
4417 err = -ENOSPC;
4419 mddev_unlock(mddev);
4420 return err ? err : len;
4423 static struct md_sysfs_entry md_size =
4424 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4426 /* Metadata version.
4427 * This is one of
4428 * 'none' for arrays with no metadata (good luck...)
4429 * 'external' for arrays with externally managed metadata,
4430 * or N.M for internally known formats
4432 static ssize_t
4433 metadata_show(struct mddev *mddev, char *page)
4435 if (mddev->persistent)
4436 return sprintf(page, "%d.%d\n",
4437 mddev->major_version, mddev->minor_version);
4438 else if (mddev->external)
4439 return sprintf(page, "external:%s\n", mddev->metadata_type);
4440 else
4441 return sprintf(page, "none\n");
4444 static ssize_t
4445 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4447 int major, minor;
4448 char *e;
4449 int err;
4450 /* Changing the details of 'external' metadata is
4451 * always permitted. Otherwise there must be
4452 * no devices attached to the array.
4455 err = mddev_lock(mddev);
4456 if (err)
4457 return err;
4458 err = -EBUSY;
4459 if (mddev->external && strncmp(buf, "external:", 9) == 0)
4461 else if (!list_empty(&mddev->disks))
4462 goto out_unlock;
4464 err = 0;
4465 if (cmd_match(buf, "none")) {
4466 mddev->persistent = 0;
4467 mddev->external = 0;
4468 mddev->major_version = 0;
4469 mddev->minor_version = 90;
4470 goto out_unlock;
4472 if (strncmp(buf, "external:", 9) == 0) {
4473 size_t namelen = len-9;
4474 if (namelen >= sizeof(mddev->metadata_type))
4475 namelen = sizeof(mddev->metadata_type)-1;
4476 strncpy(mddev->metadata_type, buf+9, namelen);
4477 mddev->metadata_type[namelen] = 0;
4478 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4479 mddev->metadata_type[--namelen] = 0;
4480 mddev->persistent = 0;
4481 mddev->external = 1;
4482 mddev->major_version = 0;
4483 mddev->minor_version = 90;
4484 goto out_unlock;
4486 major = simple_strtoul(buf, &e, 10);
4487 err = -EINVAL;
4488 if (e==buf || *e != '.')
4489 goto out_unlock;
4490 buf = e+1;
4491 minor = simple_strtoul(buf, &e, 10);
4492 if (e==buf || (*e && *e != '\n') )
4493 goto out_unlock;
4494 err = -ENOENT;
4495 if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4496 goto out_unlock;
4497 mddev->major_version = major;
4498 mddev->minor_version = minor;
4499 mddev->persistent = 1;
4500 mddev->external = 0;
4501 err = 0;
4502 out_unlock:
4503 mddev_unlock(mddev);
4504 return err ?: len;
4507 static struct md_sysfs_entry md_metadata =
4508 __ATTR_PREALLOC(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4510 static ssize_t
4511 action_show(struct mddev *mddev, char *page)
4513 char *type = "idle";
4514 unsigned long recovery = mddev->recovery;
4515 if (test_bit(MD_RECOVERY_FROZEN, &recovery))
4516 type = "frozen";
4517 else if (test_bit(MD_RECOVERY_RUNNING, &recovery) ||
4518 (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &recovery))) {
4519 if (test_bit(MD_RECOVERY_RESHAPE, &recovery))
4520 type = "reshape";
4521 else if (test_bit(MD_RECOVERY_SYNC, &recovery)) {
4522 if (!test_bit(MD_RECOVERY_REQUESTED, &recovery))
4523 type = "resync";
4524 else if (test_bit(MD_RECOVERY_CHECK, &recovery))
4525 type = "check";
4526 else
4527 type = "repair";
4528 } else if (test_bit(MD_RECOVERY_RECOVER, &recovery))
4529 type = "recover";
4530 else if (mddev->reshape_position != MaxSector)
4531 type = "reshape";
4533 return sprintf(page, "%s\n", type);
4536 static ssize_t
4537 action_store(struct mddev *mddev, const char *page, size_t len)
4539 if (!mddev->pers || !mddev->pers->sync_request)
4540 return -EINVAL;
4543 if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4544 if (cmd_match(page, "frozen"))
4545 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4546 else
4547 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4548 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
4549 mddev_lock(mddev) == 0) {
4550 flush_workqueue(md_misc_wq);
4551 if (mddev->sync_thread) {
4552 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4553 md_reap_sync_thread(mddev);
4555 mddev_unlock(mddev);
4557 } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4558 return -EBUSY;
4559 else if (cmd_match(page, "resync"))
4560 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4561 else if (cmd_match(page, "recover")) {
4562 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4563 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4564 } else if (cmd_match(page, "reshape")) {
4565 int err;
4566 if (mddev->pers->start_reshape == NULL)
4567 return -EINVAL;
4568 err = mddev_lock(mddev);
4569 if (!err) {
4570 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4571 err = -EBUSY;
4572 else {
4573 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4574 err = mddev->pers->start_reshape(mddev);
4576 mddev_unlock(mddev);
4578 if (err)
4579 return err;
4580 sysfs_notify(&mddev->kobj, NULL, "degraded");
4581 } else {
4582 if (cmd_match(page, "check"))
4583 set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4584 else if (!cmd_match(page, "repair"))
4585 return -EINVAL;
4586 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4587 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4588 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4590 if (mddev->ro == 2) {
4591 /* A write to sync_action is enough to justify
4592 * canceling read-auto mode
4594 mddev->ro = 0;
4595 md_wakeup_thread(mddev->sync_thread);
4597 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4598 md_wakeup_thread(mddev->thread);
4599 sysfs_notify_dirent_safe(mddev->sysfs_action);
4600 return len;
4603 static struct md_sysfs_entry md_scan_mode =
4604 __ATTR_PREALLOC(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4606 static ssize_t
4607 last_sync_action_show(struct mddev *mddev, char *page)
4609 return sprintf(page, "%s\n", mddev->last_sync_action);
4612 static struct md_sysfs_entry md_last_scan_mode = __ATTR_RO(last_sync_action);
4614 static ssize_t
4615 mismatch_cnt_show(struct mddev *mddev, char *page)
4617 return sprintf(page, "%llu\n",
4618 (unsigned long long)
4619 atomic64_read(&mddev->resync_mismatches));
4622 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4624 static ssize_t
4625 sync_min_show(struct mddev *mddev, char *page)
4627 return sprintf(page, "%d (%s)\n", speed_min(mddev),
4628 mddev->sync_speed_min ? "local": "system");
4631 static ssize_t
4632 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4634 unsigned int min;
4635 int rv;
4637 if (strncmp(buf, "system", 6)==0) {
4638 min = 0;
4639 } else {
4640 rv = kstrtouint(buf, 10, &min);
4641 if (rv < 0)
4642 return rv;
4643 if (min == 0)
4644 return -EINVAL;
4646 mddev->sync_speed_min = min;
4647 return len;
4650 static struct md_sysfs_entry md_sync_min =
4651 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4653 static ssize_t
4654 sync_max_show(struct mddev *mddev, char *page)
4656 return sprintf(page, "%d (%s)\n", speed_max(mddev),
4657 mddev->sync_speed_max ? "local": "system");
4660 static ssize_t
4661 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4663 unsigned int max;
4664 int rv;
4666 if (strncmp(buf, "system", 6)==0) {
4667 max = 0;
4668 } else {
4669 rv = kstrtouint(buf, 10, &max);
4670 if (rv < 0)
4671 return rv;
4672 if (max == 0)
4673 return -EINVAL;
4675 mddev->sync_speed_max = max;
4676 return len;
4679 static struct md_sysfs_entry md_sync_max =
4680 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4682 static ssize_t
4683 degraded_show(struct mddev *mddev, char *page)
4685 return sprintf(page, "%d\n", mddev->degraded);
4687 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4689 static ssize_t
4690 sync_force_parallel_show(struct mddev *mddev, char *page)
4692 return sprintf(page, "%d\n", mddev->parallel_resync);
4695 static ssize_t
4696 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4698 long n;
4700 if (kstrtol(buf, 10, &n))
4701 return -EINVAL;
4703 if (n != 0 && n != 1)
4704 return -EINVAL;
4706 mddev->parallel_resync = n;
4708 if (mddev->sync_thread)
4709 wake_up(&resync_wait);
4711 return len;
4714 /* force parallel resync, even with shared block devices */
4715 static struct md_sysfs_entry md_sync_force_parallel =
4716 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4717 sync_force_parallel_show, sync_force_parallel_store);
4719 static ssize_t
4720 sync_speed_show(struct mddev *mddev, char *page)
4722 unsigned long resync, dt, db;
4723 if (mddev->curr_resync == 0)
4724 return sprintf(page, "none\n");
4725 resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4726 dt = (jiffies - mddev->resync_mark) / HZ;
4727 if (!dt) dt++;
4728 db = resync - mddev->resync_mark_cnt;
4729 return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4732 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4734 static ssize_t
4735 sync_completed_show(struct mddev *mddev, char *page)
4737 unsigned long long max_sectors, resync;
4739 if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4740 return sprintf(page, "none\n");
4742 if (mddev->curr_resync == 1 ||
4743 mddev->curr_resync == 2)
4744 return sprintf(page, "delayed\n");
4746 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4747 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4748 max_sectors = mddev->resync_max_sectors;
4749 else
4750 max_sectors = mddev->dev_sectors;
4752 resync = mddev->curr_resync_completed;
4753 return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4756 static struct md_sysfs_entry md_sync_completed =
4757 __ATTR_PREALLOC(sync_completed, S_IRUGO, sync_completed_show, NULL);
4759 static ssize_t
4760 min_sync_show(struct mddev *mddev, char *page)
4762 return sprintf(page, "%llu\n",
4763 (unsigned long long)mddev->resync_min);
4765 static ssize_t
4766 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4768 unsigned long long min;
4769 int err;
4771 if (kstrtoull(buf, 10, &min))
4772 return -EINVAL;
4774 spin_lock(&mddev->lock);
4775 err = -EINVAL;
4776 if (min > mddev->resync_max)
4777 goto out_unlock;
4779 err = -EBUSY;
4780 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4781 goto out_unlock;
4783 /* Round down to multiple of 4K for safety */
4784 mddev->resync_min = round_down(min, 8);
4785 err = 0;
4787 out_unlock:
4788 spin_unlock(&mddev->lock);
4789 return err ?: len;
4792 static struct md_sysfs_entry md_min_sync =
4793 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4795 static ssize_t
4796 max_sync_show(struct mddev *mddev, char *page)
4798 if (mddev->resync_max == MaxSector)
4799 return sprintf(page, "max\n");
4800 else
4801 return sprintf(page, "%llu\n",
4802 (unsigned long long)mddev->resync_max);
4804 static ssize_t
4805 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4807 int err;
4808 spin_lock(&mddev->lock);
4809 if (strncmp(buf, "max", 3) == 0)
4810 mddev->resync_max = MaxSector;
4811 else {
4812 unsigned long long max;
4813 int chunk;
4815 err = -EINVAL;
4816 if (kstrtoull(buf, 10, &max))
4817 goto out_unlock;
4818 if (max < mddev->resync_min)
4819 goto out_unlock;
4821 err = -EBUSY;
4822 if (max < mddev->resync_max &&
4823 mddev->ro == 0 &&
4824 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4825 goto out_unlock;
4827 /* Must be a multiple of chunk_size */
4828 chunk = mddev->chunk_sectors;
4829 if (chunk) {
4830 sector_t temp = max;
4832 err = -EINVAL;
4833 if (sector_div(temp, chunk))
4834 goto out_unlock;
4836 mddev->resync_max = max;
4838 wake_up(&mddev->recovery_wait);
4839 err = 0;
4840 out_unlock:
4841 spin_unlock(&mddev->lock);
4842 return err ?: len;
4845 static struct md_sysfs_entry md_max_sync =
4846 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4848 static ssize_t
4849 suspend_lo_show(struct mddev *mddev, char *page)
4851 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4854 static ssize_t
4855 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4857 unsigned long long new;
4858 int err;
4860 err = kstrtoull(buf, 10, &new);
4861 if (err < 0)
4862 return err;
4863 if (new != (sector_t)new)
4864 return -EINVAL;
4866 err = mddev_lock(mddev);
4867 if (err)
4868 return err;
4869 err = -EINVAL;
4870 if (mddev->pers == NULL ||
4871 mddev->pers->quiesce == NULL)
4872 goto unlock;
4873 mddev_suspend(mddev);
4874 mddev->suspend_lo = new;
4875 mddev_resume(mddev);
4877 err = 0;
4878 unlock:
4879 mddev_unlock(mddev);
4880 return err ?: len;
4882 static struct md_sysfs_entry md_suspend_lo =
4883 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4885 static ssize_t
4886 suspend_hi_show(struct mddev *mddev, char *page)
4888 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4891 static ssize_t
4892 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4894 unsigned long long new;
4895 int err;
4897 err = kstrtoull(buf, 10, &new);
4898 if (err < 0)
4899 return err;
4900 if (new != (sector_t)new)
4901 return -EINVAL;
4903 err = mddev_lock(mddev);
4904 if (err)
4905 return err;
4906 err = -EINVAL;
4907 if (mddev->pers == NULL)
4908 goto unlock;
4910 mddev_suspend(mddev);
4911 mddev->suspend_hi = new;
4912 mddev_resume(mddev);
4914 err = 0;
4915 unlock:
4916 mddev_unlock(mddev);
4917 return err ?: len;
4919 static struct md_sysfs_entry md_suspend_hi =
4920 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4922 static ssize_t
4923 reshape_position_show(struct mddev *mddev, char *page)
4925 if (mddev->reshape_position != MaxSector)
4926 return sprintf(page, "%llu\n",
4927 (unsigned long long)mddev->reshape_position);
4928 strcpy(page, "none\n");
4929 return 5;
4932 static ssize_t
4933 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4935 struct md_rdev *rdev;
4936 unsigned long long new;
4937 int err;
4939 err = kstrtoull(buf, 10, &new);
4940 if (err < 0)
4941 return err;
4942 if (new != (sector_t)new)
4943 return -EINVAL;
4944 err = mddev_lock(mddev);
4945 if (err)
4946 return err;
4947 err = -EBUSY;
4948 if (mddev->pers)
4949 goto unlock;
4950 mddev->reshape_position = new;
4951 mddev->delta_disks = 0;
4952 mddev->reshape_backwards = 0;
4953 mddev->new_level = mddev->level;
4954 mddev->new_layout = mddev->layout;
4955 mddev->new_chunk_sectors = mddev->chunk_sectors;
4956 rdev_for_each(rdev, mddev)
4957 rdev->new_data_offset = rdev->data_offset;
4958 err = 0;
4959 unlock:
4960 mddev_unlock(mddev);
4961 return err ?: len;
4964 static struct md_sysfs_entry md_reshape_position =
4965 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4966 reshape_position_store);
4968 static ssize_t
4969 reshape_direction_show(struct mddev *mddev, char *page)
4971 return sprintf(page, "%s\n",
4972 mddev->reshape_backwards ? "backwards" : "forwards");
4975 static ssize_t
4976 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
4978 int backwards = 0;
4979 int err;
4981 if (cmd_match(buf, "forwards"))
4982 backwards = 0;
4983 else if (cmd_match(buf, "backwards"))
4984 backwards = 1;
4985 else
4986 return -EINVAL;
4987 if (mddev->reshape_backwards == backwards)
4988 return len;
4990 err = mddev_lock(mddev);
4991 if (err)
4992 return err;
4993 /* check if we are allowed to change */
4994 if (mddev->delta_disks)
4995 err = -EBUSY;
4996 else if (mddev->persistent &&
4997 mddev->major_version == 0)
4998 err = -EINVAL;
4999 else
5000 mddev->reshape_backwards = backwards;
5001 mddev_unlock(mddev);
5002 return err ?: len;
5005 static struct md_sysfs_entry md_reshape_direction =
5006 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
5007 reshape_direction_store);
5009 static ssize_t
5010 array_size_show(struct mddev *mddev, char *page)
5012 if (mddev->external_size)
5013 return sprintf(page, "%llu\n",
5014 (unsigned long long)mddev->array_sectors/2);
5015 else
5016 return sprintf(page, "default\n");
5019 static ssize_t
5020 array_size_store(struct mddev *mddev, const char *buf, size_t len)
5022 sector_t sectors;
5023 int err;
5025 err = mddev_lock(mddev);
5026 if (err)
5027 return err;
5029 /* cluster raid doesn't support change array_sectors */
5030 if (mddev_is_clustered(mddev)) {
5031 mddev_unlock(mddev);
5032 return -EINVAL;
5035 if (strncmp(buf, "default", 7) == 0) {
5036 if (mddev->pers)
5037 sectors = mddev->pers->size(mddev, 0, 0);
5038 else
5039 sectors = mddev->array_sectors;
5041 mddev->external_size = 0;
5042 } else {
5043 if (strict_blocks_to_sectors(buf, &sectors) < 0)
5044 err = -EINVAL;
5045 else if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
5046 err = -E2BIG;
5047 else
5048 mddev->external_size = 1;
5051 if (!err) {
5052 mddev->array_sectors = sectors;
5053 if (mddev->pers) {
5054 set_capacity(mddev->gendisk, mddev->array_sectors);
5055 revalidate_disk(mddev->gendisk);
5058 mddev_unlock(mddev);
5059 return err ?: len;
5062 static struct md_sysfs_entry md_array_size =
5063 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
5064 array_size_store);
5066 static ssize_t
5067 consistency_policy_show(struct mddev *mddev, char *page)
5069 int ret;
5071 if (test_bit(MD_HAS_JOURNAL, &mddev->flags)) {
5072 ret = sprintf(page, "journal\n");
5073 } else if (test_bit(MD_HAS_PPL, &mddev->flags)) {
5074 ret = sprintf(page, "ppl\n");
5075 } else if (mddev->bitmap) {
5076 ret = sprintf(page, "bitmap\n");
5077 } else if (mddev->pers) {
5078 if (mddev->pers->sync_request)
5079 ret = sprintf(page, "resync\n");
5080 else
5081 ret = sprintf(page, "none\n");
5082 } else {
5083 ret = sprintf(page, "unknown\n");
5086 return ret;
5089 static ssize_t
5090 consistency_policy_store(struct mddev *mddev, const char *buf, size_t len)
5092 int err = 0;
5094 if (mddev->pers) {
5095 if (mddev->pers->change_consistency_policy)
5096 err = mddev->pers->change_consistency_policy(mddev, buf);
5097 else
5098 err = -EBUSY;
5099 } else if (mddev->external && strncmp(buf, "ppl", 3) == 0) {
5100 set_bit(MD_HAS_PPL, &mddev->flags);
5101 } else {
5102 err = -EINVAL;
5105 return err ? err : len;
5108 static struct md_sysfs_entry md_consistency_policy =
5109 __ATTR(consistency_policy, S_IRUGO | S_IWUSR, consistency_policy_show,
5110 consistency_policy_store);
5112 static struct attribute *md_default_attrs[] = {
5113 &md_level.attr,
5114 &md_layout.attr,
5115 &md_raid_disks.attr,
5116 &md_chunk_size.attr,
5117 &md_size.attr,
5118 &md_resync_start.attr,
5119 &md_metadata.attr,
5120 &md_new_device.attr,
5121 &md_safe_delay.attr,
5122 &md_array_state.attr,
5123 &md_reshape_position.attr,
5124 &md_reshape_direction.attr,
5125 &md_array_size.attr,
5126 &max_corr_read_errors.attr,
5127 &md_consistency_policy.attr,
5128 NULL,
5131 static struct attribute *md_redundancy_attrs[] = {
5132 &md_scan_mode.attr,
5133 &md_last_scan_mode.attr,
5134 &md_mismatches.attr,
5135 &md_sync_min.attr,
5136 &md_sync_max.attr,
5137 &md_sync_speed.attr,
5138 &md_sync_force_parallel.attr,
5139 &md_sync_completed.attr,
5140 &md_min_sync.attr,
5141 &md_max_sync.attr,
5142 &md_suspend_lo.attr,
5143 &md_suspend_hi.attr,
5144 &md_bitmap.attr,
5145 &md_degraded.attr,
5146 NULL,
5148 static struct attribute_group md_redundancy_group = {
5149 .name = NULL,
5150 .attrs = md_redundancy_attrs,
5153 static ssize_t
5154 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
5156 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5157 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5158 ssize_t rv;
5160 if (!entry->show)
5161 return -EIO;
5162 spin_lock(&all_mddevs_lock);
5163 if (list_empty(&mddev->all_mddevs)) {
5164 spin_unlock(&all_mddevs_lock);
5165 return -EBUSY;
5167 mddev_get(mddev);
5168 spin_unlock(&all_mddevs_lock);
5170 rv = entry->show(mddev, page);
5171 mddev_put(mddev);
5172 return rv;
5175 static ssize_t
5176 md_attr_store(struct kobject *kobj, struct attribute *attr,
5177 const char *page, size_t length)
5179 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
5180 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
5181 ssize_t rv;
5183 if (!entry->store)
5184 return -EIO;
5185 if (!capable(CAP_SYS_ADMIN))
5186 return -EACCES;
5187 spin_lock(&all_mddevs_lock);
5188 if (list_empty(&mddev->all_mddevs)) {
5189 spin_unlock(&all_mddevs_lock);
5190 return -EBUSY;
5192 mddev_get(mddev);
5193 spin_unlock(&all_mddevs_lock);
5194 rv = entry->store(mddev, page, length);
5195 mddev_put(mddev);
5196 return rv;
5199 static void md_free(struct kobject *ko)
5201 struct mddev *mddev = container_of(ko, struct mddev, kobj);
5203 if (mddev->sysfs_state)
5204 sysfs_put(mddev->sysfs_state);
5206 if (mddev->queue)
5207 blk_cleanup_queue(mddev->queue);
5208 if (mddev->gendisk) {
5209 del_gendisk(mddev->gendisk);
5210 put_disk(mddev->gendisk);
5212 percpu_ref_exit(&mddev->writes_pending);
5214 kfree(mddev);
5217 static const struct sysfs_ops md_sysfs_ops = {
5218 .show = md_attr_show,
5219 .store = md_attr_store,
5221 static struct kobj_type md_ktype = {
5222 .release = md_free,
5223 .sysfs_ops = &md_sysfs_ops,
5224 .default_attrs = md_default_attrs,
5227 int mdp_major = 0;
5229 static void mddev_delayed_delete(struct work_struct *ws)
5231 struct mddev *mddev = container_of(ws, struct mddev, del_work);
5233 sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
5234 kobject_del(&mddev->kobj);
5235 kobject_put(&mddev->kobj);
5238 static void no_op(struct percpu_ref *r) {}
5240 int mddev_init_writes_pending(struct mddev *mddev)
5242 if (mddev->writes_pending.percpu_count_ptr)
5243 return 0;
5244 if (percpu_ref_init(&mddev->writes_pending, no_op, 0, GFP_KERNEL) < 0)
5245 return -ENOMEM;
5246 /* We want to start with the refcount at zero */
5247 percpu_ref_put(&mddev->writes_pending);
5248 return 0;
5250 EXPORT_SYMBOL_GPL(mddev_init_writes_pending);
5252 static int md_alloc(dev_t dev, char *name)
5255 * If dev is zero, name is the name of a device to allocate with
5256 * an arbitrary minor number. It will be "md_???"
5257 * If dev is non-zero it must be a device number with a MAJOR of
5258 * MD_MAJOR or mdp_major. In this case, if "name" is NULL, then
5259 * the device is being created by opening a node in /dev.
5260 * If "name" is not NULL, the device is being created by
5261 * writing to /sys/module/md_mod/parameters/new_array.
5263 static DEFINE_MUTEX(disks_mutex);
5264 struct mddev *mddev = mddev_find(dev);
5265 struct gendisk *disk;
5266 int partitioned;
5267 int shift;
5268 int unit;
5269 int error;
5271 if (!mddev)
5272 return -ENODEV;
5274 partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
5275 shift = partitioned ? MdpMinorShift : 0;
5276 unit = MINOR(mddev->unit) >> shift;
5278 /* wait for any previous instance of this device to be
5279 * completely removed (mddev_delayed_delete).
5281 flush_workqueue(md_misc_wq);
5283 mutex_lock(&disks_mutex);
5284 error = -EEXIST;
5285 if (mddev->gendisk)
5286 goto abort;
5288 if (name && !dev) {
5289 /* Need to ensure that 'name' is not a duplicate.
5291 struct mddev *mddev2;
5292 spin_lock(&all_mddevs_lock);
5294 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
5295 if (mddev2->gendisk &&
5296 strcmp(mddev2->gendisk->disk_name, name) == 0) {
5297 spin_unlock(&all_mddevs_lock);
5298 goto abort;
5300 spin_unlock(&all_mddevs_lock);
5302 if (name && dev)
5304 * Creating /dev/mdNNN via "newarray", so adjust hold_active.
5306 mddev->hold_active = UNTIL_STOP;
5308 error = -ENOMEM;
5309 mddev->queue = blk_alloc_queue(GFP_KERNEL);
5310 if (!mddev->queue)
5311 goto abort;
5312 mddev->queue->queuedata = mddev;
5314 blk_queue_make_request(mddev->queue, md_make_request);
5315 blk_set_stacking_limits(&mddev->queue->limits);
5317 disk = alloc_disk(1 << shift);
5318 if (!disk) {
5319 blk_cleanup_queue(mddev->queue);
5320 mddev->queue = NULL;
5321 goto abort;
5323 disk->major = MAJOR(mddev->unit);
5324 disk->first_minor = unit << shift;
5325 if (name)
5326 strcpy(disk->disk_name, name);
5327 else if (partitioned)
5328 sprintf(disk->disk_name, "md_d%d", unit);
5329 else
5330 sprintf(disk->disk_name, "md%d", unit);
5331 disk->fops = &md_fops;
5332 disk->private_data = mddev;
5333 disk->queue = mddev->queue;
5334 blk_queue_write_cache(mddev->queue, true, true);
5335 /* Allow extended partitions. This makes the
5336 * 'mdp' device redundant, but we can't really
5337 * remove it now.
5339 disk->flags |= GENHD_FL_EXT_DEVT;
5340 mddev->gendisk = disk;
5341 /* As soon as we call add_disk(), another thread could get
5342 * through to md_open, so make sure it doesn't get too far
5344 mutex_lock(&mddev->open_mutex);
5345 add_disk(disk);
5347 error = kobject_init_and_add(&mddev->kobj, &md_ktype,
5348 &disk_to_dev(disk)->kobj, "%s", "md");
5349 if (error) {
5350 /* This isn't possible, but as kobject_init_and_add is marked
5351 * __must_check, we must do something with the result
5353 pr_debug("md: cannot register %s/md - name in use\n",
5354 disk->disk_name);
5355 error = 0;
5357 if (mddev->kobj.sd &&
5358 sysfs_create_group(&mddev->kobj, &md_bitmap_group))
5359 pr_debug("pointless warning\n");
5360 mutex_unlock(&mddev->open_mutex);
5361 abort:
5362 mutex_unlock(&disks_mutex);
5363 if (!error && mddev->kobj.sd) {
5364 kobject_uevent(&mddev->kobj, KOBJ_ADD);
5365 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
5367 mddev_put(mddev);
5368 return error;
5371 static struct kobject *md_probe(dev_t dev, int *part, void *data)
5373 if (create_on_open)
5374 md_alloc(dev, NULL);
5375 return NULL;
5378 static int add_named_array(const char *val, const struct kernel_param *kp)
5381 * val must be "md_*" or "mdNNN".
5382 * For "md_*" we allocate an array with a large free minor number, and
5383 * set the name to val. val must not already be an active name.
5384 * For "mdNNN" we allocate an array with the minor number NNN
5385 * which must not already be in use.
5387 int len = strlen(val);
5388 char buf[DISK_NAME_LEN];
5389 unsigned long devnum;
5391 while (len && val[len-1] == '\n')
5392 len--;
5393 if (len >= DISK_NAME_LEN)
5394 return -E2BIG;
5395 strlcpy(buf, val, len+1);
5396 if (strncmp(buf, "md_", 3) == 0)
5397 return md_alloc(0, buf);
5398 if (strncmp(buf, "md", 2) == 0 &&
5399 isdigit(buf[2]) &&
5400 kstrtoul(buf+2, 10, &devnum) == 0 &&
5401 devnum <= MINORMASK)
5402 return md_alloc(MKDEV(MD_MAJOR, devnum), NULL);
5404 return -EINVAL;
5407 static void md_safemode_timeout(struct timer_list *t)
5409 struct mddev *mddev = from_timer(mddev, t, safemode_timer);
5411 mddev->safemode = 1;
5412 if (mddev->external)
5413 sysfs_notify_dirent_safe(mddev->sysfs_state);
5415 md_wakeup_thread(mddev->thread);
5418 static int start_dirty_degraded;
5420 int md_run(struct mddev *mddev)
5422 int err;
5423 struct md_rdev *rdev;
5424 struct md_personality *pers;
5426 if (list_empty(&mddev->disks))
5427 /* cannot run an array with no devices.. */
5428 return -EINVAL;
5430 if (mddev->pers)
5431 return -EBUSY;
5432 /* Cannot run until previous stop completes properly */
5433 if (mddev->sysfs_active)
5434 return -EBUSY;
5437 * Analyze all RAID superblock(s)
5439 if (!mddev->raid_disks) {
5440 if (!mddev->persistent)
5441 return -EINVAL;
5442 analyze_sbs(mddev);
5445 if (mddev->level != LEVEL_NONE)
5446 request_module("md-level-%d", mddev->level);
5447 else if (mddev->clevel[0])
5448 request_module("md-%s", mddev->clevel);
5451 * Drop all container device buffers, from now on
5452 * the only valid external interface is through the md
5453 * device.
5455 rdev_for_each(rdev, mddev) {
5456 if (test_bit(Faulty, &rdev->flags))
5457 continue;
5458 sync_blockdev(rdev->bdev);
5459 invalidate_bdev(rdev->bdev);
5460 if (mddev->ro != 1 &&
5461 (bdev_read_only(rdev->bdev) ||
5462 bdev_read_only(rdev->meta_bdev))) {
5463 mddev->ro = 1;
5464 if (mddev->gendisk)
5465 set_disk_ro(mddev->gendisk, 1);
5468 /* perform some consistency tests on the device.
5469 * We don't want the data to overlap the metadata,
5470 * Internal Bitmap issues have been handled elsewhere.
5472 if (rdev->meta_bdev) {
5473 /* Nothing to check */;
5474 } else if (rdev->data_offset < rdev->sb_start) {
5475 if (mddev->dev_sectors &&
5476 rdev->data_offset + mddev->dev_sectors
5477 > rdev->sb_start) {
5478 pr_warn("md: %s: data overlaps metadata\n",
5479 mdname(mddev));
5480 return -EINVAL;
5482 } else {
5483 if (rdev->sb_start + rdev->sb_size/512
5484 > rdev->data_offset) {
5485 pr_warn("md: %s: metadata overlaps data\n",
5486 mdname(mddev));
5487 return -EINVAL;
5490 sysfs_notify_dirent_safe(rdev->sysfs_state);
5493 if (mddev->bio_set == NULL) {
5494 mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5495 if (!mddev->bio_set)
5496 return -ENOMEM;
5498 if (mddev->sync_set == NULL) {
5499 mddev->sync_set = bioset_create(BIO_POOL_SIZE, 0, BIOSET_NEED_BVECS);
5500 if (!mddev->sync_set)
5501 return -ENOMEM;
5504 spin_lock(&pers_lock);
5505 pers = find_pers(mddev->level, mddev->clevel);
5506 if (!pers || !try_module_get(pers->owner)) {
5507 spin_unlock(&pers_lock);
5508 if (mddev->level != LEVEL_NONE)
5509 pr_warn("md: personality for level %d is not loaded!\n",
5510 mddev->level);
5511 else
5512 pr_warn("md: personality for level %s is not loaded!\n",
5513 mddev->clevel);
5514 return -EINVAL;
5516 spin_unlock(&pers_lock);
5517 if (mddev->level != pers->level) {
5518 mddev->level = pers->level;
5519 mddev->new_level = pers->level;
5521 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5523 if (mddev->reshape_position != MaxSector &&
5524 pers->start_reshape == NULL) {
5525 /* This personality cannot handle reshaping... */
5526 module_put(pers->owner);
5527 return -EINVAL;
5530 if (pers->sync_request) {
5531 /* Warn if this is a potentially silly
5532 * configuration.
5534 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5535 struct md_rdev *rdev2;
5536 int warned = 0;
5538 rdev_for_each(rdev, mddev)
5539 rdev_for_each(rdev2, mddev) {
5540 if (rdev < rdev2 &&
5541 rdev->bdev->bd_contains ==
5542 rdev2->bdev->bd_contains) {
5543 pr_warn("%s: WARNING: %s appears to be on the same physical disk as %s.\n",
5544 mdname(mddev),
5545 bdevname(rdev->bdev,b),
5546 bdevname(rdev2->bdev,b2));
5547 warned = 1;
5551 if (warned)
5552 pr_warn("True protection against single-disk failure might be compromised.\n");
5555 mddev->recovery = 0;
5556 /* may be over-ridden by personality */
5557 mddev->resync_max_sectors = mddev->dev_sectors;
5559 mddev->ok_start_degraded = start_dirty_degraded;
5561 if (start_readonly && mddev->ro == 0)
5562 mddev->ro = 2; /* read-only, but switch on first write */
5564 err = pers->run(mddev);
5565 if (err)
5566 pr_warn("md: pers->run() failed ...\n");
5567 else if (pers->size(mddev, 0, 0) < mddev->array_sectors) {
5568 WARN_ONCE(!mddev->external_size,
5569 "%s: default size too small, but 'external_size' not in effect?\n",
5570 __func__);
5571 pr_warn("md: invalid array_size %llu > default size %llu\n",
5572 (unsigned long long)mddev->array_sectors / 2,
5573 (unsigned long long)pers->size(mddev, 0, 0) / 2);
5574 err = -EINVAL;
5576 if (err == 0 && pers->sync_request &&
5577 (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5578 struct bitmap *bitmap;
5580 bitmap = bitmap_create(mddev, -1);
5581 if (IS_ERR(bitmap)) {
5582 err = PTR_ERR(bitmap);
5583 pr_warn("%s: failed to create bitmap (%d)\n",
5584 mdname(mddev), err);
5585 } else
5586 mddev->bitmap = bitmap;
5589 if (err) {
5590 mddev_detach(mddev);
5591 if (mddev->private)
5592 pers->free(mddev, mddev->private);
5593 mddev->private = NULL;
5594 module_put(pers->owner);
5595 bitmap_destroy(mddev);
5596 return err;
5598 if (mddev->queue) {
5599 bool nonrot = true;
5601 rdev_for_each(rdev, mddev) {
5602 if (rdev->raid_disk >= 0 &&
5603 !blk_queue_nonrot(bdev_get_queue(rdev->bdev))) {
5604 nonrot = false;
5605 break;
5608 if (mddev->degraded)
5609 nonrot = false;
5610 if (nonrot)
5611 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, mddev->queue);
5612 else
5613 queue_flag_clear_unlocked(QUEUE_FLAG_NONROT, mddev->queue);
5614 mddev->queue->backing_dev_info->congested_data = mddev;
5615 mddev->queue->backing_dev_info->congested_fn = md_congested;
5617 if (pers->sync_request) {
5618 if (mddev->kobj.sd &&
5619 sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5620 pr_warn("md: cannot register extra attributes for %s\n",
5621 mdname(mddev));
5622 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5623 } else if (mddev->ro == 2) /* auto-readonly not meaningful */
5624 mddev->ro = 0;
5626 atomic_set(&mddev->max_corr_read_errors,
5627 MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5628 mddev->safemode = 0;
5629 if (mddev_is_clustered(mddev))
5630 mddev->safemode_delay = 0;
5631 else
5632 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5633 mddev->in_sync = 1;
5634 smp_wmb();
5635 spin_lock(&mddev->lock);
5636 mddev->pers = pers;
5637 spin_unlock(&mddev->lock);
5638 rdev_for_each(rdev, mddev)
5639 if (rdev->raid_disk >= 0)
5640 if (sysfs_link_rdev(mddev, rdev))
5641 /* failure here is OK */;
5643 if (mddev->degraded && !mddev->ro)
5644 /* This ensures that recovering status is reported immediately
5645 * via sysfs - until a lack of spares is confirmed.
5647 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5648 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5650 if (mddev->sb_flags)
5651 md_update_sb(mddev, 0);
5653 md_new_event(mddev);
5654 sysfs_notify_dirent_safe(mddev->sysfs_state);
5655 sysfs_notify_dirent_safe(mddev->sysfs_action);
5656 sysfs_notify(&mddev->kobj, NULL, "degraded");
5657 return 0;
5659 EXPORT_SYMBOL_GPL(md_run);
5661 static int do_md_run(struct mddev *mddev)
5663 int err;
5665 err = md_run(mddev);
5666 if (err)
5667 goto out;
5668 err = bitmap_load(mddev);
5669 if (err) {
5670 bitmap_destroy(mddev);
5671 goto out;
5674 if (mddev_is_clustered(mddev))
5675 md_allow_write(mddev);
5677 /* run start up tasks that require md_thread */
5678 md_start(mddev);
5680 md_wakeup_thread(mddev->thread);
5681 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5683 set_capacity(mddev->gendisk, mddev->array_sectors);
5684 revalidate_disk(mddev->gendisk);
5685 mddev->changed = 1;
5686 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5687 out:
5688 return err;
5691 int md_start(struct mddev *mddev)
5693 int ret = 0;
5695 if (mddev->pers->start) {
5696 set_bit(MD_RECOVERY_WAIT, &mddev->recovery);
5697 md_wakeup_thread(mddev->thread);
5698 ret = mddev->pers->start(mddev);
5699 clear_bit(MD_RECOVERY_WAIT, &mddev->recovery);
5700 md_wakeup_thread(mddev->sync_thread);
5702 return ret;
5704 EXPORT_SYMBOL_GPL(md_start);
5706 static int restart_array(struct mddev *mddev)
5708 struct gendisk *disk = mddev->gendisk;
5709 struct md_rdev *rdev;
5710 bool has_journal = false;
5711 bool has_readonly = false;
5713 /* Complain if it has no devices */
5714 if (list_empty(&mddev->disks))
5715 return -ENXIO;
5716 if (!mddev->pers)
5717 return -EINVAL;
5718 if (!mddev->ro)
5719 return -EBUSY;
5721 rcu_read_lock();
5722 rdev_for_each_rcu(rdev, mddev) {
5723 if (test_bit(Journal, &rdev->flags) &&
5724 !test_bit(Faulty, &rdev->flags))
5725 has_journal = true;
5726 if (bdev_read_only(rdev->bdev))
5727 has_readonly = true;
5729 rcu_read_unlock();
5730 if (test_bit(MD_HAS_JOURNAL, &mddev->flags) && !has_journal)
5731 /* Don't restart rw with journal missing/faulty */
5732 return -EINVAL;
5733 if (has_readonly)
5734 return -EROFS;
5736 mddev->safemode = 0;
5737 mddev->ro = 0;
5738 set_disk_ro(disk, 0);
5739 pr_debug("md: %s switched to read-write mode.\n", mdname(mddev));
5740 /* Kick recovery or resync if necessary */
5741 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5742 md_wakeup_thread(mddev->thread);
5743 md_wakeup_thread(mddev->sync_thread);
5744 sysfs_notify_dirent_safe(mddev->sysfs_state);
5745 return 0;
5748 static void md_clean(struct mddev *mddev)
5750 mddev->array_sectors = 0;
5751 mddev->external_size = 0;
5752 mddev->dev_sectors = 0;
5753 mddev->raid_disks = 0;
5754 mddev->recovery_cp = 0;
5755 mddev->resync_min = 0;
5756 mddev->resync_max = MaxSector;
5757 mddev->reshape_position = MaxSector;
5758 mddev->external = 0;
5759 mddev->persistent = 0;
5760 mddev->level = LEVEL_NONE;
5761 mddev->clevel[0] = 0;
5762 mddev->flags = 0;
5763 mddev->sb_flags = 0;
5764 mddev->ro = 0;
5765 mddev->metadata_type[0] = 0;
5766 mddev->chunk_sectors = 0;
5767 mddev->ctime = mddev->utime = 0;
5768 mddev->layout = 0;
5769 mddev->max_disks = 0;
5770 mddev->events = 0;
5771 mddev->can_decrease_events = 0;
5772 mddev->delta_disks = 0;
5773 mddev->reshape_backwards = 0;
5774 mddev->new_level = LEVEL_NONE;
5775 mddev->new_layout = 0;
5776 mddev->new_chunk_sectors = 0;
5777 mddev->curr_resync = 0;
5778 atomic64_set(&mddev->resync_mismatches, 0);
5779 mddev->suspend_lo = mddev->suspend_hi = 0;
5780 mddev->sync_speed_min = mddev->sync_speed_max = 0;
5781 mddev->recovery = 0;
5782 mddev->in_sync = 0;
5783 mddev->changed = 0;
5784 mddev->degraded = 0;
5785 mddev->safemode = 0;
5786 mddev->private = NULL;
5787 mddev->cluster_info = NULL;
5788 mddev->bitmap_info.offset = 0;
5789 mddev->bitmap_info.default_offset = 0;
5790 mddev->bitmap_info.default_space = 0;
5791 mddev->bitmap_info.chunksize = 0;
5792 mddev->bitmap_info.daemon_sleep = 0;
5793 mddev->bitmap_info.max_write_behind = 0;
5794 mddev->bitmap_info.nodes = 0;
5797 static void __md_stop_writes(struct mddev *mddev)
5799 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5800 flush_workqueue(md_misc_wq);
5801 if (mddev->sync_thread) {
5802 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5803 md_reap_sync_thread(mddev);
5806 del_timer_sync(&mddev->safemode_timer);
5808 if (mddev->pers && mddev->pers->quiesce) {
5809 mddev->pers->quiesce(mddev, 1);
5810 mddev->pers->quiesce(mddev, 0);
5812 bitmap_flush(mddev);
5814 if (mddev->ro == 0 &&
5815 ((!mddev->in_sync && !mddev_is_clustered(mddev)) ||
5816 mddev->sb_flags)) {
5817 /* mark array as shutdown cleanly */
5818 if (!mddev_is_clustered(mddev))
5819 mddev->in_sync = 1;
5820 md_update_sb(mddev, 1);
5824 void md_stop_writes(struct mddev *mddev)
5826 mddev_lock_nointr(mddev);
5827 __md_stop_writes(mddev);
5828 mddev_unlock(mddev);
5830 EXPORT_SYMBOL_GPL(md_stop_writes);
5832 static void mddev_detach(struct mddev *mddev)
5834 bitmap_wait_behind_writes(mddev);
5835 if (mddev->pers && mddev->pers->quiesce) {
5836 mddev->pers->quiesce(mddev, 1);
5837 mddev->pers->quiesce(mddev, 0);
5839 md_unregister_thread(&mddev->thread);
5840 if (mddev->queue)
5841 blk_sync_queue(mddev->queue); /* the unplug fn references 'conf'*/
5844 static void __md_stop(struct mddev *mddev)
5846 struct md_personality *pers = mddev->pers;
5847 bitmap_destroy(mddev);
5848 mddev_detach(mddev);
5849 /* Ensure ->event_work is done */
5850 flush_workqueue(md_misc_wq);
5851 spin_lock(&mddev->lock);
5852 mddev->pers = NULL;
5853 spin_unlock(&mddev->lock);
5854 pers->free(mddev, mddev->private);
5855 mddev->private = NULL;
5856 if (pers->sync_request && mddev->to_remove == NULL)
5857 mddev->to_remove = &md_redundancy_group;
5858 module_put(pers->owner);
5859 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5862 void md_stop(struct mddev *mddev)
5864 /* stop the array and free an attached data structures.
5865 * This is called from dm-raid
5867 __md_stop(mddev);
5868 if (mddev->bio_set) {
5869 bioset_free(mddev->bio_set);
5870 mddev->bio_set = NULL;
5872 if (mddev->sync_set) {
5873 bioset_free(mddev->sync_set);
5874 mddev->sync_set = NULL;
5878 EXPORT_SYMBOL_GPL(md_stop);
5880 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5882 int err = 0;
5883 int did_freeze = 0;
5885 if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5886 did_freeze = 1;
5887 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5888 md_wakeup_thread(mddev->thread);
5890 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5891 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5892 if (mddev->sync_thread)
5893 /* Thread might be blocked waiting for metadata update
5894 * which will now never happen */
5895 wake_up_process(mddev->sync_thread->tsk);
5897 if (mddev->external && test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags))
5898 return -EBUSY;
5899 mddev_unlock(mddev);
5900 wait_event(resync_wait, !test_bit(MD_RECOVERY_RUNNING,
5901 &mddev->recovery));
5902 wait_event(mddev->sb_wait,
5903 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
5904 mddev_lock_nointr(mddev);
5906 mutex_lock(&mddev->open_mutex);
5907 if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5908 mddev->sync_thread ||
5909 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
5910 pr_warn("md: %s still in use.\n",mdname(mddev));
5911 if (did_freeze) {
5912 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5913 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5914 md_wakeup_thread(mddev->thread);
5916 err = -EBUSY;
5917 goto out;
5919 if (mddev->pers) {
5920 __md_stop_writes(mddev);
5922 err = -ENXIO;
5923 if (mddev->ro==1)
5924 goto out;
5925 mddev->ro = 1;
5926 set_disk_ro(mddev->gendisk, 1);
5927 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5928 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5929 md_wakeup_thread(mddev->thread);
5930 sysfs_notify_dirent_safe(mddev->sysfs_state);
5931 err = 0;
5933 out:
5934 mutex_unlock(&mddev->open_mutex);
5935 return err;
5938 /* mode:
5939 * 0 - completely stop and dis-assemble array
5940 * 2 - stop but do not disassemble array
5942 static int do_md_stop(struct mddev *mddev, int mode,
5943 struct block_device *bdev)
5945 struct gendisk *disk = mddev->gendisk;
5946 struct md_rdev *rdev;
5947 int did_freeze = 0;
5949 if (!test_bit(MD_RECOVERY_FROZEN, &mddev->recovery)) {
5950 did_freeze = 1;
5951 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5952 md_wakeup_thread(mddev->thread);
5954 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
5955 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5956 if (mddev->sync_thread)
5957 /* Thread might be blocked waiting for metadata update
5958 * which will now never happen */
5959 wake_up_process(mddev->sync_thread->tsk);
5961 mddev_unlock(mddev);
5962 wait_event(resync_wait, (mddev->sync_thread == NULL &&
5963 !test_bit(MD_RECOVERY_RUNNING,
5964 &mddev->recovery)));
5965 mddev_lock_nointr(mddev);
5967 mutex_lock(&mddev->open_mutex);
5968 if ((mddev->pers && atomic_read(&mddev->openers) > !!bdev) ||
5969 mddev->sysfs_active ||
5970 mddev->sync_thread ||
5971 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery)) {
5972 pr_warn("md: %s still in use.\n",mdname(mddev));
5973 mutex_unlock(&mddev->open_mutex);
5974 if (did_freeze) {
5975 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5976 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5977 md_wakeup_thread(mddev->thread);
5979 return -EBUSY;
5981 if (mddev->pers) {
5982 if (mddev->ro)
5983 set_disk_ro(disk, 0);
5985 __md_stop_writes(mddev);
5986 __md_stop(mddev);
5987 mddev->queue->backing_dev_info->congested_fn = NULL;
5989 /* tell userspace to handle 'inactive' */
5990 sysfs_notify_dirent_safe(mddev->sysfs_state);
5992 rdev_for_each(rdev, mddev)
5993 if (rdev->raid_disk >= 0)
5994 sysfs_unlink_rdev(mddev, rdev);
5996 set_capacity(disk, 0);
5997 mutex_unlock(&mddev->open_mutex);
5998 mddev->changed = 1;
5999 revalidate_disk(disk);
6001 if (mddev->ro)
6002 mddev->ro = 0;
6003 } else
6004 mutex_unlock(&mddev->open_mutex);
6006 * Free resources if final stop
6008 if (mode == 0) {
6009 pr_info("md: %s stopped.\n", mdname(mddev));
6011 if (mddev->bitmap_info.file) {
6012 struct file *f = mddev->bitmap_info.file;
6013 spin_lock(&mddev->lock);
6014 mddev->bitmap_info.file = NULL;
6015 spin_unlock(&mddev->lock);
6016 fput(f);
6018 mddev->bitmap_info.offset = 0;
6020 export_array(mddev);
6022 md_clean(mddev);
6023 if (mddev->hold_active == UNTIL_STOP)
6024 mddev->hold_active = 0;
6026 md_new_event(mddev);
6027 sysfs_notify_dirent_safe(mddev->sysfs_state);
6028 return 0;
6031 #ifndef MODULE
6032 static void autorun_array(struct mddev *mddev)
6034 struct md_rdev *rdev;
6035 int err;
6037 if (list_empty(&mddev->disks))
6038 return;
6040 pr_info("md: running: ");
6042 rdev_for_each(rdev, mddev) {
6043 char b[BDEVNAME_SIZE];
6044 pr_cont("<%s>", bdevname(rdev->bdev,b));
6046 pr_cont("\n");
6048 err = do_md_run(mddev);
6049 if (err) {
6050 pr_warn("md: do_md_run() returned %d\n", err);
6051 do_md_stop(mddev, 0, NULL);
6056 * lets try to run arrays based on all disks that have arrived
6057 * until now. (those are in pending_raid_disks)
6059 * the method: pick the first pending disk, collect all disks with
6060 * the same UUID, remove all from the pending list and put them into
6061 * the 'same_array' list. Then order this list based on superblock
6062 * update time (freshest comes first), kick out 'old' disks and
6063 * compare superblocks. If everything's fine then run it.
6065 * If "unit" is allocated, then bump its reference count
6067 static void autorun_devices(int part)
6069 struct md_rdev *rdev0, *rdev, *tmp;
6070 struct mddev *mddev;
6071 char b[BDEVNAME_SIZE];
6073 pr_info("md: autorun ...\n");
6074 while (!list_empty(&pending_raid_disks)) {
6075 int unit;
6076 dev_t dev;
6077 LIST_HEAD(candidates);
6078 rdev0 = list_entry(pending_raid_disks.next,
6079 struct md_rdev, same_set);
6081 pr_debug("md: considering %s ...\n", bdevname(rdev0->bdev,b));
6082 INIT_LIST_HEAD(&candidates);
6083 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
6084 if (super_90_load(rdev, rdev0, 0) >= 0) {
6085 pr_debug("md: adding %s ...\n",
6086 bdevname(rdev->bdev,b));
6087 list_move(&rdev->same_set, &candidates);
6090 * now we have a set of devices, with all of them having
6091 * mostly sane superblocks. It's time to allocate the
6092 * mddev.
6094 if (part) {
6095 dev = MKDEV(mdp_major,
6096 rdev0->preferred_minor << MdpMinorShift);
6097 unit = MINOR(dev) >> MdpMinorShift;
6098 } else {
6099 dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
6100 unit = MINOR(dev);
6102 if (rdev0->preferred_minor != unit) {
6103 pr_warn("md: unit number in %s is bad: %d\n",
6104 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
6105 break;
6108 md_probe(dev, NULL, NULL);
6109 mddev = mddev_find(dev);
6110 if (!mddev || !mddev->gendisk) {
6111 if (mddev)
6112 mddev_put(mddev);
6113 break;
6115 if (mddev_lock(mddev))
6116 pr_warn("md: %s locked, cannot run\n", mdname(mddev));
6117 else if (mddev->raid_disks || mddev->major_version
6118 || !list_empty(&mddev->disks)) {
6119 pr_warn("md: %s already running, cannot run %s\n",
6120 mdname(mddev), bdevname(rdev0->bdev,b));
6121 mddev_unlock(mddev);
6122 } else {
6123 pr_debug("md: created %s\n", mdname(mddev));
6124 mddev->persistent = 1;
6125 rdev_for_each_list(rdev, tmp, &candidates) {
6126 list_del_init(&rdev->same_set);
6127 if (bind_rdev_to_array(rdev, mddev))
6128 export_rdev(rdev);
6130 autorun_array(mddev);
6131 mddev_unlock(mddev);
6133 /* on success, candidates will be empty, on error
6134 * it won't...
6136 rdev_for_each_list(rdev, tmp, &candidates) {
6137 list_del_init(&rdev->same_set);
6138 export_rdev(rdev);
6140 mddev_put(mddev);
6142 pr_info("md: ... autorun DONE.\n");
6144 #endif /* !MODULE */
6146 static int get_version(void __user *arg)
6148 mdu_version_t ver;
6150 ver.major = MD_MAJOR_VERSION;
6151 ver.minor = MD_MINOR_VERSION;
6152 ver.patchlevel = MD_PATCHLEVEL_VERSION;
6154 if (copy_to_user(arg, &ver, sizeof(ver)))
6155 return -EFAULT;
6157 return 0;
6160 static int get_array_info(struct mddev *mddev, void __user *arg)
6162 mdu_array_info_t info;
6163 int nr,working,insync,failed,spare;
6164 struct md_rdev *rdev;
6166 nr = working = insync = failed = spare = 0;
6167 rcu_read_lock();
6168 rdev_for_each_rcu(rdev, mddev) {
6169 nr++;
6170 if (test_bit(Faulty, &rdev->flags))
6171 failed++;
6172 else {
6173 working++;
6174 if (test_bit(In_sync, &rdev->flags))
6175 insync++;
6176 else if (test_bit(Journal, &rdev->flags))
6177 /* TODO: add journal count to md_u.h */
6179 else
6180 spare++;
6183 rcu_read_unlock();
6185 info.major_version = mddev->major_version;
6186 info.minor_version = mddev->minor_version;
6187 info.patch_version = MD_PATCHLEVEL_VERSION;
6188 info.ctime = clamp_t(time64_t, mddev->ctime, 0, U32_MAX);
6189 info.level = mddev->level;
6190 info.size = mddev->dev_sectors / 2;
6191 if (info.size != mddev->dev_sectors / 2) /* overflow */
6192 info.size = -1;
6193 info.nr_disks = nr;
6194 info.raid_disks = mddev->raid_disks;
6195 info.md_minor = mddev->md_minor;
6196 info.not_persistent= !mddev->persistent;
6198 info.utime = clamp_t(time64_t, mddev->utime, 0, U32_MAX);
6199 info.state = 0;
6200 if (mddev->in_sync)
6201 info.state = (1<<MD_SB_CLEAN);
6202 if (mddev->bitmap && mddev->bitmap_info.offset)
6203 info.state |= (1<<MD_SB_BITMAP_PRESENT);
6204 if (mddev_is_clustered(mddev))
6205 info.state |= (1<<MD_SB_CLUSTERED);
6206 info.active_disks = insync;
6207 info.working_disks = working;
6208 info.failed_disks = failed;
6209 info.spare_disks = spare;
6211 info.layout = mddev->layout;
6212 info.chunk_size = mddev->chunk_sectors << 9;
6214 if (copy_to_user(arg, &info, sizeof(info)))
6215 return -EFAULT;
6217 return 0;
6220 static int get_bitmap_file(struct mddev *mddev, void __user * arg)
6222 mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
6223 char *ptr;
6224 int err;
6226 file = kzalloc(sizeof(*file), GFP_NOIO);
6227 if (!file)
6228 return -ENOMEM;
6230 err = 0;
6231 spin_lock(&mddev->lock);
6232 /* bitmap enabled */
6233 if (mddev->bitmap_info.file) {
6234 ptr = file_path(mddev->bitmap_info.file, file->pathname,
6235 sizeof(file->pathname));
6236 if (IS_ERR(ptr))
6237 err = PTR_ERR(ptr);
6238 else
6239 memmove(file->pathname, ptr,
6240 sizeof(file->pathname)-(ptr-file->pathname));
6242 spin_unlock(&mddev->lock);
6244 if (err == 0 &&
6245 copy_to_user(arg, file, sizeof(*file)))
6246 err = -EFAULT;
6248 kfree(file);
6249 return err;
6252 static int get_disk_info(struct mddev *mddev, void __user * arg)
6254 mdu_disk_info_t info;
6255 struct md_rdev *rdev;
6257 if (copy_from_user(&info, arg, sizeof(info)))
6258 return -EFAULT;
6260 rcu_read_lock();
6261 rdev = md_find_rdev_nr_rcu(mddev, info.number);
6262 if (rdev) {
6263 info.major = MAJOR(rdev->bdev->bd_dev);
6264 info.minor = MINOR(rdev->bdev->bd_dev);
6265 info.raid_disk = rdev->raid_disk;
6266 info.state = 0;
6267 if (test_bit(Faulty, &rdev->flags))
6268 info.state |= (1<<MD_DISK_FAULTY);
6269 else if (test_bit(In_sync, &rdev->flags)) {
6270 info.state |= (1<<MD_DISK_ACTIVE);
6271 info.state |= (1<<MD_DISK_SYNC);
6273 if (test_bit(Journal, &rdev->flags))
6274 info.state |= (1<<MD_DISK_JOURNAL);
6275 if (test_bit(WriteMostly, &rdev->flags))
6276 info.state |= (1<<MD_DISK_WRITEMOSTLY);
6277 if (test_bit(FailFast, &rdev->flags))
6278 info.state |= (1<<MD_DISK_FAILFAST);
6279 } else {
6280 info.major = info.minor = 0;
6281 info.raid_disk = -1;
6282 info.state = (1<<MD_DISK_REMOVED);
6284 rcu_read_unlock();
6286 if (copy_to_user(arg, &info, sizeof(info)))
6287 return -EFAULT;
6289 return 0;
6292 static int add_new_disk(struct mddev *mddev, mdu_disk_info_t *info)
6294 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
6295 struct md_rdev *rdev;
6296 dev_t dev = MKDEV(info->major,info->minor);
6298 if (mddev_is_clustered(mddev) &&
6299 !(info->state & ((1 << MD_DISK_CLUSTER_ADD) | (1 << MD_DISK_CANDIDATE)))) {
6300 pr_warn("%s: Cannot add to clustered mddev.\n",
6301 mdname(mddev));
6302 return -EINVAL;
6305 if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
6306 return -EOVERFLOW;
6308 if (!mddev->raid_disks) {
6309 int err;
6310 /* expecting a device which has a superblock */
6311 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
6312 if (IS_ERR(rdev)) {
6313 pr_warn("md: md_import_device returned %ld\n",
6314 PTR_ERR(rdev));
6315 return PTR_ERR(rdev);
6317 if (!list_empty(&mddev->disks)) {
6318 struct md_rdev *rdev0
6319 = list_entry(mddev->disks.next,
6320 struct md_rdev, same_set);
6321 err = super_types[mddev->major_version]
6322 .load_super(rdev, rdev0, mddev->minor_version);
6323 if (err < 0) {
6324 pr_warn("md: %s has different UUID to %s\n",
6325 bdevname(rdev->bdev,b),
6326 bdevname(rdev0->bdev,b2));
6327 export_rdev(rdev);
6328 return -EINVAL;
6331 err = bind_rdev_to_array(rdev, mddev);
6332 if (err)
6333 export_rdev(rdev);
6334 return err;
6338 * add_new_disk can be used once the array is assembled
6339 * to add "hot spares". They must already have a superblock
6340 * written
6342 if (mddev->pers) {
6343 int err;
6344 if (!mddev->pers->hot_add_disk) {
6345 pr_warn("%s: personality does not support diskops!\n",
6346 mdname(mddev));
6347 return -EINVAL;
6349 if (mddev->persistent)
6350 rdev = md_import_device(dev, mddev->major_version,
6351 mddev->minor_version);
6352 else
6353 rdev = md_import_device(dev, -1, -1);
6354 if (IS_ERR(rdev)) {
6355 pr_warn("md: md_import_device returned %ld\n",
6356 PTR_ERR(rdev));
6357 return PTR_ERR(rdev);
6359 /* set saved_raid_disk if appropriate */
6360 if (!mddev->persistent) {
6361 if (info->state & (1<<MD_DISK_SYNC) &&
6362 info->raid_disk < mddev->raid_disks) {
6363 rdev->raid_disk = info->raid_disk;
6364 set_bit(In_sync, &rdev->flags);
6365 clear_bit(Bitmap_sync, &rdev->flags);
6366 } else
6367 rdev->raid_disk = -1;
6368 rdev->saved_raid_disk = rdev->raid_disk;
6369 } else
6370 super_types[mddev->major_version].
6371 validate_super(mddev, rdev);
6372 if ((info->state & (1<<MD_DISK_SYNC)) &&
6373 rdev->raid_disk != info->raid_disk) {
6374 /* This was a hot-add request, but events doesn't
6375 * match, so reject it.
6377 export_rdev(rdev);
6378 return -EINVAL;
6381 clear_bit(In_sync, &rdev->flags); /* just to be sure */
6382 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6383 set_bit(WriteMostly, &rdev->flags);
6384 else
6385 clear_bit(WriteMostly, &rdev->flags);
6386 if (info->state & (1<<MD_DISK_FAILFAST))
6387 set_bit(FailFast, &rdev->flags);
6388 else
6389 clear_bit(FailFast, &rdev->flags);
6391 if (info->state & (1<<MD_DISK_JOURNAL)) {
6392 struct md_rdev *rdev2;
6393 bool has_journal = false;
6395 /* make sure no existing journal disk */
6396 rdev_for_each(rdev2, mddev) {
6397 if (test_bit(Journal, &rdev2->flags)) {
6398 has_journal = true;
6399 break;
6402 if (has_journal || mddev->bitmap) {
6403 export_rdev(rdev);
6404 return -EBUSY;
6406 set_bit(Journal, &rdev->flags);
6409 * check whether the device shows up in other nodes
6411 if (mddev_is_clustered(mddev)) {
6412 if (info->state & (1 << MD_DISK_CANDIDATE))
6413 set_bit(Candidate, &rdev->flags);
6414 else if (info->state & (1 << MD_DISK_CLUSTER_ADD)) {
6415 /* --add initiated by this node */
6416 err = md_cluster_ops->add_new_disk(mddev, rdev);
6417 if (err) {
6418 export_rdev(rdev);
6419 return err;
6424 rdev->raid_disk = -1;
6425 err = bind_rdev_to_array(rdev, mddev);
6427 if (err)
6428 export_rdev(rdev);
6430 if (mddev_is_clustered(mddev)) {
6431 if (info->state & (1 << MD_DISK_CANDIDATE)) {
6432 if (!err) {
6433 err = md_cluster_ops->new_disk_ack(mddev,
6434 err == 0);
6435 if (err)
6436 md_kick_rdev_from_array(rdev);
6438 } else {
6439 if (err)
6440 md_cluster_ops->add_new_disk_cancel(mddev);
6441 else
6442 err = add_bound_rdev(rdev);
6445 } else if (!err)
6446 err = add_bound_rdev(rdev);
6448 return err;
6451 /* otherwise, add_new_disk is only allowed
6452 * for major_version==0 superblocks
6454 if (mddev->major_version != 0) {
6455 pr_warn("%s: ADD_NEW_DISK not supported\n", mdname(mddev));
6456 return -EINVAL;
6459 if (!(info->state & (1<<MD_DISK_FAULTY))) {
6460 int err;
6461 rdev = md_import_device(dev, -1, 0);
6462 if (IS_ERR(rdev)) {
6463 pr_warn("md: error, md_import_device() returned %ld\n",
6464 PTR_ERR(rdev));
6465 return PTR_ERR(rdev);
6467 rdev->desc_nr = info->number;
6468 if (info->raid_disk < mddev->raid_disks)
6469 rdev->raid_disk = info->raid_disk;
6470 else
6471 rdev->raid_disk = -1;
6473 if (rdev->raid_disk < mddev->raid_disks)
6474 if (info->state & (1<<MD_DISK_SYNC))
6475 set_bit(In_sync, &rdev->flags);
6477 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
6478 set_bit(WriteMostly, &rdev->flags);
6479 if (info->state & (1<<MD_DISK_FAILFAST))
6480 set_bit(FailFast, &rdev->flags);
6482 if (!mddev->persistent) {
6483 pr_debug("md: nonpersistent superblock ...\n");
6484 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6485 } else
6486 rdev->sb_start = calc_dev_sboffset(rdev);
6487 rdev->sectors = rdev->sb_start;
6489 err = bind_rdev_to_array(rdev, mddev);
6490 if (err) {
6491 export_rdev(rdev);
6492 return err;
6496 return 0;
6499 static int hot_remove_disk(struct mddev *mddev, dev_t dev)
6501 char b[BDEVNAME_SIZE];
6502 struct md_rdev *rdev;
6504 rdev = find_rdev(mddev, dev);
6505 if (!rdev)
6506 return -ENXIO;
6508 if (rdev->raid_disk < 0)
6509 goto kick_rdev;
6511 clear_bit(Blocked, &rdev->flags);
6512 remove_and_add_spares(mddev, rdev);
6514 if (rdev->raid_disk >= 0)
6515 goto busy;
6517 kick_rdev:
6518 if (mddev_is_clustered(mddev))
6519 md_cluster_ops->remove_disk(mddev, rdev);
6521 md_kick_rdev_from_array(rdev);
6522 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6523 if (mddev->thread)
6524 md_wakeup_thread(mddev->thread);
6525 else
6526 md_update_sb(mddev, 1);
6527 md_new_event(mddev);
6529 return 0;
6530 busy:
6531 pr_debug("md: cannot remove active disk %s from %s ...\n",
6532 bdevname(rdev->bdev,b), mdname(mddev));
6533 return -EBUSY;
6536 static int hot_add_disk(struct mddev *mddev, dev_t dev)
6538 char b[BDEVNAME_SIZE];
6539 int err;
6540 struct md_rdev *rdev;
6542 if (!mddev->pers)
6543 return -ENODEV;
6545 if (mddev->major_version != 0) {
6546 pr_warn("%s: HOT_ADD may only be used with version-0 superblocks.\n",
6547 mdname(mddev));
6548 return -EINVAL;
6550 if (!mddev->pers->hot_add_disk) {
6551 pr_warn("%s: personality does not support diskops!\n",
6552 mdname(mddev));
6553 return -EINVAL;
6556 rdev = md_import_device(dev, -1, 0);
6557 if (IS_ERR(rdev)) {
6558 pr_warn("md: error, md_import_device() returned %ld\n",
6559 PTR_ERR(rdev));
6560 return -EINVAL;
6563 if (mddev->persistent)
6564 rdev->sb_start = calc_dev_sboffset(rdev);
6565 else
6566 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
6568 rdev->sectors = rdev->sb_start;
6570 if (test_bit(Faulty, &rdev->flags)) {
6571 pr_warn("md: can not hot-add faulty %s disk to %s!\n",
6572 bdevname(rdev->bdev,b), mdname(mddev));
6573 err = -EINVAL;
6574 goto abort_export;
6577 clear_bit(In_sync, &rdev->flags);
6578 rdev->desc_nr = -1;
6579 rdev->saved_raid_disk = -1;
6580 err = bind_rdev_to_array(rdev, mddev);
6581 if (err)
6582 goto abort_export;
6585 * The rest should better be atomic, we can have disk failures
6586 * noticed in interrupt contexts ...
6589 rdev->raid_disk = -1;
6591 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6592 if (!mddev->thread)
6593 md_update_sb(mddev, 1);
6595 * Kick recovery, maybe this spare has to be added to the
6596 * array immediately.
6598 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6599 md_wakeup_thread(mddev->thread);
6600 md_new_event(mddev);
6601 return 0;
6603 abort_export:
6604 export_rdev(rdev);
6605 return err;
6608 static int set_bitmap_file(struct mddev *mddev, int fd)
6610 int err = 0;
6612 if (mddev->pers) {
6613 if (!mddev->pers->quiesce || !mddev->thread)
6614 return -EBUSY;
6615 if (mddev->recovery || mddev->sync_thread)
6616 return -EBUSY;
6617 /* we should be able to change the bitmap.. */
6620 if (fd >= 0) {
6621 struct inode *inode;
6622 struct file *f;
6624 if (mddev->bitmap || mddev->bitmap_info.file)
6625 return -EEXIST; /* cannot add when bitmap is present */
6626 f = fget(fd);
6628 if (f == NULL) {
6629 pr_warn("%s: error: failed to get bitmap file\n",
6630 mdname(mddev));
6631 return -EBADF;
6634 inode = f->f_mapping->host;
6635 if (!S_ISREG(inode->i_mode)) {
6636 pr_warn("%s: error: bitmap file must be a regular file\n",
6637 mdname(mddev));
6638 err = -EBADF;
6639 } else if (!(f->f_mode & FMODE_WRITE)) {
6640 pr_warn("%s: error: bitmap file must open for write\n",
6641 mdname(mddev));
6642 err = -EBADF;
6643 } else if (atomic_read(&inode->i_writecount) != 1) {
6644 pr_warn("%s: error: bitmap file is already in use\n",
6645 mdname(mddev));
6646 err = -EBUSY;
6648 if (err) {
6649 fput(f);
6650 return err;
6652 mddev->bitmap_info.file = f;
6653 mddev->bitmap_info.offset = 0; /* file overrides offset */
6654 } else if (mddev->bitmap == NULL)
6655 return -ENOENT; /* cannot remove what isn't there */
6656 err = 0;
6657 if (mddev->pers) {
6658 if (fd >= 0) {
6659 struct bitmap *bitmap;
6661 bitmap = bitmap_create(mddev, -1);
6662 mddev_suspend(mddev);
6663 if (!IS_ERR(bitmap)) {
6664 mddev->bitmap = bitmap;
6665 err = bitmap_load(mddev);
6666 } else
6667 err = PTR_ERR(bitmap);
6668 if (err) {
6669 bitmap_destroy(mddev);
6670 fd = -1;
6672 mddev_resume(mddev);
6673 } else if (fd < 0) {
6674 mddev_suspend(mddev);
6675 bitmap_destroy(mddev);
6676 mddev_resume(mddev);
6679 if (fd < 0) {
6680 struct file *f = mddev->bitmap_info.file;
6681 if (f) {
6682 spin_lock(&mddev->lock);
6683 mddev->bitmap_info.file = NULL;
6684 spin_unlock(&mddev->lock);
6685 fput(f);
6689 return err;
6693 * set_array_info is used two different ways
6694 * The original usage is when creating a new array.
6695 * In this usage, raid_disks is > 0 and it together with
6696 * level, size, not_persistent,layout,chunksize determine the
6697 * shape of the array.
6698 * This will always create an array with a type-0.90.0 superblock.
6699 * The newer usage is when assembling an array.
6700 * In this case raid_disks will be 0, and the major_version field is
6701 * use to determine which style super-blocks are to be found on the devices.
6702 * The minor and patch _version numbers are also kept incase the
6703 * super_block handler wishes to interpret them.
6705 static int set_array_info(struct mddev *mddev, mdu_array_info_t *info)
6708 if (info->raid_disks == 0) {
6709 /* just setting version number for superblock loading */
6710 if (info->major_version < 0 ||
6711 info->major_version >= ARRAY_SIZE(super_types) ||
6712 super_types[info->major_version].name == NULL) {
6713 /* maybe try to auto-load a module? */
6714 pr_warn("md: superblock version %d not known\n",
6715 info->major_version);
6716 return -EINVAL;
6718 mddev->major_version = info->major_version;
6719 mddev->minor_version = info->minor_version;
6720 mddev->patch_version = info->patch_version;
6721 mddev->persistent = !info->not_persistent;
6722 /* ensure mddev_put doesn't delete this now that there
6723 * is some minimal configuration.
6725 mddev->ctime = ktime_get_real_seconds();
6726 return 0;
6728 mddev->major_version = MD_MAJOR_VERSION;
6729 mddev->minor_version = MD_MINOR_VERSION;
6730 mddev->patch_version = MD_PATCHLEVEL_VERSION;
6731 mddev->ctime = ktime_get_real_seconds();
6733 mddev->level = info->level;
6734 mddev->clevel[0] = 0;
6735 mddev->dev_sectors = 2 * (sector_t)info->size;
6736 mddev->raid_disks = info->raid_disks;
6737 /* don't set md_minor, it is determined by which /dev/md* was
6738 * openned
6740 if (info->state & (1<<MD_SB_CLEAN))
6741 mddev->recovery_cp = MaxSector;
6742 else
6743 mddev->recovery_cp = 0;
6744 mddev->persistent = ! info->not_persistent;
6745 mddev->external = 0;
6747 mddev->layout = info->layout;
6748 mddev->chunk_sectors = info->chunk_size >> 9;
6750 if (mddev->persistent) {
6751 mddev->max_disks = MD_SB_DISKS;
6752 mddev->flags = 0;
6753 mddev->sb_flags = 0;
6755 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
6757 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6758 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6759 mddev->bitmap_info.offset = 0;
6761 mddev->reshape_position = MaxSector;
6764 * Generate a 128 bit UUID
6766 get_random_bytes(mddev->uuid, 16);
6768 mddev->new_level = mddev->level;
6769 mddev->new_chunk_sectors = mddev->chunk_sectors;
6770 mddev->new_layout = mddev->layout;
6771 mddev->delta_disks = 0;
6772 mddev->reshape_backwards = 0;
6774 return 0;
6777 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6779 lockdep_assert_held(&mddev->reconfig_mutex);
6781 if (mddev->external_size)
6782 return;
6784 mddev->array_sectors = array_sectors;
6786 EXPORT_SYMBOL(md_set_array_sectors);
6788 static int update_size(struct mddev *mddev, sector_t num_sectors)
6790 struct md_rdev *rdev;
6791 int rv;
6792 int fit = (num_sectors == 0);
6793 sector_t old_dev_sectors = mddev->dev_sectors;
6795 if (mddev->pers->resize == NULL)
6796 return -EINVAL;
6797 /* The "num_sectors" is the number of sectors of each device that
6798 * is used. This can only make sense for arrays with redundancy.
6799 * linear and raid0 always use whatever space is available. We can only
6800 * consider changing this number if no resync or reconstruction is
6801 * happening, and if the new size is acceptable. It must fit before the
6802 * sb_start or, if that is <data_offset, it must fit before the size
6803 * of each device. If num_sectors is zero, we find the largest size
6804 * that fits.
6806 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6807 mddev->sync_thread)
6808 return -EBUSY;
6809 if (mddev->ro)
6810 return -EROFS;
6812 rdev_for_each(rdev, mddev) {
6813 sector_t avail = rdev->sectors;
6815 if (fit && (num_sectors == 0 || num_sectors > avail))
6816 num_sectors = avail;
6817 if (avail < num_sectors)
6818 return -ENOSPC;
6820 rv = mddev->pers->resize(mddev, num_sectors);
6821 if (!rv) {
6822 if (mddev_is_clustered(mddev))
6823 md_cluster_ops->update_size(mddev, old_dev_sectors);
6824 else if (mddev->queue) {
6825 set_capacity(mddev->gendisk, mddev->array_sectors);
6826 revalidate_disk(mddev->gendisk);
6829 return rv;
6832 static int update_raid_disks(struct mddev *mddev, int raid_disks)
6834 int rv;
6835 struct md_rdev *rdev;
6836 /* change the number of raid disks */
6837 if (mddev->pers->check_reshape == NULL)
6838 return -EINVAL;
6839 if (mddev->ro)
6840 return -EROFS;
6841 if (raid_disks <= 0 ||
6842 (mddev->max_disks && raid_disks >= mddev->max_disks))
6843 return -EINVAL;
6844 if (mddev->sync_thread ||
6845 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
6846 mddev->reshape_position != MaxSector)
6847 return -EBUSY;
6849 rdev_for_each(rdev, mddev) {
6850 if (mddev->raid_disks < raid_disks &&
6851 rdev->data_offset < rdev->new_data_offset)
6852 return -EINVAL;
6853 if (mddev->raid_disks > raid_disks &&
6854 rdev->data_offset > rdev->new_data_offset)
6855 return -EINVAL;
6858 mddev->delta_disks = raid_disks - mddev->raid_disks;
6859 if (mddev->delta_disks < 0)
6860 mddev->reshape_backwards = 1;
6861 else if (mddev->delta_disks > 0)
6862 mddev->reshape_backwards = 0;
6864 rv = mddev->pers->check_reshape(mddev);
6865 if (rv < 0) {
6866 mddev->delta_disks = 0;
6867 mddev->reshape_backwards = 0;
6869 return rv;
6873 * update_array_info is used to change the configuration of an
6874 * on-line array.
6875 * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
6876 * fields in the info are checked against the array.
6877 * Any differences that cannot be handled will cause an error.
6878 * Normally, only one change can be managed at a time.
6880 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
6882 int rv = 0;
6883 int cnt = 0;
6884 int state = 0;
6886 /* calculate expected state,ignoring low bits */
6887 if (mddev->bitmap && mddev->bitmap_info.offset)
6888 state |= (1 << MD_SB_BITMAP_PRESENT);
6890 if (mddev->major_version != info->major_version ||
6891 mddev->minor_version != info->minor_version ||
6892 /* mddev->patch_version != info->patch_version || */
6893 mddev->ctime != info->ctime ||
6894 mddev->level != info->level ||
6895 /* mddev->layout != info->layout || */
6896 mddev->persistent != !info->not_persistent ||
6897 mddev->chunk_sectors != info->chunk_size >> 9 ||
6898 /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6899 ((state^info->state) & 0xfffffe00)
6901 return -EINVAL;
6902 /* Check there is only one change */
6903 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6904 cnt++;
6905 if (mddev->raid_disks != info->raid_disks)
6906 cnt++;
6907 if (mddev->layout != info->layout)
6908 cnt++;
6909 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6910 cnt++;
6911 if (cnt == 0)
6912 return 0;
6913 if (cnt > 1)
6914 return -EINVAL;
6916 if (mddev->layout != info->layout) {
6917 /* Change layout
6918 * we don't need to do anything at the md level, the
6919 * personality will take care of it all.
6921 if (mddev->pers->check_reshape == NULL)
6922 return -EINVAL;
6923 else {
6924 mddev->new_layout = info->layout;
6925 rv = mddev->pers->check_reshape(mddev);
6926 if (rv)
6927 mddev->new_layout = mddev->layout;
6928 return rv;
6931 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6932 rv = update_size(mddev, (sector_t)info->size * 2);
6934 if (mddev->raid_disks != info->raid_disks)
6935 rv = update_raid_disks(mddev, info->raid_disks);
6937 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6938 if (mddev->pers->quiesce == NULL || mddev->thread == NULL) {
6939 rv = -EINVAL;
6940 goto err;
6942 if (mddev->recovery || mddev->sync_thread) {
6943 rv = -EBUSY;
6944 goto err;
6946 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
6947 struct bitmap *bitmap;
6948 /* add the bitmap */
6949 if (mddev->bitmap) {
6950 rv = -EEXIST;
6951 goto err;
6953 if (mddev->bitmap_info.default_offset == 0) {
6954 rv = -EINVAL;
6955 goto err;
6957 mddev->bitmap_info.offset =
6958 mddev->bitmap_info.default_offset;
6959 mddev->bitmap_info.space =
6960 mddev->bitmap_info.default_space;
6961 bitmap = bitmap_create(mddev, -1);
6962 mddev_suspend(mddev);
6963 if (!IS_ERR(bitmap)) {
6964 mddev->bitmap = bitmap;
6965 rv = bitmap_load(mddev);
6966 } else
6967 rv = PTR_ERR(bitmap);
6968 if (rv)
6969 bitmap_destroy(mddev);
6970 mddev_resume(mddev);
6971 } else {
6972 /* remove the bitmap */
6973 if (!mddev->bitmap) {
6974 rv = -ENOENT;
6975 goto err;
6977 if (mddev->bitmap->storage.file) {
6978 rv = -EINVAL;
6979 goto err;
6981 if (mddev->bitmap_info.nodes) {
6982 /* hold PW on all the bitmap lock */
6983 if (md_cluster_ops->lock_all_bitmaps(mddev) <= 0) {
6984 pr_warn("md: can't change bitmap to none since the array is in use by more than one node\n");
6985 rv = -EPERM;
6986 md_cluster_ops->unlock_all_bitmaps(mddev);
6987 goto err;
6990 mddev->bitmap_info.nodes = 0;
6991 md_cluster_ops->leave(mddev);
6993 mddev_suspend(mddev);
6994 bitmap_destroy(mddev);
6995 mddev_resume(mddev);
6996 mddev->bitmap_info.offset = 0;
6999 md_update_sb(mddev, 1);
7000 return rv;
7001 err:
7002 return rv;
7005 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
7007 struct md_rdev *rdev;
7008 int err = 0;
7010 if (mddev->pers == NULL)
7011 return -ENODEV;
7013 rcu_read_lock();
7014 rdev = md_find_rdev_rcu(mddev, dev);
7015 if (!rdev)
7016 err = -ENODEV;
7017 else {
7018 md_error(mddev, rdev);
7019 if (!test_bit(Faulty, &rdev->flags))
7020 err = -EBUSY;
7022 rcu_read_unlock();
7023 return err;
7027 * We have a problem here : there is no easy way to give a CHS
7028 * virtual geometry. We currently pretend that we have a 2 heads
7029 * 4 sectors (with a BIG number of cylinders...). This drives
7030 * dosfs just mad... ;-)
7032 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
7034 struct mddev *mddev = bdev->bd_disk->private_data;
7036 geo->heads = 2;
7037 geo->sectors = 4;
7038 geo->cylinders = mddev->array_sectors / 8;
7039 return 0;
7042 static inline bool md_ioctl_valid(unsigned int cmd)
7044 switch (cmd) {
7045 case ADD_NEW_DISK:
7046 case BLKROSET:
7047 case GET_ARRAY_INFO:
7048 case GET_BITMAP_FILE:
7049 case GET_DISK_INFO:
7050 case HOT_ADD_DISK:
7051 case HOT_REMOVE_DISK:
7052 case RAID_AUTORUN:
7053 case RAID_VERSION:
7054 case RESTART_ARRAY_RW:
7055 case RUN_ARRAY:
7056 case SET_ARRAY_INFO:
7057 case SET_BITMAP_FILE:
7058 case SET_DISK_FAULTY:
7059 case STOP_ARRAY:
7060 case STOP_ARRAY_RO:
7061 case CLUSTERED_DISK_NACK:
7062 return true;
7063 default:
7064 return false;
7068 static int md_ioctl(struct block_device *bdev, fmode_t mode,
7069 unsigned int cmd, unsigned long arg)
7071 int err = 0;
7072 void __user *argp = (void __user *)arg;
7073 struct mddev *mddev = NULL;
7074 int ro;
7075 bool did_set_md_closing = false;
7077 if (!md_ioctl_valid(cmd))
7078 return -ENOTTY;
7080 switch (cmd) {
7081 case RAID_VERSION:
7082 case GET_ARRAY_INFO:
7083 case GET_DISK_INFO:
7084 break;
7085 default:
7086 if (!capable(CAP_SYS_ADMIN))
7087 return -EACCES;
7091 * Commands dealing with the RAID driver but not any
7092 * particular array:
7094 switch (cmd) {
7095 case RAID_VERSION:
7096 err = get_version(argp);
7097 goto out;
7099 #ifndef MODULE
7100 case RAID_AUTORUN:
7101 err = 0;
7102 autostart_arrays(arg);
7103 goto out;
7104 #endif
7105 default:;
7109 * Commands creating/starting a new array:
7112 mddev = bdev->bd_disk->private_data;
7114 if (!mddev) {
7115 BUG();
7116 goto out;
7119 /* Some actions do not requires the mutex */
7120 switch (cmd) {
7121 case GET_ARRAY_INFO:
7122 if (!mddev->raid_disks && !mddev->external)
7123 err = -ENODEV;
7124 else
7125 err = get_array_info(mddev, argp);
7126 goto out;
7128 case GET_DISK_INFO:
7129 if (!mddev->raid_disks && !mddev->external)
7130 err = -ENODEV;
7131 else
7132 err = get_disk_info(mddev, argp);
7133 goto out;
7135 case SET_DISK_FAULTY:
7136 err = set_disk_faulty(mddev, new_decode_dev(arg));
7137 goto out;
7139 case GET_BITMAP_FILE:
7140 err = get_bitmap_file(mddev, argp);
7141 goto out;
7145 if (cmd == ADD_NEW_DISK)
7146 /* need to ensure md_delayed_delete() has completed */
7147 flush_workqueue(md_misc_wq);
7149 if (cmd == HOT_REMOVE_DISK)
7150 /* need to ensure recovery thread has run */
7151 wait_event_interruptible_timeout(mddev->sb_wait,
7152 !test_bit(MD_RECOVERY_NEEDED,
7153 &mddev->recovery),
7154 msecs_to_jiffies(5000));
7155 if (cmd == STOP_ARRAY || cmd == STOP_ARRAY_RO) {
7156 /* Need to flush page cache, and ensure no-one else opens
7157 * and writes
7159 mutex_lock(&mddev->open_mutex);
7160 if (mddev->pers && atomic_read(&mddev->openers) > 1) {
7161 mutex_unlock(&mddev->open_mutex);
7162 err = -EBUSY;
7163 goto out;
7165 WARN_ON_ONCE(test_bit(MD_CLOSING, &mddev->flags));
7166 set_bit(MD_CLOSING, &mddev->flags);
7167 did_set_md_closing = true;
7168 mutex_unlock(&mddev->open_mutex);
7169 sync_blockdev(bdev);
7171 err = mddev_lock(mddev);
7172 if (err) {
7173 pr_debug("md: ioctl lock interrupted, reason %d, cmd %d\n",
7174 err, cmd);
7175 goto out;
7178 if (cmd == SET_ARRAY_INFO) {
7179 mdu_array_info_t info;
7180 if (!arg)
7181 memset(&info, 0, sizeof(info));
7182 else if (copy_from_user(&info, argp, sizeof(info))) {
7183 err = -EFAULT;
7184 goto unlock;
7186 if (mddev->pers) {
7187 err = update_array_info(mddev, &info);
7188 if (err) {
7189 pr_warn("md: couldn't update array info. %d\n", err);
7190 goto unlock;
7192 goto unlock;
7194 if (!list_empty(&mddev->disks)) {
7195 pr_warn("md: array %s already has disks!\n", mdname(mddev));
7196 err = -EBUSY;
7197 goto unlock;
7199 if (mddev->raid_disks) {
7200 pr_warn("md: array %s already initialised!\n", mdname(mddev));
7201 err = -EBUSY;
7202 goto unlock;
7204 err = set_array_info(mddev, &info);
7205 if (err) {
7206 pr_warn("md: couldn't set array info. %d\n", err);
7207 goto unlock;
7209 goto unlock;
7213 * Commands querying/configuring an existing array:
7215 /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
7216 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
7217 if ((!mddev->raid_disks && !mddev->external)
7218 && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
7219 && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
7220 && cmd != GET_BITMAP_FILE) {
7221 err = -ENODEV;
7222 goto unlock;
7226 * Commands even a read-only array can execute:
7228 switch (cmd) {
7229 case RESTART_ARRAY_RW:
7230 err = restart_array(mddev);
7231 goto unlock;
7233 case STOP_ARRAY:
7234 err = do_md_stop(mddev, 0, bdev);
7235 goto unlock;
7237 case STOP_ARRAY_RO:
7238 err = md_set_readonly(mddev, bdev);
7239 goto unlock;
7241 case HOT_REMOVE_DISK:
7242 err = hot_remove_disk(mddev, new_decode_dev(arg));
7243 goto unlock;
7245 case ADD_NEW_DISK:
7246 /* We can support ADD_NEW_DISK on read-only arrays
7247 * only if we are re-adding a preexisting device.
7248 * So require mddev->pers and MD_DISK_SYNC.
7250 if (mddev->pers) {
7251 mdu_disk_info_t info;
7252 if (copy_from_user(&info, argp, sizeof(info)))
7253 err = -EFAULT;
7254 else if (!(info.state & (1<<MD_DISK_SYNC)))
7255 /* Need to clear read-only for this */
7256 break;
7257 else
7258 err = add_new_disk(mddev, &info);
7259 goto unlock;
7261 break;
7263 case BLKROSET:
7264 if (get_user(ro, (int __user *)(arg))) {
7265 err = -EFAULT;
7266 goto unlock;
7268 err = -EINVAL;
7270 /* if the bdev is going readonly the value of mddev->ro
7271 * does not matter, no writes are coming
7273 if (ro)
7274 goto unlock;
7276 /* are we are already prepared for writes? */
7277 if (mddev->ro != 1)
7278 goto unlock;
7280 /* transitioning to readauto need only happen for
7281 * arrays that call md_write_start
7283 if (mddev->pers) {
7284 err = restart_array(mddev);
7285 if (err == 0) {
7286 mddev->ro = 2;
7287 set_disk_ro(mddev->gendisk, 0);
7290 goto unlock;
7294 * The remaining ioctls are changing the state of the
7295 * superblock, so we do not allow them on read-only arrays.
7297 if (mddev->ro && mddev->pers) {
7298 if (mddev->ro == 2) {
7299 mddev->ro = 0;
7300 sysfs_notify_dirent_safe(mddev->sysfs_state);
7301 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7302 /* mddev_unlock will wake thread */
7303 /* If a device failed while we were read-only, we
7304 * need to make sure the metadata is updated now.
7306 if (test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags)) {
7307 mddev_unlock(mddev);
7308 wait_event(mddev->sb_wait,
7309 !test_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags) &&
7310 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
7311 mddev_lock_nointr(mddev);
7313 } else {
7314 err = -EROFS;
7315 goto unlock;
7319 switch (cmd) {
7320 case ADD_NEW_DISK:
7322 mdu_disk_info_t info;
7323 if (copy_from_user(&info, argp, sizeof(info)))
7324 err = -EFAULT;
7325 else
7326 err = add_new_disk(mddev, &info);
7327 goto unlock;
7330 case CLUSTERED_DISK_NACK:
7331 if (mddev_is_clustered(mddev))
7332 md_cluster_ops->new_disk_ack(mddev, false);
7333 else
7334 err = -EINVAL;
7335 goto unlock;
7337 case HOT_ADD_DISK:
7338 err = hot_add_disk(mddev, new_decode_dev(arg));
7339 goto unlock;
7341 case RUN_ARRAY:
7342 err = do_md_run(mddev);
7343 goto unlock;
7345 case SET_BITMAP_FILE:
7346 err = set_bitmap_file(mddev, (int)arg);
7347 goto unlock;
7349 default:
7350 err = -EINVAL;
7351 goto unlock;
7354 unlock:
7355 if (mddev->hold_active == UNTIL_IOCTL &&
7356 err != -EINVAL)
7357 mddev->hold_active = 0;
7358 mddev_unlock(mddev);
7359 out:
7360 if(did_set_md_closing)
7361 clear_bit(MD_CLOSING, &mddev->flags);
7362 return err;
7364 #ifdef CONFIG_COMPAT
7365 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
7366 unsigned int cmd, unsigned long arg)
7368 switch (cmd) {
7369 case HOT_REMOVE_DISK:
7370 case HOT_ADD_DISK:
7371 case SET_DISK_FAULTY:
7372 case SET_BITMAP_FILE:
7373 /* These take in integer arg, do not convert */
7374 break;
7375 default:
7376 arg = (unsigned long)compat_ptr(arg);
7377 break;
7380 return md_ioctl(bdev, mode, cmd, arg);
7382 #endif /* CONFIG_COMPAT */
7384 static int md_open(struct block_device *bdev, fmode_t mode)
7387 * Succeed if we can lock the mddev, which confirms that
7388 * it isn't being stopped right now.
7390 struct mddev *mddev = mddev_find(bdev->bd_dev);
7391 int err;
7393 if (!mddev)
7394 return -ENODEV;
7396 if (mddev->gendisk != bdev->bd_disk) {
7397 /* we are racing with mddev_put which is discarding this
7398 * bd_disk.
7400 mddev_put(mddev);
7401 /* Wait until bdev->bd_disk is definitely gone */
7402 flush_workqueue(md_misc_wq);
7403 /* Then retry the open from the top */
7404 return -ERESTARTSYS;
7406 BUG_ON(mddev != bdev->bd_disk->private_data);
7408 if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
7409 goto out;
7411 if (test_bit(MD_CLOSING, &mddev->flags)) {
7412 mutex_unlock(&mddev->open_mutex);
7413 err = -ENODEV;
7414 goto out;
7417 err = 0;
7418 atomic_inc(&mddev->openers);
7419 mutex_unlock(&mddev->open_mutex);
7421 check_disk_change(bdev);
7422 out:
7423 if (err)
7424 mddev_put(mddev);
7425 return err;
7428 static void md_release(struct gendisk *disk, fmode_t mode)
7430 struct mddev *mddev = disk->private_data;
7432 BUG_ON(!mddev);
7433 atomic_dec(&mddev->openers);
7434 mddev_put(mddev);
7437 static int md_media_changed(struct gendisk *disk)
7439 struct mddev *mddev = disk->private_data;
7441 return mddev->changed;
7444 static int md_revalidate(struct gendisk *disk)
7446 struct mddev *mddev = disk->private_data;
7448 mddev->changed = 0;
7449 return 0;
7451 static const struct block_device_operations md_fops =
7453 .owner = THIS_MODULE,
7454 .open = md_open,
7455 .release = md_release,
7456 .ioctl = md_ioctl,
7457 #ifdef CONFIG_COMPAT
7458 .compat_ioctl = md_compat_ioctl,
7459 #endif
7460 .getgeo = md_getgeo,
7461 .media_changed = md_media_changed,
7462 .revalidate_disk= md_revalidate,
7465 static int md_thread(void *arg)
7467 struct md_thread *thread = arg;
7470 * md_thread is a 'system-thread', it's priority should be very
7471 * high. We avoid resource deadlocks individually in each
7472 * raid personality. (RAID5 does preallocation) We also use RR and
7473 * the very same RT priority as kswapd, thus we will never get
7474 * into a priority inversion deadlock.
7476 * we definitely have to have equal or higher priority than
7477 * bdflush, otherwise bdflush will deadlock if there are too
7478 * many dirty RAID5 blocks.
7481 allow_signal(SIGKILL);
7482 while (!kthread_should_stop()) {
7484 /* We need to wait INTERRUPTIBLE so that
7485 * we don't add to the load-average.
7486 * That means we need to be sure no signals are
7487 * pending
7489 if (signal_pending(current))
7490 flush_signals(current);
7492 wait_event_interruptible_timeout
7493 (thread->wqueue,
7494 test_bit(THREAD_WAKEUP, &thread->flags)
7495 || kthread_should_stop() || kthread_should_park(),
7496 thread->timeout);
7498 clear_bit(THREAD_WAKEUP, &thread->flags);
7499 if (kthread_should_park())
7500 kthread_parkme();
7501 if (!kthread_should_stop())
7502 thread->run(thread);
7505 return 0;
7508 void md_wakeup_thread(struct md_thread *thread)
7510 if (thread) {
7511 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
7512 set_bit(THREAD_WAKEUP, &thread->flags);
7513 wake_up(&thread->wqueue);
7516 EXPORT_SYMBOL(md_wakeup_thread);
7518 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
7519 struct mddev *mddev, const char *name)
7521 struct md_thread *thread;
7523 thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
7524 if (!thread)
7525 return NULL;
7527 init_waitqueue_head(&thread->wqueue);
7529 thread->run = run;
7530 thread->mddev = mddev;
7531 thread->timeout = MAX_SCHEDULE_TIMEOUT;
7532 thread->tsk = kthread_run(md_thread, thread,
7533 "%s_%s",
7534 mdname(thread->mddev),
7535 name);
7536 if (IS_ERR(thread->tsk)) {
7537 kfree(thread);
7538 return NULL;
7540 return thread;
7542 EXPORT_SYMBOL(md_register_thread);
7544 void md_unregister_thread(struct md_thread **threadp)
7546 struct md_thread *thread = *threadp;
7547 if (!thread)
7548 return;
7549 pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
7550 /* Locking ensures that mddev_unlock does not wake_up a
7551 * non-existent thread
7553 spin_lock(&pers_lock);
7554 *threadp = NULL;
7555 spin_unlock(&pers_lock);
7557 kthread_stop(thread->tsk);
7558 kfree(thread);
7560 EXPORT_SYMBOL(md_unregister_thread);
7562 void md_error(struct mddev *mddev, struct md_rdev *rdev)
7564 if (!rdev || test_bit(Faulty, &rdev->flags))
7565 return;
7567 if (!mddev->pers || !mddev->pers->error_handler)
7568 return;
7569 mddev->pers->error_handler(mddev,rdev);
7570 if (mddev->degraded)
7571 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7572 sysfs_notify_dirent_safe(rdev->sysfs_state);
7573 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7574 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7575 md_wakeup_thread(mddev->thread);
7576 if (mddev->event_work.func)
7577 queue_work(md_misc_wq, &mddev->event_work);
7578 md_new_event(mddev);
7580 EXPORT_SYMBOL(md_error);
7582 /* seq_file implementation /proc/mdstat */
7584 static void status_unused(struct seq_file *seq)
7586 int i = 0;
7587 struct md_rdev *rdev;
7589 seq_printf(seq, "unused devices: ");
7591 list_for_each_entry(rdev, &pending_raid_disks, same_set) {
7592 char b[BDEVNAME_SIZE];
7593 i++;
7594 seq_printf(seq, "%s ",
7595 bdevname(rdev->bdev,b));
7597 if (!i)
7598 seq_printf(seq, "<none>");
7600 seq_printf(seq, "\n");
7603 static int status_resync(struct seq_file *seq, struct mddev *mddev)
7605 sector_t max_sectors, resync, res;
7606 unsigned long dt, db;
7607 sector_t rt;
7608 int scale;
7609 unsigned int per_milli;
7611 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
7612 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7613 max_sectors = mddev->resync_max_sectors;
7614 else
7615 max_sectors = mddev->dev_sectors;
7617 resync = mddev->curr_resync;
7618 if (resync <= 3) {
7619 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7620 /* Still cleaning up */
7621 resync = max_sectors;
7622 } else if (resync > max_sectors)
7623 resync = max_sectors;
7624 else
7625 resync -= atomic_read(&mddev->recovery_active);
7627 if (resync == 0) {
7628 if (mddev->recovery_cp < MaxSector) {
7629 seq_printf(seq, "\tresync=PENDING");
7630 return 1;
7632 return 0;
7634 if (resync < 3) {
7635 seq_printf(seq, "\tresync=DELAYED");
7636 return 1;
7639 WARN_ON(max_sectors == 0);
7640 /* Pick 'scale' such that (resync>>scale)*1000 will fit
7641 * in a sector_t, and (max_sectors>>scale) will fit in a
7642 * u32, as those are the requirements for sector_div.
7643 * Thus 'scale' must be at least 10
7645 scale = 10;
7646 if (sizeof(sector_t) > sizeof(unsigned long)) {
7647 while ( max_sectors/2 > (1ULL<<(scale+32)))
7648 scale++;
7650 res = (resync>>scale)*1000;
7651 sector_div(res, (u32)((max_sectors>>scale)+1));
7653 per_milli = res;
7655 int i, x = per_milli/50, y = 20-x;
7656 seq_printf(seq, "[");
7657 for (i = 0; i < x; i++)
7658 seq_printf(seq, "=");
7659 seq_printf(seq, ">");
7660 for (i = 0; i < y; i++)
7661 seq_printf(seq, ".");
7662 seq_printf(seq, "] ");
7664 seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
7665 (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
7666 "reshape" :
7667 (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
7668 "check" :
7669 (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
7670 "resync" : "recovery"))),
7671 per_milli/10, per_milli % 10,
7672 (unsigned long long) resync/2,
7673 (unsigned long long) max_sectors/2);
7676 * dt: time from mark until now
7677 * db: blocks written from mark until now
7678 * rt: remaining time
7680 * rt is a sector_t, so could be 32bit or 64bit.
7681 * So we divide before multiply in case it is 32bit and close
7682 * to the limit.
7683 * We scale the divisor (db) by 32 to avoid losing precision
7684 * near the end of resync when the number of remaining sectors
7685 * is close to 'db'.
7686 * We then divide rt by 32 after multiplying by db to compensate.
7687 * The '+1' avoids division by zero if db is very small.
7689 dt = ((jiffies - mddev->resync_mark) / HZ);
7690 if (!dt) dt++;
7691 db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
7692 - mddev->resync_mark_cnt;
7694 rt = max_sectors - resync; /* number of remaining sectors */
7695 sector_div(rt, db/32+1);
7696 rt *= dt;
7697 rt >>= 5;
7699 seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
7700 ((unsigned long)rt % 60)/6);
7702 seq_printf(seq, " speed=%ldK/sec", db/2/dt);
7703 return 1;
7706 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
7708 struct list_head *tmp;
7709 loff_t l = *pos;
7710 struct mddev *mddev;
7712 if (l >= 0x10000)
7713 return NULL;
7714 if (!l--)
7715 /* header */
7716 return (void*)1;
7718 spin_lock(&all_mddevs_lock);
7719 list_for_each(tmp,&all_mddevs)
7720 if (!l--) {
7721 mddev = list_entry(tmp, struct mddev, all_mddevs);
7722 mddev_get(mddev);
7723 spin_unlock(&all_mddevs_lock);
7724 return mddev;
7726 spin_unlock(&all_mddevs_lock);
7727 if (!l--)
7728 return (void*)2;/* tail */
7729 return NULL;
7732 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
7734 struct list_head *tmp;
7735 struct mddev *next_mddev, *mddev = v;
7737 ++*pos;
7738 if (v == (void*)2)
7739 return NULL;
7741 spin_lock(&all_mddevs_lock);
7742 if (v == (void*)1)
7743 tmp = all_mddevs.next;
7744 else
7745 tmp = mddev->all_mddevs.next;
7746 if (tmp != &all_mddevs)
7747 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
7748 else {
7749 next_mddev = (void*)2;
7750 *pos = 0x10000;
7752 spin_unlock(&all_mddevs_lock);
7754 if (v != (void*)1)
7755 mddev_put(mddev);
7756 return next_mddev;
7760 static void md_seq_stop(struct seq_file *seq, void *v)
7762 struct mddev *mddev = v;
7764 if (mddev && v != (void*)1 && v != (void*)2)
7765 mddev_put(mddev);
7768 static int md_seq_show(struct seq_file *seq, void *v)
7770 struct mddev *mddev = v;
7771 sector_t sectors;
7772 struct md_rdev *rdev;
7774 if (v == (void*)1) {
7775 struct md_personality *pers;
7776 seq_printf(seq, "Personalities : ");
7777 spin_lock(&pers_lock);
7778 list_for_each_entry(pers, &pers_list, list)
7779 seq_printf(seq, "[%s] ", pers->name);
7781 spin_unlock(&pers_lock);
7782 seq_printf(seq, "\n");
7783 seq->poll_event = atomic_read(&md_event_count);
7784 return 0;
7786 if (v == (void*)2) {
7787 status_unused(seq);
7788 return 0;
7791 spin_lock(&mddev->lock);
7792 if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7793 seq_printf(seq, "%s : %sactive", mdname(mddev),
7794 mddev->pers ? "" : "in");
7795 if (mddev->pers) {
7796 if (mddev->ro==1)
7797 seq_printf(seq, " (read-only)");
7798 if (mddev->ro==2)
7799 seq_printf(seq, " (auto-read-only)");
7800 seq_printf(seq, " %s", mddev->pers->name);
7803 sectors = 0;
7804 rcu_read_lock();
7805 rdev_for_each_rcu(rdev, mddev) {
7806 char b[BDEVNAME_SIZE];
7807 seq_printf(seq, " %s[%d]",
7808 bdevname(rdev->bdev,b), rdev->desc_nr);
7809 if (test_bit(WriteMostly, &rdev->flags))
7810 seq_printf(seq, "(W)");
7811 if (test_bit(Journal, &rdev->flags))
7812 seq_printf(seq, "(J)");
7813 if (test_bit(Faulty, &rdev->flags)) {
7814 seq_printf(seq, "(F)");
7815 continue;
7817 if (rdev->raid_disk < 0)
7818 seq_printf(seq, "(S)"); /* spare */
7819 if (test_bit(Replacement, &rdev->flags))
7820 seq_printf(seq, "(R)");
7821 sectors += rdev->sectors;
7823 rcu_read_unlock();
7825 if (!list_empty(&mddev->disks)) {
7826 if (mddev->pers)
7827 seq_printf(seq, "\n %llu blocks",
7828 (unsigned long long)
7829 mddev->array_sectors / 2);
7830 else
7831 seq_printf(seq, "\n %llu blocks",
7832 (unsigned long long)sectors / 2);
7834 if (mddev->persistent) {
7835 if (mddev->major_version != 0 ||
7836 mddev->minor_version != 90) {
7837 seq_printf(seq," super %d.%d",
7838 mddev->major_version,
7839 mddev->minor_version);
7841 } else if (mddev->external)
7842 seq_printf(seq, " super external:%s",
7843 mddev->metadata_type);
7844 else
7845 seq_printf(seq, " super non-persistent");
7847 if (mddev->pers) {
7848 mddev->pers->status(seq, mddev);
7849 seq_printf(seq, "\n ");
7850 if (mddev->pers->sync_request) {
7851 if (status_resync(seq, mddev))
7852 seq_printf(seq, "\n ");
7854 } else
7855 seq_printf(seq, "\n ");
7857 bitmap_status(seq, mddev->bitmap);
7859 seq_printf(seq, "\n");
7861 spin_unlock(&mddev->lock);
7863 return 0;
7866 static const struct seq_operations md_seq_ops = {
7867 .start = md_seq_start,
7868 .next = md_seq_next,
7869 .stop = md_seq_stop,
7870 .show = md_seq_show,
7873 static int md_seq_open(struct inode *inode, struct file *file)
7875 struct seq_file *seq;
7876 int error;
7878 error = seq_open(file, &md_seq_ops);
7879 if (error)
7880 return error;
7882 seq = file->private_data;
7883 seq->poll_event = atomic_read(&md_event_count);
7884 return error;
7887 static int md_unloading;
7888 static __poll_t mdstat_poll(struct file *filp, poll_table *wait)
7890 struct seq_file *seq = filp->private_data;
7891 __poll_t mask;
7893 if (md_unloading)
7894 return EPOLLIN|EPOLLRDNORM|EPOLLERR|EPOLLPRI;
7895 poll_wait(filp, &md_event_waiters, wait);
7897 /* always allow read */
7898 mask = EPOLLIN | EPOLLRDNORM;
7900 if (seq->poll_event != atomic_read(&md_event_count))
7901 mask |= EPOLLERR | EPOLLPRI;
7902 return mask;
7905 static const struct file_operations md_seq_fops = {
7906 .owner = THIS_MODULE,
7907 .open = md_seq_open,
7908 .read = seq_read,
7909 .llseek = seq_lseek,
7910 .release = seq_release,
7911 .poll = mdstat_poll,
7914 int register_md_personality(struct md_personality *p)
7916 pr_debug("md: %s personality registered for level %d\n",
7917 p->name, p->level);
7918 spin_lock(&pers_lock);
7919 list_add_tail(&p->list, &pers_list);
7920 spin_unlock(&pers_lock);
7921 return 0;
7923 EXPORT_SYMBOL(register_md_personality);
7925 int unregister_md_personality(struct md_personality *p)
7927 pr_debug("md: %s personality unregistered\n", p->name);
7928 spin_lock(&pers_lock);
7929 list_del_init(&p->list);
7930 spin_unlock(&pers_lock);
7931 return 0;
7933 EXPORT_SYMBOL(unregister_md_personality);
7935 int register_md_cluster_operations(struct md_cluster_operations *ops,
7936 struct module *module)
7938 int ret = 0;
7939 spin_lock(&pers_lock);
7940 if (md_cluster_ops != NULL)
7941 ret = -EALREADY;
7942 else {
7943 md_cluster_ops = ops;
7944 md_cluster_mod = module;
7946 spin_unlock(&pers_lock);
7947 return ret;
7949 EXPORT_SYMBOL(register_md_cluster_operations);
7951 int unregister_md_cluster_operations(void)
7953 spin_lock(&pers_lock);
7954 md_cluster_ops = NULL;
7955 spin_unlock(&pers_lock);
7956 return 0;
7958 EXPORT_SYMBOL(unregister_md_cluster_operations);
7960 int md_setup_cluster(struct mddev *mddev, int nodes)
7962 if (!md_cluster_ops)
7963 request_module("md-cluster");
7964 spin_lock(&pers_lock);
7965 /* ensure module won't be unloaded */
7966 if (!md_cluster_ops || !try_module_get(md_cluster_mod)) {
7967 pr_warn("can't find md-cluster module or get it's reference.\n");
7968 spin_unlock(&pers_lock);
7969 return -ENOENT;
7971 spin_unlock(&pers_lock);
7973 return md_cluster_ops->join(mddev, nodes);
7976 void md_cluster_stop(struct mddev *mddev)
7978 if (!md_cluster_ops)
7979 return;
7980 md_cluster_ops->leave(mddev);
7981 module_put(md_cluster_mod);
7984 static int is_mddev_idle(struct mddev *mddev, int init)
7986 struct md_rdev *rdev;
7987 int idle;
7988 int curr_events;
7990 idle = 1;
7991 rcu_read_lock();
7992 rdev_for_each_rcu(rdev, mddev) {
7993 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
7994 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
7995 (int)part_stat_read(&disk->part0, sectors[1]) -
7996 atomic_read(&disk->sync_io);
7997 /* sync IO will cause sync_io to increase before the disk_stats
7998 * as sync_io is counted when a request starts, and
7999 * disk_stats is counted when it completes.
8000 * So resync activity will cause curr_events to be smaller than
8001 * when there was no such activity.
8002 * non-sync IO will cause disk_stat to increase without
8003 * increasing sync_io so curr_events will (eventually)
8004 * be larger than it was before. Once it becomes
8005 * substantially larger, the test below will cause
8006 * the array to appear non-idle, and resync will slow
8007 * down.
8008 * If there is a lot of outstanding resync activity when
8009 * we set last_event to curr_events, then all that activity
8010 * completing might cause the array to appear non-idle
8011 * and resync will be slowed down even though there might
8012 * not have been non-resync activity. This will only
8013 * happen once though. 'last_events' will soon reflect
8014 * the state where there is little or no outstanding
8015 * resync requests, and further resync activity will
8016 * always make curr_events less than last_events.
8019 if (init || curr_events - rdev->last_events > 64) {
8020 rdev->last_events = curr_events;
8021 idle = 0;
8024 rcu_read_unlock();
8025 return idle;
8028 void md_done_sync(struct mddev *mddev, int blocks, int ok)
8030 /* another "blocks" (512byte) blocks have been synced */
8031 atomic_sub(blocks, &mddev->recovery_active);
8032 wake_up(&mddev->recovery_wait);
8033 if (!ok) {
8034 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8035 set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
8036 md_wakeup_thread(mddev->thread);
8037 // stop recovery, signal do_sync ....
8040 EXPORT_SYMBOL(md_done_sync);
8042 /* md_write_start(mddev, bi)
8043 * If we need to update some array metadata (e.g. 'active' flag
8044 * in superblock) before writing, schedule a superblock update
8045 * and wait for it to complete.
8046 * A return value of 'false' means that the write wasn't recorded
8047 * and cannot proceed as the array is being suspend.
8049 bool md_write_start(struct mddev *mddev, struct bio *bi)
8051 int did_change = 0;
8052 if (bio_data_dir(bi) != WRITE)
8053 return true;
8055 BUG_ON(mddev->ro == 1);
8056 if (mddev->ro == 2) {
8057 /* need to switch to read/write */
8058 mddev->ro = 0;
8059 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8060 md_wakeup_thread(mddev->thread);
8061 md_wakeup_thread(mddev->sync_thread);
8062 did_change = 1;
8064 rcu_read_lock();
8065 percpu_ref_get(&mddev->writes_pending);
8066 smp_mb(); /* Match smp_mb in set_in_sync() */
8067 if (mddev->safemode == 1)
8068 mddev->safemode = 0;
8069 /* sync_checkers is always 0 when writes_pending is in per-cpu mode */
8070 if (mddev->in_sync || mddev->sync_checkers) {
8071 spin_lock(&mddev->lock);
8072 if (mddev->in_sync) {
8073 mddev->in_sync = 0;
8074 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8075 set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8076 md_wakeup_thread(mddev->thread);
8077 did_change = 1;
8079 spin_unlock(&mddev->lock);
8081 rcu_read_unlock();
8082 if (did_change)
8083 sysfs_notify_dirent_safe(mddev->sysfs_state);
8084 wait_event(mddev->sb_wait,
8085 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags) ||
8086 mddev->suspended);
8087 if (test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags)) {
8088 percpu_ref_put(&mddev->writes_pending);
8089 return false;
8091 return true;
8093 EXPORT_SYMBOL(md_write_start);
8095 /* md_write_inc can only be called when md_write_start() has
8096 * already been called at least once of the current request.
8097 * It increments the counter and is useful when a single request
8098 * is split into several parts. Each part causes an increment and
8099 * so needs a matching md_write_end().
8100 * Unlike md_write_start(), it is safe to call md_write_inc() inside
8101 * a spinlocked region.
8103 void md_write_inc(struct mddev *mddev, struct bio *bi)
8105 if (bio_data_dir(bi) != WRITE)
8106 return;
8107 WARN_ON_ONCE(mddev->in_sync || mddev->ro);
8108 percpu_ref_get(&mddev->writes_pending);
8110 EXPORT_SYMBOL(md_write_inc);
8112 void md_write_end(struct mddev *mddev)
8114 percpu_ref_put(&mddev->writes_pending);
8116 if (mddev->safemode == 2)
8117 md_wakeup_thread(mddev->thread);
8118 else if (mddev->safemode_delay)
8119 /* The roundup() ensures this only performs locking once
8120 * every ->safemode_delay jiffies
8122 mod_timer(&mddev->safemode_timer,
8123 roundup(jiffies, mddev->safemode_delay) +
8124 mddev->safemode_delay);
8127 EXPORT_SYMBOL(md_write_end);
8129 /* md_allow_write(mddev)
8130 * Calling this ensures that the array is marked 'active' so that writes
8131 * may proceed without blocking. It is important to call this before
8132 * attempting a GFP_KERNEL allocation while holding the mddev lock.
8133 * Must be called with mddev_lock held.
8135 void md_allow_write(struct mddev *mddev)
8137 if (!mddev->pers)
8138 return;
8139 if (mddev->ro)
8140 return;
8141 if (!mddev->pers->sync_request)
8142 return;
8144 spin_lock(&mddev->lock);
8145 if (mddev->in_sync) {
8146 mddev->in_sync = 0;
8147 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8148 set_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8149 if (mddev->safemode_delay &&
8150 mddev->safemode == 0)
8151 mddev->safemode = 1;
8152 spin_unlock(&mddev->lock);
8153 md_update_sb(mddev, 0);
8154 sysfs_notify_dirent_safe(mddev->sysfs_state);
8155 /* wait for the dirty state to be recorded in the metadata */
8156 wait_event(mddev->sb_wait,
8157 !test_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags));
8158 } else
8159 spin_unlock(&mddev->lock);
8161 EXPORT_SYMBOL_GPL(md_allow_write);
8163 #define SYNC_MARKS 10
8164 #define SYNC_MARK_STEP (3*HZ)
8165 #define UPDATE_FREQUENCY (5*60*HZ)
8166 void md_do_sync(struct md_thread *thread)
8168 struct mddev *mddev = thread->mddev;
8169 struct mddev *mddev2;
8170 unsigned int currspeed = 0,
8171 window;
8172 sector_t max_sectors,j, io_sectors, recovery_done;
8173 unsigned long mark[SYNC_MARKS];
8174 unsigned long update_time;
8175 sector_t mark_cnt[SYNC_MARKS];
8176 int last_mark,m;
8177 struct list_head *tmp;
8178 sector_t last_check;
8179 int skipped = 0;
8180 struct md_rdev *rdev;
8181 char *desc, *action = NULL;
8182 struct blk_plug plug;
8183 int ret;
8185 /* just incase thread restarts... */
8186 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8187 test_bit(MD_RECOVERY_WAIT, &mddev->recovery))
8188 return;
8189 if (mddev->ro) {/* never try to sync a read-only array */
8190 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8191 return;
8194 if (mddev_is_clustered(mddev)) {
8195 ret = md_cluster_ops->resync_start(mddev);
8196 if (ret)
8197 goto skip;
8199 set_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags);
8200 if (!(test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
8201 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) ||
8202 test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
8203 && ((unsigned long long)mddev->curr_resync_completed
8204 < (unsigned long long)mddev->resync_max_sectors))
8205 goto skip;
8208 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8209 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)) {
8210 desc = "data-check";
8211 action = "check";
8212 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8213 desc = "requested-resync";
8214 action = "repair";
8215 } else
8216 desc = "resync";
8217 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8218 desc = "reshape";
8219 else
8220 desc = "recovery";
8222 mddev->last_sync_action = action ?: desc;
8224 /* we overload curr_resync somewhat here.
8225 * 0 == not engaged in resync at all
8226 * 2 == checking that there is no conflict with another sync
8227 * 1 == like 2, but have yielded to allow conflicting resync to
8228 * commense
8229 * other == active in resync - this many blocks
8231 * Before starting a resync we must have set curr_resync to
8232 * 2, and then checked that every "conflicting" array has curr_resync
8233 * less than ours. When we find one that is the same or higher
8234 * we wait on resync_wait. To avoid deadlock, we reduce curr_resync
8235 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
8236 * This will mean we have to start checking from the beginning again.
8240 do {
8241 int mddev2_minor = -1;
8242 mddev->curr_resync = 2;
8244 try_again:
8245 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8246 goto skip;
8247 for_each_mddev(mddev2, tmp) {
8248 if (mddev2 == mddev)
8249 continue;
8250 if (!mddev->parallel_resync
8251 && mddev2->curr_resync
8252 && match_mddev_units(mddev, mddev2)) {
8253 DEFINE_WAIT(wq);
8254 if (mddev < mddev2 && mddev->curr_resync == 2) {
8255 /* arbitrarily yield */
8256 mddev->curr_resync = 1;
8257 wake_up(&resync_wait);
8259 if (mddev > mddev2 && mddev->curr_resync == 1)
8260 /* no need to wait here, we can wait the next
8261 * time 'round when curr_resync == 2
8263 continue;
8264 /* We need to wait 'interruptible' so as not to
8265 * contribute to the load average, and not to
8266 * be caught by 'softlockup'
8268 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
8269 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8270 mddev2->curr_resync >= mddev->curr_resync) {
8271 if (mddev2_minor != mddev2->md_minor) {
8272 mddev2_minor = mddev2->md_minor;
8273 pr_info("md: delaying %s of %s until %s has finished (they share one or more physical units)\n",
8274 desc, mdname(mddev),
8275 mdname(mddev2));
8277 mddev_put(mddev2);
8278 if (signal_pending(current))
8279 flush_signals(current);
8280 schedule();
8281 finish_wait(&resync_wait, &wq);
8282 goto try_again;
8284 finish_wait(&resync_wait, &wq);
8287 } while (mddev->curr_resync < 2);
8289 j = 0;
8290 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8291 /* resync follows the size requested by the personality,
8292 * which defaults to physical size, but can be virtual size
8294 max_sectors = mddev->resync_max_sectors;
8295 atomic64_set(&mddev->resync_mismatches, 0);
8296 /* we don't use the checkpoint if there's a bitmap */
8297 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8298 j = mddev->resync_min;
8299 else if (!mddev->bitmap)
8300 j = mddev->recovery_cp;
8302 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
8303 max_sectors = mddev->resync_max_sectors;
8304 else {
8305 /* recovery follows the physical size of devices */
8306 max_sectors = mddev->dev_sectors;
8307 j = MaxSector;
8308 rcu_read_lock();
8309 rdev_for_each_rcu(rdev, mddev)
8310 if (rdev->raid_disk >= 0 &&
8311 !test_bit(Journal, &rdev->flags) &&
8312 !test_bit(Faulty, &rdev->flags) &&
8313 !test_bit(In_sync, &rdev->flags) &&
8314 rdev->recovery_offset < j)
8315 j = rdev->recovery_offset;
8316 rcu_read_unlock();
8318 /* If there is a bitmap, we need to make sure all
8319 * writes that started before we added a spare
8320 * complete before we start doing a recovery.
8321 * Otherwise the write might complete and (via
8322 * bitmap_endwrite) set a bit in the bitmap after the
8323 * recovery has checked that bit and skipped that
8324 * region.
8326 if (mddev->bitmap) {
8327 mddev->pers->quiesce(mddev, 1);
8328 mddev->pers->quiesce(mddev, 0);
8332 pr_info("md: %s of RAID array %s\n", desc, mdname(mddev));
8333 pr_debug("md: minimum _guaranteed_ speed: %d KB/sec/disk.\n", speed_min(mddev));
8334 pr_debug("md: using maximum available idle IO bandwidth (but not more than %d KB/sec) for %s.\n",
8335 speed_max(mddev), desc);
8337 is_mddev_idle(mddev, 1); /* this initializes IO event counters */
8339 io_sectors = 0;
8340 for (m = 0; m < SYNC_MARKS; m++) {
8341 mark[m] = jiffies;
8342 mark_cnt[m] = io_sectors;
8344 last_mark = 0;
8345 mddev->resync_mark = mark[last_mark];
8346 mddev->resync_mark_cnt = mark_cnt[last_mark];
8349 * Tune reconstruction:
8351 window = 32*(PAGE_SIZE/512);
8352 pr_debug("md: using %dk window, over a total of %lluk.\n",
8353 window/2, (unsigned long long)max_sectors/2);
8355 atomic_set(&mddev->recovery_active, 0);
8356 last_check = 0;
8358 if (j>2) {
8359 pr_debug("md: resuming %s of %s from checkpoint.\n",
8360 desc, mdname(mddev));
8361 mddev->curr_resync = j;
8362 } else
8363 mddev->curr_resync = 3; /* no longer delayed */
8364 mddev->curr_resync_completed = j;
8365 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8366 md_new_event(mddev);
8367 update_time = jiffies;
8369 blk_start_plug(&plug);
8370 while (j < max_sectors) {
8371 sector_t sectors;
8373 skipped = 0;
8375 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8376 ((mddev->curr_resync > mddev->curr_resync_completed &&
8377 (mddev->curr_resync - mddev->curr_resync_completed)
8378 > (max_sectors >> 4)) ||
8379 time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
8380 (j - mddev->curr_resync_completed)*2
8381 >= mddev->resync_max - mddev->curr_resync_completed ||
8382 mddev->curr_resync_completed > mddev->resync_max
8383 )) {
8384 /* time to update curr_resync_completed */
8385 wait_event(mddev->recovery_wait,
8386 atomic_read(&mddev->recovery_active) == 0);
8387 mddev->curr_resync_completed = j;
8388 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
8389 j > mddev->recovery_cp)
8390 mddev->recovery_cp = j;
8391 update_time = jiffies;
8392 set_bit(MD_SB_CHANGE_CLEAN, &mddev->sb_flags);
8393 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8396 while (j >= mddev->resync_max &&
8397 !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8398 /* As this condition is controlled by user-space,
8399 * we can block indefinitely, so use '_interruptible'
8400 * to avoid triggering warnings.
8402 flush_signals(current); /* just in case */
8403 wait_event_interruptible(mddev->recovery_wait,
8404 mddev->resync_max > j
8405 || test_bit(MD_RECOVERY_INTR,
8406 &mddev->recovery));
8409 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8410 break;
8412 sectors = mddev->pers->sync_request(mddev, j, &skipped);
8413 if (sectors == 0) {
8414 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8415 break;
8418 if (!skipped) { /* actual IO requested */
8419 io_sectors += sectors;
8420 atomic_add(sectors, &mddev->recovery_active);
8423 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8424 break;
8426 j += sectors;
8427 if (j > max_sectors)
8428 /* when skipping, extra large numbers can be returned. */
8429 j = max_sectors;
8430 if (j > 2)
8431 mddev->curr_resync = j;
8432 mddev->curr_mark_cnt = io_sectors;
8433 if (last_check == 0)
8434 /* this is the earliest that rebuild will be
8435 * visible in /proc/mdstat
8437 md_new_event(mddev);
8439 if (last_check + window > io_sectors || j == max_sectors)
8440 continue;
8442 last_check = io_sectors;
8443 repeat:
8444 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
8445 /* step marks */
8446 int next = (last_mark+1) % SYNC_MARKS;
8448 mddev->resync_mark = mark[next];
8449 mddev->resync_mark_cnt = mark_cnt[next];
8450 mark[next] = jiffies;
8451 mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
8452 last_mark = next;
8455 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8456 break;
8459 * this loop exits only if either when we are slower than
8460 * the 'hard' speed limit, or the system was IO-idle for
8461 * a jiffy.
8462 * the system might be non-idle CPU-wise, but we only care
8463 * about not overloading the IO subsystem. (things like an
8464 * e2fsck being done on the RAID array should execute fast)
8466 cond_resched();
8468 recovery_done = io_sectors - atomic_read(&mddev->recovery_active);
8469 currspeed = ((unsigned long)(recovery_done - mddev->resync_mark_cnt))/2
8470 /((jiffies-mddev->resync_mark)/HZ +1) +1;
8472 if (currspeed > speed_min(mddev)) {
8473 if (currspeed > speed_max(mddev)) {
8474 msleep(500);
8475 goto repeat;
8477 if (!is_mddev_idle(mddev, 0)) {
8479 * Give other IO more of a chance.
8480 * The faster the devices, the less we wait.
8482 wait_event(mddev->recovery_wait,
8483 !atomic_read(&mddev->recovery_active));
8487 pr_info("md: %s: %s %s.\n",mdname(mddev), desc,
8488 test_bit(MD_RECOVERY_INTR, &mddev->recovery)
8489 ? "interrupted" : "done");
8491 * this also signals 'finished resyncing' to md_stop
8493 blk_finish_plug(&plug);
8494 wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
8496 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8497 !test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8498 mddev->curr_resync > 3) {
8499 mddev->curr_resync_completed = mddev->curr_resync;
8500 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
8502 mddev->pers->sync_request(mddev, max_sectors, &skipped);
8504 if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
8505 mddev->curr_resync > 3) {
8506 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
8507 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8508 if (mddev->curr_resync >= mddev->recovery_cp) {
8509 pr_debug("md: checkpointing %s of %s.\n",
8510 desc, mdname(mddev));
8511 if (test_bit(MD_RECOVERY_ERROR,
8512 &mddev->recovery))
8513 mddev->recovery_cp =
8514 mddev->curr_resync_completed;
8515 else
8516 mddev->recovery_cp =
8517 mddev->curr_resync;
8519 } else
8520 mddev->recovery_cp = MaxSector;
8521 } else {
8522 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
8523 mddev->curr_resync = MaxSector;
8524 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8525 test_bit(MD_RECOVERY_RECOVER, &mddev->recovery)) {
8526 rcu_read_lock();
8527 rdev_for_each_rcu(rdev, mddev)
8528 if (rdev->raid_disk >= 0 &&
8529 mddev->delta_disks >= 0 &&
8530 !test_bit(Journal, &rdev->flags) &&
8531 !test_bit(Faulty, &rdev->flags) &&
8532 !test_bit(In_sync, &rdev->flags) &&
8533 rdev->recovery_offset < mddev->curr_resync)
8534 rdev->recovery_offset = mddev->curr_resync;
8535 rcu_read_unlock();
8539 skip:
8540 /* set CHANGE_PENDING here since maybe another update is needed,
8541 * so other nodes are informed. It should be harmless for normal
8542 * raid */
8543 set_mask_bits(&mddev->sb_flags, 0,
8544 BIT(MD_SB_CHANGE_PENDING) | BIT(MD_SB_CHANGE_DEVS));
8546 spin_lock(&mddev->lock);
8547 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
8548 /* We completed so min/max setting can be forgotten if used. */
8549 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8550 mddev->resync_min = 0;
8551 mddev->resync_max = MaxSector;
8552 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
8553 mddev->resync_min = mddev->curr_resync_completed;
8554 set_bit(MD_RECOVERY_DONE, &mddev->recovery);
8555 mddev->curr_resync = 0;
8556 spin_unlock(&mddev->lock);
8558 wake_up(&resync_wait);
8559 md_wakeup_thread(mddev->thread);
8560 return;
8562 EXPORT_SYMBOL_GPL(md_do_sync);
8564 static int remove_and_add_spares(struct mddev *mddev,
8565 struct md_rdev *this)
8567 struct md_rdev *rdev;
8568 int spares = 0;
8569 int removed = 0;
8570 bool remove_some = false;
8572 rdev_for_each(rdev, mddev) {
8573 if ((this == NULL || rdev == this) &&
8574 rdev->raid_disk >= 0 &&
8575 !test_bit(Blocked, &rdev->flags) &&
8576 test_bit(Faulty, &rdev->flags) &&
8577 atomic_read(&rdev->nr_pending)==0) {
8578 /* Faulty non-Blocked devices with nr_pending == 0
8579 * never get nr_pending incremented,
8580 * never get Faulty cleared, and never get Blocked set.
8581 * So we can synchronize_rcu now rather than once per device
8583 remove_some = true;
8584 set_bit(RemoveSynchronized, &rdev->flags);
8588 if (remove_some)
8589 synchronize_rcu();
8590 rdev_for_each(rdev, mddev) {
8591 if ((this == NULL || rdev == this) &&
8592 rdev->raid_disk >= 0 &&
8593 !test_bit(Blocked, &rdev->flags) &&
8594 ((test_bit(RemoveSynchronized, &rdev->flags) ||
8595 (!test_bit(In_sync, &rdev->flags) &&
8596 !test_bit(Journal, &rdev->flags))) &&
8597 atomic_read(&rdev->nr_pending)==0)) {
8598 if (mddev->pers->hot_remove_disk(
8599 mddev, rdev) == 0) {
8600 sysfs_unlink_rdev(mddev, rdev);
8601 rdev->raid_disk = -1;
8602 removed++;
8605 if (remove_some && test_bit(RemoveSynchronized, &rdev->flags))
8606 clear_bit(RemoveSynchronized, &rdev->flags);
8609 if (removed && mddev->kobj.sd)
8610 sysfs_notify(&mddev->kobj, NULL, "degraded");
8612 if (this && removed)
8613 goto no_add;
8615 rdev_for_each(rdev, mddev) {
8616 if (this && this != rdev)
8617 continue;
8618 if (test_bit(Candidate, &rdev->flags))
8619 continue;
8620 if (rdev->raid_disk >= 0 &&
8621 !test_bit(In_sync, &rdev->flags) &&
8622 !test_bit(Journal, &rdev->flags) &&
8623 !test_bit(Faulty, &rdev->flags))
8624 spares++;
8625 if (rdev->raid_disk >= 0)
8626 continue;
8627 if (test_bit(Faulty, &rdev->flags))
8628 continue;
8629 if (!test_bit(Journal, &rdev->flags)) {
8630 if (mddev->ro &&
8631 ! (rdev->saved_raid_disk >= 0 &&
8632 !test_bit(Bitmap_sync, &rdev->flags)))
8633 continue;
8635 rdev->recovery_offset = 0;
8637 if (mddev->pers->
8638 hot_add_disk(mddev, rdev) == 0) {
8639 if (sysfs_link_rdev(mddev, rdev))
8640 /* failure here is OK */;
8641 if (!test_bit(Journal, &rdev->flags))
8642 spares++;
8643 md_new_event(mddev);
8644 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8647 no_add:
8648 if (removed)
8649 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8650 return spares;
8653 static void md_start_sync(struct work_struct *ws)
8655 struct mddev *mddev = container_of(ws, struct mddev, del_work);
8657 mddev->sync_thread = md_register_thread(md_do_sync,
8658 mddev,
8659 "resync");
8660 if (!mddev->sync_thread) {
8661 pr_warn("%s: could not start resync thread...\n",
8662 mdname(mddev));
8663 /* leave the spares where they are, it shouldn't hurt */
8664 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8665 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8666 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8667 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8668 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8669 wake_up(&resync_wait);
8670 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8671 &mddev->recovery))
8672 if (mddev->sysfs_action)
8673 sysfs_notify_dirent_safe(mddev->sysfs_action);
8674 } else
8675 md_wakeup_thread(mddev->sync_thread);
8676 sysfs_notify_dirent_safe(mddev->sysfs_action);
8677 md_new_event(mddev);
8681 * This routine is regularly called by all per-raid-array threads to
8682 * deal with generic issues like resync and super-block update.
8683 * Raid personalities that don't have a thread (linear/raid0) do not
8684 * need this as they never do any recovery or update the superblock.
8686 * It does not do any resync itself, but rather "forks" off other threads
8687 * to do that as needed.
8688 * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
8689 * "->recovery" and create a thread at ->sync_thread.
8690 * When the thread finishes it sets MD_RECOVERY_DONE
8691 * and wakeups up this thread which will reap the thread and finish up.
8692 * This thread also removes any faulty devices (with nr_pending == 0).
8694 * The overall approach is:
8695 * 1/ if the superblock needs updating, update it.
8696 * 2/ If a recovery thread is running, don't do anything else.
8697 * 3/ If recovery has finished, clean up, possibly marking spares active.
8698 * 4/ If there are any faulty devices, remove them.
8699 * 5/ If array is degraded, try to add spares devices
8700 * 6/ If array has spares or is not in-sync, start a resync thread.
8702 void md_check_recovery(struct mddev *mddev)
8704 if (mddev->suspended)
8705 return;
8707 if (mddev->bitmap)
8708 bitmap_daemon_work(mddev);
8710 if (signal_pending(current)) {
8711 if (mddev->pers->sync_request && !mddev->external) {
8712 pr_debug("md: %s in immediate safe mode\n",
8713 mdname(mddev));
8714 mddev->safemode = 2;
8716 flush_signals(current);
8719 if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
8720 return;
8721 if ( ! (
8722 (mddev->sb_flags & ~ (1<<MD_SB_CHANGE_PENDING)) ||
8723 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8724 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
8725 (mddev->external == 0 && mddev->safemode == 1) ||
8726 (mddev->safemode == 2
8727 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
8729 return;
8731 if (mddev_trylock(mddev)) {
8732 int spares = 0;
8734 if (!mddev->external && mddev->safemode == 1)
8735 mddev->safemode = 0;
8737 if (mddev->ro) {
8738 struct md_rdev *rdev;
8739 if (!mddev->external && mddev->in_sync)
8740 /* 'Blocked' flag not needed as failed devices
8741 * will be recorded if array switched to read/write.
8742 * Leaving it set will prevent the device
8743 * from being removed.
8745 rdev_for_each(rdev, mddev)
8746 clear_bit(Blocked, &rdev->flags);
8747 /* On a read-only array we can:
8748 * - remove failed devices
8749 * - add already-in_sync devices if the array itself
8750 * is in-sync.
8751 * As we only add devices that are already in-sync,
8752 * we can activate the spares immediately.
8754 remove_and_add_spares(mddev, NULL);
8755 /* There is no thread, but we need to call
8756 * ->spare_active and clear saved_raid_disk
8758 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
8759 md_reap_sync_thread(mddev);
8760 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8761 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8762 clear_bit(MD_SB_CHANGE_PENDING, &mddev->sb_flags);
8763 goto unlock;
8766 if (mddev_is_clustered(mddev)) {
8767 struct md_rdev *rdev;
8768 /* kick the device if another node issued a
8769 * remove disk.
8771 rdev_for_each(rdev, mddev) {
8772 if (test_and_clear_bit(ClusterRemove, &rdev->flags) &&
8773 rdev->raid_disk < 0)
8774 md_kick_rdev_from_array(rdev);
8778 if (!mddev->external && !mddev->in_sync) {
8779 spin_lock(&mddev->lock);
8780 set_in_sync(mddev);
8781 spin_unlock(&mddev->lock);
8784 if (mddev->sb_flags)
8785 md_update_sb(mddev, 0);
8787 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
8788 !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
8789 /* resync/recovery still happening */
8790 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8791 goto unlock;
8793 if (mddev->sync_thread) {
8794 md_reap_sync_thread(mddev);
8795 goto unlock;
8797 /* Set RUNNING before clearing NEEDED to avoid
8798 * any transients in the value of "sync_action".
8800 mddev->curr_resync_completed = 0;
8801 spin_lock(&mddev->lock);
8802 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8803 spin_unlock(&mddev->lock);
8804 /* Clear some bits that don't mean anything, but
8805 * might be left set
8807 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
8808 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8810 if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
8811 test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
8812 goto not_running;
8813 /* no recovery is running.
8814 * remove any failed drives, then
8815 * add spares if possible.
8816 * Spares are also removed and re-added, to allow
8817 * the personality to fail the re-add.
8820 if (mddev->reshape_position != MaxSector) {
8821 if (mddev->pers->check_reshape == NULL ||
8822 mddev->pers->check_reshape(mddev) != 0)
8823 /* Cannot proceed */
8824 goto not_running;
8825 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8826 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8827 } else if ((spares = remove_and_add_spares(mddev, NULL))) {
8828 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8829 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8830 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8831 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8832 } else if (mddev->recovery_cp < MaxSector) {
8833 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8834 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
8835 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
8836 /* nothing to be done ... */
8837 goto not_running;
8839 if (mddev->pers->sync_request) {
8840 if (spares) {
8841 /* We are adding a device or devices to an array
8842 * which has the bitmap stored on all devices.
8843 * So make sure all bitmap pages get written
8845 bitmap_write_all(mddev->bitmap);
8847 INIT_WORK(&mddev->del_work, md_start_sync);
8848 queue_work(md_misc_wq, &mddev->del_work);
8849 goto unlock;
8851 not_running:
8852 if (!mddev->sync_thread) {
8853 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8854 wake_up(&resync_wait);
8855 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
8856 &mddev->recovery))
8857 if (mddev->sysfs_action)
8858 sysfs_notify_dirent_safe(mddev->sysfs_action);
8860 unlock:
8861 wake_up(&mddev->sb_wait);
8862 mddev_unlock(mddev);
8863 } else if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags) && mddev->sb_flags) {
8864 /* Write superblock - thread that called mddev_suspend()
8865 * holds reconfig_mutex for us.
8867 set_bit(MD_UPDATING_SB, &mddev->flags);
8868 smp_mb__after_atomic();
8869 if (test_bit(MD_ALLOW_SB_UPDATE, &mddev->flags))
8870 md_update_sb(mddev, 0);
8871 clear_bit_unlock(MD_UPDATING_SB, &mddev->flags);
8872 wake_up(&mddev->sb_wait);
8875 EXPORT_SYMBOL(md_check_recovery);
8877 void md_reap_sync_thread(struct mddev *mddev)
8879 struct md_rdev *rdev;
8881 /* resync has finished, collect result */
8882 md_unregister_thread(&mddev->sync_thread);
8883 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
8884 !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
8885 /* success...*/
8886 /* activate any spares */
8887 if (mddev->pers->spare_active(mddev)) {
8888 sysfs_notify(&mddev->kobj, NULL,
8889 "degraded");
8890 set_bit(MD_SB_CHANGE_DEVS, &mddev->sb_flags);
8893 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
8894 mddev->pers->finish_reshape)
8895 mddev->pers->finish_reshape(mddev);
8897 /* If array is no-longer degraded, then any saved_raid_disk
8898 * information must be scrapped.
8900 if (!mddev->degraded)
8901 rdev_for_each(rdev, mddev)
8902 rdev->saved_raid_disk = -1;
8904 md_update_sb(mddev, 1);
8905 /* MD_SB_CHANGE_PENDING should be cleared by md_update_sb, so we can
8906 * call resync_finish here if MD_CLUSTER_RESYNC_LOCKED is set by
8907 * clustered raid */
8908 if (test_and_clear_bit(MD_CLUSTER_RESYNC_LOCKED, &mddev->flags))
8909 md_cluster_ops->resync_finish(mddev);
8910 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
8911 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
8912 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
8913 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
8914 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
8915 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
8916 wake_up(&resync_wait);
8917 /* flag recovery needed just to double check */
8918 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
8919 sysfs_notify_dirent_safe(mddev->sysfs_action);
8920 md_new_event(mddev);
8921 if (mddev->event_work.func)
8922 queue_work(md_misc_wq, &mddev->event_work);
8924 EXPORT_SYMBOL(md_reap_sync_thread);
8926 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
8928 sysfs_notify_dirent_safe(rdev->sysfs_state);
8929 wait_event_timeout(rdev->blocked_wait,
8930 !test_bit(Blocked, &rdev->flags) &&
8931 !test_bit(BlockedBadBlocks, &rdev->flags),
8932 msecs_to_jiffies(5000));
8933 rdev_dec_pending(rdev, mddev);
8935 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
8937 void md_finish_reshape(struct mddev *mddev)
8939 /* called be personality module when reshape completes. */
8940 struct md_rdev *rdev;
8942 rdev_for_each(rdev, mddev) {
8943 if (rdev->data_offset > rdev->new_data_offset)
8944 rdev->sectors += rdev->data_offset - rdev->new_data_offset;
8945 else
8946 rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
8947 rdev->data_offset = rdev->new_data_offset;
8950 EXPORT_SYMBOL(md_finish_reshape);
8952 /* Bad block management */
8954 /* Returns 1 on success, 0 on failure */
8955 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8956 int is_new)
8958 struct mddev *mddev = rdev->mddev;
8959 int rv;
8960 if (is_new)
8961 s += rdev->new_data_offset;
8962 else
8963 s += rdev->data_offset;
8964 rv = badblocks_set(&rdev->badblocks, s, sectors, 0);
8965 if (rv == 0) {
8966 /* Make sure they get written out promptly */
8967 if (test_bit(ExternalBbl, &rdev->flags))
8968 sysfs_notify(&rdev->kobj, NULL,
8969 "unacknowledged_bad_blocks");
8970 sysfs_notify_dirent_safe(rdev->sysfs_state);
8971 set_mask_bits(&mddev->sb_flags, 0,
8972 BIT(MD_SB_CHANGE_CLEAN) | BIT(MD_SB_CHANGE_PENDING));
8973 md_wakeup_thread(rdev->mddev->thread);
8974 return 1;
8975 } else
8976 return 0;
8978 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
8980 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8981 int is_new)
8983 int rv;
8984 if (is_new)
8985 s += rdev->new_data_offset;
8986 else
8987 s += rdev->data_offset;
8988 rv = badblocks_clear(&rdev->badblocks, s, sectors);
8989 if ((rv == 0) && test_bit(ExternalBbl, &rdev->flags))
8990 sysfs_notify(&rdev->kobj, NULL, "bad_blocks");
8991 return rv;
8993 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
8995 static int md_notify_reboot(struct notifier_block *this,
8996 unsigned long code, void *x)
8998 struct list_head *tmp;
8999 struct mddev *mddev;
9000 int need_delay = 0;
9002 for_each_mddev(mddev, tmp) {
9003 if (mddev_trylock(mddev)) {
9004 if (mddev->pers)
9005 __md_stop_writes(mddev);
9006 if (mddev->persistent)
9007 mddev->safemode = 2;
9008 mddev_unlock(mddev);
9010 need_delay = 1;
9013 * certain more exotic SCSI devices are known to be
9014 * volatile wrt too early system reboots. While the
9015 * right place to handle this issue is the given
9016 * driver, we do want to have a safe RAID driver ...
9018 if (need_delay)
9019 mdelay(1000*1);
9021 return NOTIFY_DONE;
9024 static struct notifier_block md_notifier = {
9025 .notifier_call = md_notify_reboot,
9026 .next = NULL,
9027 .priority = INT_MAX, /* before any real devices */
9030 static void md_geninit(void)
9032 pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
9034 proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
9037 static int __init md_init(void)
9039 int ret = -ENOMEM;
9041 md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
9042 if (!md_wq)
9043 goto err_wq;
9045 md_misc_wq = alloc_workqueue("md_misc", 0, 0);
9046 if (!md_misc_wq)
9047 goto err_misc_wq;
9049 if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
9050 goto err_md;
9052 if ((ret = register_blkdev(0, "mdp")) < 0)
9053 goto err_mdp;
9054 mdp_major = ret;
9056 blk_register_region(MKDEV(MD_MAJOR, 0), 512, THIS_MODULE,
9057 md_probe, NULL, NULL);
9058 blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
9059 md_probe, NULL, NULL);
9061 register_reboot_notifier(&md_notifier);
9062 raid_table_header = register_sysctl_table(raid_root_table);
9064 md_geninit();
9065 return 0;
9067 err_mdp:
9068 unregister_blkdev(MD_MAJOR, "md");
9069 err_md:
9070 destroy_workqueue(md_misc_wq);
9071 err_misc_wq:
9072 destroy_workqueue(md_wq);
9073 err_wq:
9074 return ret;
9077 static void check_sb_changes(struct mddev *mddev, struct md_rdev *rdev)
9079 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
9080 struct md_rdev *rdev2;
9081 int role, ret;
9082 char b[BDEVNAME_SIZE];
9085 * If size is changed in another node then we need to
9086 * do resize as well.
9088 if (mddev->dev_sectors != le64_to_cpu(sb->size)) {
9089 ret = mddev->pers->resize(mddev, le64_to_cpu(sb->size));
9090 if (ret)
9091 pr_info("md-cluster: resize failed\n");
9092 else
9093 bitmap_update_sb(mddev->bitmap);
9096 /* Check for change of roles in the active devices */
9097 rdev_for_each(rdev2, mddev) {
9098 if (test_bit(Faulty, &rdev2->flags))
9099 continue;
9101 /* Check if the roles changed */
9102 role = le16_to_cpu(sb->dev_roles[rdev2->desc_nr]);
9104 if (test_bit(Candidate, &rdev2->flags)) {
9105 if (role == 0xfffe) {
9106 pr_info("md: Removing Candidate device %s because add failed\n", bdevname(rdev2->bdev,b));
9107 md_kick_rdev_from_array(rdev2);
9108 continue;
9110 else
9111 clear_bit(Candidate, &rdev2->flags);
9114 if (role != rdev2->raid_disk) {
9115 /* got activated */
9116 if (rdev2->raid_disk == -1 && role != 0xffff) {
9117 rdev2->saved_raid_disk = role;
9118 ret = remove_and_add_spares(mddev, rdev2);
9119 pr_info("Activated spare: %s\n",
9120 bdevname(rdev2->bdev,b));
9121 /* wakeup mddev->thread here, so array could
9122 * perform resync with the new activated disk */
9123 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
9124 md_wakeup_thread(mddev->thread);
9127 /* device faulty
9128 * We just want to do the minimum to mark the disk
9129 * as faulty. The recovery is performed by the
9130 * one who initiated the error.
9132 if ((role == 0xfffe) || (role == 0xfffd)) {
9133 md_error(mddev, rdev2);
9134 clear_bit(Blocked, &rdev2->flags);
9139 if (mddev->raid_disks != le32_to_cpu(sb->raid_disks))
9140 update_raid_disks(mddev, le32_to_cpu(sb->raid_disks));
9142 /* Finally set the event to be up to date */
9143 mddev->events = le64_to_cpu(sb->events);
9146 static int read_rdev(struct mddev *mddev, struct md_rdev *rdev)
9148 int err;
9149 struct page *swapout = rdev->sb_page;
9150 struct mdp_superblock_1 *sb;
9152 /* Store the sb page of the rdev in the swapout temporary
9153 * variable in case we err in the future
9155 rdev->sb_page = NULL;
9156 err = alloc_disk_sb(rdev);
9157 if (err == 0) {
9158 ClearPageUptodate(rdev->sb_page);
9159 rdev->sb_loaded = 0;
9160 err = super_types[mddev->major_version].
9161 load_super(rdev, NULL, mddev->minor_version);
9163 if (err < 0) {
9164 pr_warn("%s: %d Could not reload rdev(%d) err: %d. Restoring old values\n",
9165 __func__, __LINE__, rdev->desc_nr, err);
9166 if (rdev->sb_page)
9167 put_page(rdev->sb_page);
9168 rdev->sb_page = swapout;
9169 rdev->sb_loaded = 1;
9170 return err;
9173 sb = page_address(rdev->sb_page);
9174 /* Read the offset unconditionally, even if MD_FEATURE_RECOVERY_OFFSET
9175 * is not set
9178 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RECOVERY_OFFSET))
9179 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
9181 /* The other node finished recovery, call spare_active to set
9182 * device In_sync and mddev->degraded
9184 if (rdev->recovery_offset == MaxSector &&
9185 !test_bit(In_sync, &rdev->flags) &&
9186 mddev->pers->spare_active(mddev))
9187 sysfs_notify(&mddev->kobj, NULL, "degraded");
9189 put_page(swapout);
9190 return 0;
9193 void md_reload_sb(struct mddev *mddev, int nr)
9195 struct md_rdev *rdev;
9196 int err;
9198 /* Find the rdev */
9199 rdev_for_each_rcu(rdev, mddev) {
9200 if (rdev->desc_nr == nr)
9201 break;
9204 if (!rdev || rdev->desc_nr != nr) {
9205 pr_warn("%s: %d Could not find rdev with nr %d\n", __func__, __LINE__, nr);
9206 return;
9209 err = read_rdev(mddev, rdev);
9210 if (err < 0)
9211 return;
9213 check_sb_changes(mddev, rdev);
9215 /* Read all rdev's to update recovery_offset */
9216 rdev_for_each_rcu(rdev, mddev)
9217 read_rdev(mddev, rdev);
9219 EXPORT_SYMBOL(md_reload_sb);
9221 #ifndef MODULE
9224 * Searches all registered partitions for autorun RAID arrays
9225 * at boot time.
9228 static DEFINE_MUTEX(detected_devices_mutex);
9229 static LIST_HEAD(all_detected_devices);
9230 struct detected_devices_node {
9231 struct list_head list;
9232 dev_t dev;
9235 void md_autodetect_dev(dev_t dev)
9237 struct detected_devices_node *node_detected_dev;
9239 node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
9240 if (node_detected_dev) {
9241 node_detected_dev->dev = dev;
9242 mutex_lock(&detected_devices_mutex);
9243 list_add_tail(&node_detected_dev->list, &all_detected_devices);
9244 mutex_unlock(&detected_devices_mutex);
9248 static void autostart_arrays(int part)
9250 struct md_rdev *rdev;
9251 struct detected_devices_node *node_detected_dev;
9252 dev_t dev;
9253 int i_scanned, i_passed;
9255 i_scanned = 0;
9256 i_passed = 0;
9258 pr_info("md: Autodetecting RAID arrays.\n");
9260 mutex_lock(&detected_devices_mutex);
9261 while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
9262 i_scanned++;
9263 node_detected_dev = list_entry(all_detected_devices.next,
9264 struct detected_devices_node, list);
9265 list_del(&node_detected_dev->list);
9266 dev = node_detected_dev->dev;
9267 kfree(node_detected_dev);
9268 mutex_unlock(&detected_devices_mutex);
9269 rdev = md_import_device(dev,0, 90);
9270 mutex_lock(&detected_devices_mutex);
9271 if (IS_ERR(rdev))
9272 continue;
9274 if (test_bit(Faulty, &rdev->flags))
9275 continue;
9277 set_bit(AutoDetected, &rdev->flags);
9278 list_add(&rdev->same_set, &pending_raid_disks);
9279 i_passed++;
9281 mutex_unlock(&detected_devices_mutex);
9283 pr_debug("md: Scanned %d and added %d devices.\n", i_scanned, i_passed);
9285 autorun_devices(part);
9288 #endif /* !MODULE */
9290 static __exit void md_exit(void)
9292 struct mddev *mddev;
9293 struct list_head *tmp;
9294 int delay = 1;
9296 blk_unregister_region(MKDEV(MD_MAJOR,0), 512);
9297 blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
9299 unregister_blkdev(MD_MAJOR,"md");
9300 unregister_blkdev(mdp_major, "mdp");
9301 unregister_reboot_notifier(&md_notifier);
9302 unregister_sysctl_table(raid_table_header);
9304 /* We cannot unload the modules while some process is
9305 * waiting for us in select() or poll() - wake them up
9307 md_unloading = 1;
9308 while (waitqueue_active(&md_event_waiters)) {
9309 /* not safe to leave yet */
9310 wake_up(&md_event_waiters);
9311 msleep(delay);
9312 delay += delay;
9314 remove_proc_entry("mdstat", NULL);
9316 for_each_mddev(mddev, tmp) {
9317 export_array(mddev);
9318 mddev->ctime = 0;
9319 mddev->hold_active = 0;
9321 * for_each_mddev() will call mddev_put() at the end of each
9322 * iteration. As the mddev is now fully clear, this will
9323 * schedule the mddev for destruction by a workqueue, and the
9324 * destroy_workqueue() below will wait for that to complete.
9327 destroy_workqueue(md_misc_wq);
9328 destroy_workqueue(md_wq);
9331 subsys_initcall(md_init);
9332 module_exit(md_exit)
9334 static int get_ro(char *buffer, const struct kernel_param *kp)
9336 return sprintf(buffer, "%d", start_readonly);
9338 static int set_ro(const char *val, const struct kernel_param *kp)
9340 return kstrtouint(val, 10, (unsigned int *)&start_readonly);
9343 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
9344 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
9345 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
9346 module_param(create_on_open, bool, S_IRUSR|S_IWUSR);
9348 MODULE_LICENSE("GPL");
9349 MODULE_DESCRIPTION("MD RAID framework");
9350 MODULE_ALIAS("md");
9351 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);