team: Replace rcu_read_lock with a mutex in team_vlan_rx_kill_vid
[linux/fpc-iii.git] / drivers / md / md.c
blob7c45286e2662697a91ab3f3f2075080700826443
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.
35 #include <linux/kthread.h>
36 #include <linux/blkdev.h>
37 #include <linux/sysctl.h>
38 #include <linux/seq_file.h>
39 #include <linux/fs.h>
40 #include <linux/poll.h>
41 #include <linux/ctype.h>
42 #include <linux/string.h>
43 #include <linux/hdreg.h>
44 #include <linux/proc_fs.h>
45 #include <linux/random.h>
46 #include <linux/module.h>
47 #include <linux/reboot.h>
48 #include <linux/file.h>
49 #include <linux/compat.h>
50 #include <linux/delay.h>
51 #include <linux/raid/md_p.h>
52 #include <linux/raid/md_u.h>
53 #include <linux/slab.h>
54 #include "md.h"
55 #include "bitmap.h"
57 #ifndef MODULE
58 static void autostart_arrays(int part);
59 #endif
61 /* pers_list is a list of registered personalities protected
62 * by pers_lock.
63 * pers_lock does extra service to protect accesses to
64 * mddev->thread when the mutex cannot be held.
66 static LIST_HEAD(pers_list);
67 static DEFINE_SPINLOCK(pers_lock);
69 static void md_print_devices(void);
71 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
72 static struct workqueue_struct *md_wq;
73 static struct workqueue_struct *md_misc_wq;
75 static int remove_and_add_spares(struct mddev *mddev,
76 struct md_rdev *this);
78 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
81 * Default number of read corrections we'll attempt on an rdev
82 * before ejecting it from the array. We divide the read error
83 * count by 2 for every hour elapsed between read errors.
85 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
87 * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
88 * is 1000 KB/sec, so the extra system load does not show up that much.
89 * Increase it if you want to have more _guaranteed_ speed. Note that
90 * the RAID driver will use the maximum available bandwidth if the IO
91 * subsystem is idle. There is also an 'absolute maximum' reconstruction
92 * speed limit - in case reconstruction slows down your system despite
93 * idle IO detection.
95 * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
96 * or /sys/block/mdX/md/sync_speed_{min,max}
99 static int sysctl_speed_limit_min = 1000;
100 static int sysctl_speed_limit_max = 200000;
101 static inline int speed_min(struct mddev *mddev)
103 return mddev->sync_speed_min ?
104 mddev->sync_speed_min : sysctl_speed_limit_min;
107 static inline int speed_max(struct mddev *mddev)
109 return mddev->sync_speed_max ?
110 mddev->sync_speed_max : sysctl_speed_limit_max;
113 static struct ctl_table_header *raid_table_header;
115 static ctl_table raid_table[] = {
117 .procname = "speed_limit_min",
118 .data = &sysctl_speed_limit_min,
119 .maxlen = sizeof(int),
120 .mode = S_IRUGO|S_IWUSR,
121 .proc_handler = proc_dointvec,
124 .procname = "speed_limit_max",
125 .data = &sysctl_speed_limit_max,
126 .maxlen = sizeof(int),
127 .mode = S_IRUGO|S_IWUSR,
128 .proc_handler = proc_dointvec,
133 static ctl_table raid_dir_table[] = {
135 .procname = "raid",
136 .maxlen = 0,
137 .mode = S_IRUGO|S_IXUGO,
138 .child = raid_table,
143 static ctl_table raid_root_table[] = {
145 .procname = "dev",
146 .maxlen = 0,
147 .mode = 0555,
148 .child = raid_dir_table,
153 static const struct block_device_operations md_fops;
155 static int start_readonly;
157 /* bio_clone_mddev
158 * like bio_clone, but with a local bio set
161 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
162 struct mddev *mddev)
164 struct bio *b;
166 if (!mddev || !mddev->bio_set)
167 return bio_alloc(gfp_mask, nr_iovecs);
169 b = bio_alloc_bioset(gfp_mask, nr_iovecs, mddev->bio_set);
170 if (!b)
171 return NULL;
172 return b;
174 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
176 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
177 struct mddev *mddev)
179 if (!mddev || !mddev->bio_set)
180 return bio_clone(bio, gfp_mask);
182 return bio_clone_bioset(bio, gfp_mask, mddev->bio_set);
184 EXPORT_SYMBOL_GPL(bio_clone_mddev);
186 void md_trim_bio(struct bio *bio, int offset, int size)
188 /* 'bio' is a cloned bio which we need to trim to match
189 * the given offset and size.
190 * This requires adjusting bi_sector, bi_size, and bi_io_vec
192 int i;
193 struct bio_vec *bvec;
194 int sofar = 0;
196 size <<= 9;
197 if (offset == 0 && size == bio->bi_size)
198 return;
200 clear_bit(BIO_SEG_VALID, &bio->bi_flags);
202 bio_advance(bio, offset << 9);
204 bio->bi_size = size;
206 /* avoid any complications with bi_idx being non-zero*/
207 if (bio->bi_idx) {
208 memmove(bio->bi_io_vec, bio->bi_io_vec+bio->bi_idx,
209 (bio->bi_vcnt - bio->bi_idx) * sizeof(struct bio_vec));
210 bio->bi_vcnt -= bio->bi_idx;
211 bio->bi_idx = 0;
213 /* Make sure vcnt and last bv are not too big */
214 bio_for_each_segment(bvec, bio, i) {
215 if (sofar + bvec->bv_len > size)
216 bvec->bv_len = size - sofar;
217 if (bvec->bv_len == 0) {
218 bio->bi_vcnt = i;
219 break;
221 sofar += bvec->bv_len;
224 EXPORT_SYMBOL_GPL(md_trim_bio);
227 * We have a system wide 'event count' that is incremented
228 * on any 'interesting' event, and readers of /proc/mdstat
229 * can use 'poll' or 'select' to find out when the event
230 * count increases.
232 * Events are:
233 * start array, stop array, error, add device, remove device,
234 * start build, activate spare
236 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
237 static atomic_t md_event_count;
238 void md_new_event(struct mddev *mddev)
240 atomic_inc(&md_event_count);
241 wake_up(&md_event_waiters);
243 EXPORT_SYMBOL_GPL(md_new_event);
245 /* Alternate version that can be called from interrupts
246 * when calling sysfs_notify isn't needed.
248 static void md_new_event_inintr(struct mddev *mddev)
250 atomic_inc(&md_event_count);
251 wake_up(&md_event_waiters);
255 * Enables to iterate over all existing md arrays
256 * all_mddevs_lock protects this list.
258 static LIST_HEAD(all_mddevs);
259 static DEFINE_SPINLOCK(all_mddevs_lock);
263 * iterates through all used mddevs in the system.
264 * We take care to grab the all_mddevs_lock whenever navigating
265 * the list, and to always hold a refcount when unlocked.
266 * Any code which breaks out of this loop while own
267 * a reference to the current mddev and must mddev_put it.
269 #define for_each_mddev(_mddev,_tmp) \
271 for (({ spin_lock(&all_mddevs_lock); \
272 _tmp = all_mddevs.next; \
273 _mddev = NULL;}); \
274 ({ if (_tmp != &all_mddevs) \
275 mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
276 spin_unlock(&all_mddevs_lock); \
277 if (_mddev) mddev_put(_mddev); \
278 _mddev = list_entry(_tmp, struct mddev, all_mddevs); \
279 _tmp != &all_mddevs;}); \
280 ({ spin_lock(&all_mddevs_lock); \
281 _tmp = _tmp->next;}) \
285 /* Rather than calling directly into the personality make_request function,
286 * IO requests come here first so that we can check if the device is
287 * being suspended pending a reconfiguration.
288 * We hold a refcount over the call to ->make_request. By the time that
289 * call has finished, the bio has been linked into some internal structure
290 * and so is visible to ->quiesce(), so we don't need the refcount any more.
292 static void md_make_request(struct request_queue *q, struct bio *bio)
294 const int rw = bio_data_dir(bio);
295 struct mddev *mddev = q->queuedata;
296 int cpu;
297 unsigned int sectors;
299 if (mddev == NULL || mddev->pers == NULL
300 || !mddev->ready) {
301 bio_io_error(bio);
302 return;
304 if (mddev->ro == 1 && unlikely(rw == WRITE)) {
305 bio_endio(bio, bio_sectors(bio) == 0 ? 0 : -EROFS);
306 return;
308 smp_rmb(); /* Ensure implications of 'active' are visible */
309 rcu_read_lock();
310 if (mddev->suspended) {
311 DEFINE_WAIT(__wait);
312 for (;;) {
313 prepare_to_wait(&mddev->sb_wait, &__wait,
314 TASK_UNINTERRUPTIBLE);
315 if (!mddev->suspended)
316 break;
317 rcu_read_unlock();
318 schedule();
319 rcu_read_lock();
321 finish_wait(&mddev->sb_wait, &__wait);
323 atomic_inc(&mddev->active_io);
324 rcu_read_unlock();
327 * save the sectors now since our bio can
328 * go away inside make_request
330 sectors = bio_sectors(bio);
331 mddev->pers->make_request(mddev, bio);
333 cpu = part_stat_lock();
334 part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
335 part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
336 part_stat_unlock();
338 if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
339 wake_up(&mddev->sb_wait);
342 /* mddev_suspend makes sure no new requests are submitted
343 * to the device, and that any requests that have been submitted
344 * are completely handled.
345 * Once ->stop is called and completes, the module will be completely
346 * unused.
348 void mddev_suspend(struct mddev *mddev)
350 BUG_ON(mddev->suspended);
351 mddev->suspended = 1;
352 synchronize_rcu();
353 wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
354 mddev->pers->quiesce(mddev, 1);
356 del_timer_sync(&mddev->safemode_timer);
358 EXPORT_SYMBOL_GPL(mddev_suspend);
360 void mddev_resume(struct mddev *mddev)
362 mddev->suspended = 0;
363 wake_up(&mddev->sb_wait);
364 mddev->pers->quiesce(mddev, 0);
366 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
367 md_wakeup_thread(mddev->thread);
368 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
370 EXPORT_SYMBOL_GPL(mddev_resume);
372 int mddev_congested(struct mddev *mddev, int bits)
374 return mddev->suspended;
376 EXPORT_SYMBOL(mddev_congested);
379 * Generic flush handling for md
382 static void md_end_flush(struct bio *bio, int err)
384 struct md_rdev *rdev = bio->bi_private;
385 struct mddev *mddev = rdev->mddev;
387 rdev_dec_pending(rdev, mddev);
389 if (atomic_dec_and_test(&mddev->flush_pending)) {
390 /* The pre-request flush has finished */
391 queue_work(md_wq, &mddev->flush_work);
393 bio_put(bio);
396 static void md_submit_flush_data(struct work_struct *ws);
398 static void submit_flushes(struct work_struct *ws)
400 struct mddev *mddev = container_of(ws, struct mddev, flush_work);
401 struct md_rdev *rdev;
403 INIT_WORK(&mddev->flush_work, md_submit_flush_data);
404 atomic_set(&mddev->flush_pending, 1);
405 rcu_read_lock();
406 rdev_for_each_rcu(rdev, mddev)
407 if (rdev->raid_disk >= 0 &&
408 !test_bit(Faulty, &rdev->flags)) {
409 /* Take two references, one is dropped
410 * when request finishes, one after
411 * we reclaim rcu_read_lock
413 struct bio *bi;
414 atomic_inc(&rdev->nr_pending);
415 atomic_inc(&rdev->nr_pending);
416 rcu_read_unlock();
417 bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
418 bi->bi_end_io = md_end_flush;
419 bi->bi_private = rdev;
420 bi->bi_bdev = rdev->bdev;
421 atomic_inc(&mddev->flush_pending);
422 submit_bio(WRITE_FLUSH, bi);
423 rcu_read_lock();
424 rdev_dec_pending(rdev, mddev);
426 rcu_read_unlock();
427 if (atomic_dec_and_test(&mddev->flush_pending))
428 queue_work(md_wq, &mddev->flush_work);
431 static void md_submit_flush_data(struct work_struct *ws)
433 struct mddev *mddev = container_of(ws, struct mddev, flush_work);
434 struct bio *bio = mddev->flush_bio;
436 if (bio->bi_size == 0)
437 /* an empty barrier - all done */
438 bio_endio(bio, 0);
439 else {
440 bio->bi_rw &= ~REQ_FLUSH;
441 mddev->pers->make_request(mddev, bio);
444 mddev->flush_bio = NULL;
445 wake_up(&mddev->sb_wait);
448 void md_flush_request(struct mddev *mddev, struct bio *bio)
450 spin_lock_irq(&mddev->write_lock);
451 wait_event_lock_irq(mddev->sb_wait,
452 !mddev->flush_bio,
453 mddev->write_lock);
454 mddev->flush_bio = bio;
455 spin_unlock_irq(&mddev->write_lock);
457 INIT_WORK(&mddev->flush_work, submit_flushes);
458 queue_work(md_wq, &mddev->flush_work);
460 EXPORT_SYMBOL(md_flush_request);
462 void md_unplug(struct blk_plug_cb *cb, bool from_schedule)
464 struct mddev *mddev = cb->data;
465 md_wakeup_thread(mddev->thread);
466 kfree(cb);
468 EXPORT_SYMBOL(md_unplug);
470 static inline struct mddev *mddev_get(struct mddev *mddev)
472 atomic_inc(&mddev->active);
473 return mddev;
476 static void mddev_delayed_delete(struct work_struct *ws);
478 static void mddev_put(struct mddev *mddev)
480 struct bio_set *bs = NULL;
482 if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
483 return;
484 if (!mddev->raid_disks && list_empty(&mddev->disks) &&
485 mddev->ctime == 0 && !mddev->hold_active) {
486 /* Array is not configured at all, and not held active,
487 * so destroy it */
488 list_del_init(&mddev->all_mddevs);
489 bs = mddev->bio_set;
490 mddev->bio_set = NULL;
491 if (mddev->gendisk) {
492 /* We did a probe so need to clean up. Call
493 * queue_work inside the spinlock so that
494 * flush_workqueue() after mddev_find will
495 * succeed in waiting for the work to be done.
497 INIT_WORK(&mddev->del_work, mddev_delayed_delete);
498 queue_work(md_misc_wq, &mddev->del_work);
499 } else
500 kfree(mddev);
502 spin_unlock(&all_mddevs_lock);
503 if (bs)
504 bioset_free(bs);
507 void mddev_init(struct mddev *mddev)
509 mutex_init(&mddev->open_mutex);
510 mutex_init(&mddev->reconfig_mutex);
511 mutex_init(&mddev->bitmap_info.mutex);
512 INIT_LIST_HEAD(&mddev->disks);
513 INIT_LIST_HEAD(&mddev->all_mddevs);
514 init_timer(&mddev->safemode_timer);
515 atomic_set(&mddev->active, 1);
516 atomic_set(&mddev->openers, 0);
517 atomic_set(&mddev->active_io, 0);
518 spin_lock_init(&mddev->write_lock);
519 atomic_set(&mddev->flush_pending, 0);
520 init_waitqueue_head(&mddev->sb_wait);
521 init_waitqueue_head(&mddev->recovery_wait);
522 mddev->reshape_position = MaxSector;
523 mddev->reshape_backwards = 0;
524 mddev->resync_min = 0;
525 mddev->resync_max = MaxSector;
526 mddev->level = LEVEL_NONE;
528 EXPORT_SYMBOL_GPL(mddev_init);
530 static struct mddev * mddev_find(dev_t unit)
532 struct mddev *mddev, *new = NULL;
534 if (unit && MAJOR(unit) != MD_MAJOR)
535 unit &= ~((1<<MdpMinorShift)-1);
537 retry:
538 spin_lock(&all_mddevs_lock);
540 if (unit) {
541 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
542 if (mddev->unit == unit) {
543 mddev_get(mddev);
544 spin_unlock(&all_mddevs_lock);
545 kfree(new);
546 return mddev;
549 if (new) {
550 list_add(&new->all_mddevs, &all_mddevs);
551 spin_unlock(&all_mddevs_lock);
552 new->hold_active = UNTIL_IOCTL;
553 return new;
555 } else if (new) {
556 /* find an unused unit number */
557 static int next_minor = 512;
558 int start = next_minor;
559 int is_free = 0;
560 int dev = 0;
561 while (!is_free) {
562 dev = MKDEV(MD_MAJOR, next_minor);
563 next_minor++;
564 if (next_minor > MINORMASK)
565 next_minor = 0;
566 if (next_minor == start) {
567 /* Oh dear, all in use. */
568 spin_unlock(&all_mddevs_lock);
569 kfree(new);
570 return NULL;
573 is_free = 1;
574 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
575 if (mddev->unit == dev) {
576 is_free = 0;
577 break;
580 new->unit = dev;
581 new->md_minor = MINOR(dev);
582 new->hold_active = UNTIL_STOP;
583 list_add(&new->all_mddevs, &all_mddevs);
584 spin_unlock(&all_mddevs_lock);
585 return new;
587 spin_unlock(&all_mddevs_lock);
589 new = kzalloc(sizeof(*new), GFP_KERNEL);
590 if (!new)
591 return NULL;
593 new->unit = unit;
594 if (MAJOR(unit) == MD_MAJOR)
595 new->md_minor = MINOR(unit);
596 else
597 new->md_minor = MINOR(unit) >> MdpMinorShift;
599 mddev_init(new);
601 goto retry;
604 static inline int mddev_lock(struct mddev * mddev)
606 return mutex_lock_interruptible(&mddev->reconfig_mutex);
609 static inline int mddev_is_locked(struct mddev *mddev)
611 return mutex_is_locked(&mddev->reconfig_mutex);
614 static inline int mddev_trylock(struct mddev * mddev)
616 return mutex_trylock(&mddev->reconfig_mutex);
619 static struct attribute_group md_redundancy_group;
621 static void mddev_unlock(struct mddev * mddev)
623 if (mddev->to_remove) {
624 /* These cannot be removed under reconfig_mutex as
625 * an access to the files will try to take reconfig_mutex
626 * while holding the file unremovable, which leads to
627 * a deadlock.
628 * So hold set sysfs_active while the remove in happeing,
629 * and anything else which might set ->to_remove or my
630 * otherwise change the sysfs namespace will fail with
631 * -EBUSY if sysfs_active is still set.
632 * We set sysfs_active under reconfig_mutex and elsewhere
633 * test it under the same mutex to ensure its correct value
634 * is seen.
636 struct attribute_group *to_remove = mddev->to_remove;
637 mddev->to_remove = NULL;
638 mddev->sysfs_active = 1;
639 mutex_unlock(&mddev->reconfig_mutex);
641 if (mddev->kobj.sd) {
642 if (to_remove != &md_redundancy_group)
643 sysfs_remove_group(&mddev->kobj, to_remove);
644 if (mddev->pers == NULL ||
645 mddev->pers->sync_request == NULL) {
646 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
647 if (mddev->sysfs_action)
648 sysfs_put(mddev->sysfs_action);
649 mddev->sysfs_action = NULL;
652 mddev->sysfs_active = 0;
653 } else
654 mutex_unlock(&mddev->reconfig_mutex);
656 /* As we've dropped the mutex we need a spinlock to
657 * make sure the thread doesn't disappear
659 spin_lock(&pers_lock);
660 md_wakeup_thread(mddev->thread);
661 spin_unlock(&pers_lock);
664 static struct md_rdev * find_rdev_nr(struct mddev *mddev, int nr)
666 struct md_rdev *rdev;
668 rdev_for_each(rdev, mddev)
669 if (rdev->desc_nr == nr)
670 return rdev;
672 return NULL;
675 static struct md_rdev *find_rdev_nr_rcu(struct mddev *mddev, int nr)
677 struct md_rdev *rdev;
679 rdev_for_each_rcu(rdev, mddev)
680 if (rdev->desc_nr == nr)
681 return rdev;
683 return NULL;
686 static struct md_rdev *find_rdev(struct mddev *mddev, dev_t dev)
688 struct md_rdev *rdev;
690 rdev_for_each(rdev, mddev)
691 if (rdev->bdev->bd_dev == dev)
692 return rdev;
694 return NULL;
697 static struct md_rdev *find_rdev_rcu(struct mddev *mddev, dev_t dev)
699 struct md_rdev *rdev;
701 rdev_for_each_rcu(rdev, mddev)
702 if (rdev->bdev->bd_dev == dev)
703 return rdev;
705 return NULL;
708 static struct md_personality *find_pers(int level, char *clevel)
710 struct md_personality *pers;
711 list_for_each_entry(pers, &pers_list, list) {
712 if (level != LEVEL_NONE && pers->level == level)
713 return pers;
714 if (strcmp(pers->name, clevel)==0)
715 return pers;
717 return NULL;
720 /* return the offset of the super block in 512byte sectors */
721 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
723 sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
724 return MD_NEW_SIZE_SECTORS(num_sectors);
727 static int alloc_disk_sb(struct md_rdev * rdev)
729 if (rdev->sb_page)
730 MD_BUG();
732 rdev->sb_page = alloc_page(GFP_KERNEL);
733 if (!rdev->sb_page) {
734 printk(KERN_ALERT "md: out of memory.\n");
735 return -ENOMEM;
738 return 0;
741 void md_rdev_clear(struct md_rdev *rdev)
743 if (rdev->sb_page) {
744 put_page(rdev->sb_page);
745 rdev->sb_loaded = 0;
746 rdev->sb_page = NULL;
747 rdev->sb_start = 0;
748 rdev->sectors = 0;
750 if (rdev->bb_page) {
751 put_page(rdev->bb_page);
752 rdev->bb_page = NULL;
754 kfree(rdev->badblocks.page);
755 rdev->badblocks.page = NULL;
757 EXPORT_SYMBOL_GPL(md_rdev_clear);
759 static void super_written(struct bio *bio, int error)
761 struct md_rdev *rdev = bio->bi_private;
762 struct mddev *mddev = rdev->mddev;
764 if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
765 printk("md: super_written gets error=%d, uptodate=%d\n",
766 error, test_bit(BIO_UPTODATE, &bio->bi_flags));
767 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
768 md_error(mddev, rdev);
771 if (atomic_dec_and_test(&mddev->pending_writes))
772 wake_up(&mddev->sb_wait);
773 bio_put(bio);
776 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
777 sector_t sector, int size, struct page *page)
779 /* write first size bytes of page to sector of rdev
780 * Increment mddev->pending_writes before returning
781 * and decrement it on completion, waking up sb_wait
782 * if zero is reached.
783 * If an error occurred, call md_error
785 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
787 bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
788 bio->bi_sector = sector;
789 bio_add_page(bio, page, size, 0);
790 bio->bi_private = rdev;
791 bio->bi_end_io = super_written;
793 atomic_inc(&mddev->pending_writes);
794 submit_bio(WRITE_FLUSH_FUA, bio);
797 void md_super_wait(struct mddev *mddev)
799 /* wait for all superblock writes that were scheduled to complete */
800 DEFINE_WAIT(wq);
801 for(;;) {
802 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
803 if (atomic_read(&mddev->pending_writes)==0)
804 break;
805 schedule();
807 finish_wait(&mddev->sb_wait, &wq);
810 static void bi_complete(struct bio *bio, int error)
812 complete((struct completion*)bio->bi_private);
815 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
816 struct page *page, int rw, bool metadata_op)
818 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
819 struct completion event;
820 int ret;
822 rw |= REQ_SYNC;
824 bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
825 rdev->meta_bdev : rdev->bdev;
826 if (metadata_op)
827 bio->bi_sector = sector + rdev->sb_start;
828 else if (rdev->mddev->reshape_position != MaxSector &&
829 (rdev->mddev->reshape_backwards ==
830 (sector >= rdev->mddev->reshape_position)))
831 bio->bi_sector = sector + rdev->new_data_offset;
832 else
833 bio->bi_sector = sector + rdev->data_offset;
834 bio_add_page(bio, page, size, 0);
835 init_completion(&event);
836 bio->bi_private = &event;
837 bio->bi_end_io = bi_complete;
838 submit_bio(rw, bio);
839 wait_for_completion(&event);
841 ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
842 bio_put(bio);
843 return ret;
845 EXPORT_SYMBOL_GPL(sync_page_io);
847 static int read_disk_sb(struct md_rdev * rdev, int size)
849 char b[BDEVNAME_SIZE];
850 if (!rdev->sb_page) {
851 MD_BUG();
852 return -EINVAL;
854 if (rdev->sb_loaded)
855 return 0;
858 if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
859 goto fail;
860 rdev->sb_loaded = 1;
861 return 0;
863 fail:
864 printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
865 bdevname(rdev->bdev,b));
866 return -EINVAL;
869 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
871 return sb1->set_uuid0 == sb2->set_uuid0 &&
872 sb1->set_uuid1 == sb2->set_uuid1 &&
873 sb1->set_uuid2 == sb2->set_uuid2 &&
874 sb1->set_uuid3 == sb2->set_uuid3;
877 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
879 int ret;
880 mdp_super_t *tmp1, *tmp2;
882 tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
883 tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
885 if (!tmp1 || !tmp2) {
886 ret = 0;
887 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
888 goto abort;
891 *tmp1 = *sb1;
892 *tmp2 = *sb2;
895 * nr_disks is not constant
897 tmp1->nr_disks = 0;
898 tmp2->nr_disks = 0;
900 ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
901 abort:
902 kfree(tmp1);
903 kfree(tmp2);
904 return ret;
908 static u32 md_csum_fold(u32 csum)
910 csum = (csum & 0xffff) + (csum >> 16);
911 return (csum & 0xffff) + (csum >> 16);
914 static unsigned int calc_sb_csum(mdp_super_t * sb)
916 u64 newcsum = 0;
917 u32 *sb32 = (u32*)sb;
918 int i;
919 unsigned int disk_csum, csum;
921 disk_csum = sb->sb_csum;
922 sb->sb_csum = 0;
924 for (i = 0; i < MD_SB_BYTES/4 ; i++)
925 newcsum += sb32[i];
926 csum = (newcsum & 0xffffffff) + (newcsum>>32);
929 #ifdef CONFIG_ALPHA
930 /* This used to use csum_partial, which was wrong for several
931 * reasons including that different results are returned on
932 * different architectures. It isn't critical that we get exactly
933 * the same return value as before (we always csum_fold before
934 * testing, and that removes any differences). However as we
935 * know that csum_partial always returned a 16bit value on
936 * alphas, do a fold to maximise conformity to previous behaviour.
938 sb->sb_csum = md_csum_fold(disk_csum);
939 #else
940 sb->sb_csum = disk_csum;
941 #endif
942 return csum;
947 * Handle superblock details.
948 * We want to be able to handle multiple superblock formats
949 * so we have a common interface to them all, and an array of
950 * different handlers.
951 * We rely on user-space to write the initial superblock, and support
952 * reading and updating of superblocks.
953 * Interface methods are:
954 * int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
955 * loads and validates a superblock on dev.
956 * if refdev != NULL, compare superblocks on both devices
957 * Return:
958 * 0 - dev has a superblock that is compatible with refdev
959 * 1 - dev has a superblock that is compatible and newer than refdev
960 * so dev should be used as the refdev in future
961 * -EINVAL superblock incompatible or invalid
962 * -othererror e.g. -EIO
964 * int validate_super(struct mddev *mddev, struct md_rdev *dev)
965 * Verify that dev is acceptable into mddev.
966 * The first time, mddev->raid_disks will be 0, and data from
967 * dev should be merged in. Subsequent calls check that dev
968 * is new enough. Return 0 or -EINVAL
970 * void sync_super(struct mddev *mddev, struct md_rdev *dev)
971 * Update the superblock for rdev with data in mddev
972 * This does not write to disc.
976 struct super_type {
977 char *name;
978 struct module *owner;
979 int (*load_super)(struct md_rdev *rdev,
980 struct md_rdev *refdev,
981 int minor_version);
982 int (*validate_super)(struct mddev *mddev,
983 struct md_rdev *rdev);
984 void (*sync_super)(struct mddev *mddev,
985 struct md_rdev *rdev);
986 unsigned long long (*rdev_size_change)(struct md_rdev *rdev,
987 sector_t num_sectors);
988 int (*allow_new_offset)(struct md_rdev *rdev,
989 unsigned long long new_offset);
993 * Check that the given mddev has no bitmap.
995 * This function is called from the run method of all personalities that do not
996 * support bitmaps. It prints an error message and returns non-zero if mddev
997 * has a bitmap. Otherwise, it returns 0.
1000 int md_check_no_bitmap(struct mddev *mddev)
1002 if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1003 return 0;
1004 printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
1005 mdname(mddev), mddev->pers->name);
1006 return 1;
1008 EXPORT_SYMBOL(md_check_no_bitmap);
1011 * load_super for 0.90.0
1013 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1015 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1016 mdp_super_t *sb;
1017 int ret;
1020 * Calculate the position of the superblock (512byte sectors),
1021 * it's at the end of the disk.
1023 * It also happens to be a multiple of 4Kb.
1025 rdev->sb_start = calc_dev_sboffset(rdev);
1027 ret = read_disk_sb(rdev, MD_SB_BYTES);
1028 if (ret) return ret;
1030 ret = -EINVAL;
1032 bdevname(rdev->bdev, b);
1033 sb = page_address(rdev->sb_page);
1035 if (sb->md_magic != MD_SB_MAGIC) {
1036 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
1038 goto abort;
1041 if (sb->major_version != 0 ||
1042 sb->minor_version < 90 ||
1043 sb->minor_version > 91) {
1044 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
1045 sb->major_version, sb->minor_version,
1047 goto abort;
1050 if (sb->raid_disks <= 0)
1051 goto abort;
1053 if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1054 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1056 goto abort;
1059 rdev->preferred_minor = sb->md_minor;
1060 rdev->data_offset = 0;
1061 rdev->new_data_offset = 0;
1062 rdev->sb_size = MD_SB_BYTES;
1063 rdev->badblocks.shift = -1;
1065 if (sb->level == LEVEL_MULTIPATH)
1066 rdev->desc_nr = -1;
1067 else
1068 rdev->desc_nr = sb->this_disk.number;
1070 if (!refdev) {
1071 ret = 1;
1072 } else {
1073 __u64 ev1, ev2;
1074 mdp_super_t *refsb = page_address(refdev->sb_page);
1075 if (!uuid_equal(refsb, sb)) {
1076 printk(KERN_WARNING "md: %s has different UUID to %s\n",
1077 b, bdevname(refdev->bdev,b2));
1078 goto abort;
1080 if (!sb_equal(refsb, sb)) {
1081 printk(KERN_WARNING "md: %s has same UUID"
1082 " but different superblock to %s\n",
1083 b, bdevname(refdev->bdev, b2));
1084 goto abort;
1086 ev1 = md_event(sb);
1087 ev2 = md_event(refsb);
1088 if (ev1 > ev2)
1089 ret = 1;
1090 else
1091 ret = 0;
1093 rdev->sectors = rdev->sb_start;
1094 /* Limit to 4TB as metadata cannot record more than that.
1095 * (not needed for Linear and RAID0 as metadata doesn't
1096 * record this size)
1098 if (rdev->sectors >= (2ULL << 32) && sb->level >= 1)
1099 rdev->sectors = (2ULL << 32) - 2;
1101 if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1102 /* "this cannot possibly happen" ... */
1103 ret = -EINVAL;
1105 abort:
1106 return ret;
1110 * validate_super for 0.90.0
1112 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1114 mdp_disk_t *desc;
1115 mdp_super_t *sb = page_address(rdev->sb_page);
1116 __u64 ev1 = md_event(sb);
1118 rdev->raid_disk = -1;
1119 clear_bit(Faulty, &rdev->flags);
1120 clear_bit(In_sync, &rdev->flags);
1121 clear_bit(Bitmap_sync, &rdev->flags);
1122 clear_bit(WriteMostly, &rdev->flags);
1124 if (mddev->raid_disks == 0) {
1125 mddev->major_version = 0;
1126 mddev->minor_version = sb->minor_version;
1127 mddev->patch_version = sb->patch_version;
1128 mddev->external = 0;
1129 mddev->chunk_sectors = sb->chunk_size >> 9;
1130 mddev->ctime = sb->ctime;
1131 mddev->utime = sb->utime;
1132 mddev->level = sb->level;
1133 mddev->clevel[0] = 0;
1134 mddev->layout = sb->layout;
1135 mddev->raid_disks = sb->raid_disks;
1136 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1137 mddev->events = ev1;
1138 mddev->bitmap_info.offset = 0;
1139 mddev->bitmap_info.space = 0;
1140 /* bitmap can use 60 K after the 4K superblocks */
1141 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1142 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
1143 mddev->reshape_backwards = 0;
1145 if (mddev->minor_version >= 91) {
1146 mddev->reshape_position = sb->reshape_position;
1147 mddev->delta_disks = sb->delta_disks;
1148 mddev->new_level = sb->new_level;
1149 mddev->new_layout = sb->new_layout;
1150 mddev->new_chunk_sectors = sb->new_chunk >> 9;
1151 if (mddev->delta_disks < 0)
1152 mddev->reshape_backwards = 1;
1153 } else {
1154 mddev->reshape_position = MaxSector;
1155 mddev->delta_disks = 0;
1156 mddev->new_level = mddev->level;
1157 mddev->new_layout = mddev->layout;
1158 mddev->new_chunk_sectors = mddev->chunk_sectors;
1161 if (sb->state & (1<<MD_SB_CLEAN))
1162 mddev->recovery_cp = MaxSector;
1163 else {
1164 if (sb->events_hi == sb->cp_events_hi &&
1165 sb->events_lo == sb->cp_events_lo) {
1166 mddev->recovery_cp = sb->recovery_cp;
1167 } else
1168 mddev->recovery_cp = 0;
1171 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1172 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1173 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1174 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1176 mddev->max_disks = MD_SB_DISKS;
1178 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1179 mddev->bitmap_info.file == NULL) {
1180 mddev->bitmap_info.offset =
1181 mddev->bitmap_info.default_offset;
1182 mddev->bitmap_info.space =
1183 mddev->bitmap_info.space;
1186 } else if (mddev->pers == NULL) {
1187 /* Insist on good event counter while assembling, except
1188 * for spares (which don't need an event count) */
1189 ++ev1;
1190 if (sb->disks[rdev->desc_nr].state & (
1191 (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1192 if (ev1 < mddev->events)
1193 return -EINVAL;
1194 } else if (mddev->bitmap) {
1195 /* if adding to array with a bitmap, then we can accept an
1196 * older device ... but not too old.
1198 if (ev1 < mddev->bitmap->events_cleared)
1199 return 0;
1200 if (ev1 < mddev->events)
1201 set_bit(Bitmap_sync, &rdev->flags);
1202 } else {
1203 if (ev1 < mddev->events)
1204 /* just a hot-add of a new device, leave raid_disk at -1 */
1205 return 0;
1208 if (mddev->level != LEVEL_MULTIPATH) {
1209 desc = sb->disks + rdev->desc_nr;
1211 if (desc->state & (1<<MD_DISK_FAULTY))
1212 set_bit(Faulty, &rdev->flags);
1213 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1214 desc->raid_disk < mddev->raid_disks */) {
1215 set_bit(In_sync, &rdev->flags);
1216 rdev->raid_disk = desc->raid_disk;
1217 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1218 /* active but not in sync implies recovery up to
1219 * reshape position. We don't know exactly where
1220 * that is, so set to zero for now */
1221 if (mddev->minor_version >= 91) {
1222 rdev->recovery_offset = 0;
1223 rdev->raid_disk = desc->raid_disk;
1226 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1227 set_bit(WriteMostly, &rdev->flags);
1228 } else /* MULTIPATH are always insync */
1229 set_bit(In_sync, &rdev->flags);
1230 return 0;
1234 * sync_super for 0.90.0
1236 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1238 mdp_super_t *sb;
1239 struct md_rdev *rdev2;
1240 int next_spare = mddev->raid_disks;
1243 /* make rdev->sb match mddev data..
1245 * 1/ zero out disks
1246 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1247 * 3/ any empty disks < next_spare become removed
1249 * disks[0] gets initialised to REMOVED because
1250 * we cannot be sure from other fields if it has
1251 * been initialised or not.
1253 int i;
1254 int active=0, working=0,failed=0,spare=0,nr_disks=0;
1256 rdev->sb_size = MD_SB_BYTES;
1258 sb = page_address(rdev->sb_page);
1260 memset(sb, 0, sizeof(*sb));
1262 sb->md_magic = MD_SB_MAGIC;
1263 sb->major_version = mddev->major_version;
1264 sb->patch_version = mddev->patch_version;
1265 sb->gvalid_words = 0; /* ignored */
1266 memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1267 memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1268 memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1269 memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1271 sb->ctime = mddev->ctime;
1272 sb->level = mddev->level;
1273 sb->size = mddev->dev_sectors / 2;
1274 sb->raid_disks = mddev->raid_disks;
1275 sb->md_minor = mddev->md_minor;
1276 sb->not_persistent = 0;
1277 sb->utime = mddev->utime;
1278 sb->state = 0;
1279 sb->events_hi = (mddev->events>>32);
1280 sb->events_lo = (u32)mddev->events;
1282 if (mddev->reshape_position == MaxSector)
1283 sb->minor_version = 90;
1284 else {
1285 sb->minor_version = 91;
1286 sb->reshape_position = mddev->reshape_position;
1287 sb->new_level = mddev->new_level;
1288 sb->delta_disks = mddev->delta_disks;
1289 sb->new_layout = mddev->new_layout;
1290 sb->new_chunk = mddev->new_chunk_sectors << 9;
1292 mddev->minor_version = sb->minor_version;
1293 if (mddev->in_sync)
1295 sb->recovery_cp = mddev->recovery_cp;
1296 sb->cp_events_hi = (mddev->events>>32);
1297 sb->cp_events_lo = (u32)mddev->events;
1298 if (mddev->recovery_cp == MaxSector)
1299 sb->state = (1<< MD_SB_CLEAN);
1300 } else
1301 sb->recovery_cp = 0;
1303 sb->layout = mddev->layout;
1304 sb->chunk_size = mddev->chunk_sectors << 9;
1306 if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1307 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1309 sb->disks[0].state = (1<<MD_DISK_REMOVED);
1310 rdev_for_each(rdev2, mddev) {
1311 mdp_disk_t *d;
1312 int desc_nr;
1313 int is_active = test_bit(In_sync, &rdev2->flags);
1315 if (rdev2->raid_disk >= 0 &&
1316 sb->minor_version >= 91)
1317 /* we have nowhere to store the recovery_offset,
1318 * but if it is not below the reshape_position,
1319 * we can piggy-back on that.
1321 is_active = 1;
1322 if (rdev2->raid_disk < 0 ||
1323 test_bit(Faulty, &rdev2->flags))
1324 is_active = 0;
1325 if (is_active)
1326 desc_nr = rdev2->raid_disk;
1327 else
1328 desc_nr = next_spare++;
1329 rdev2->desc_nr = desc_nr;
1330 d = &sb->disks[rdev2->desc_nr];
1331 nr_disks++;
1332 d->number = rdev2->desc_nr;
1333 d->major = MAJOR(rdev2->bdev->bd_dev);
1334 d->minor = MINOR(rdev2->bdev->bd_dev);
1335 if (is_active)
1336 d->raid_disk = rdev2->raid_disk;
1337 else
1338 d->raid_disk = rdev2->desc_nr; /* compatibility */
1339 if (test_bit(Faulty, &rdev2->flags))
1340 d->state = (1<<MD_DISK_FAULTY);
1341 else if (is_active) {
1342 d->state = (1<<MD_DISK_ACTIVE);
1343 if (test_bit(In_sync, &rdev2->flags))
1344 d->state |= (1<<MD_DISK_SYNC);
1345 active++;
1346 working++;
1347 } else {
1348 d->state = 0;
1349 spare++;
1350 working++;
1352 if (test_bit(WriteMostly, &rdev2->flags))
1353 d->state |= (1<<MD_DISK_WRITEMOSTLY);
1355 /* now set the "removed" and "faulty" bits on any missing devices */
1356 for (i=0 ; i < mddev->raid_disks ; i++) {
1357 mdp_disk_t *d = &sb->disks[i];
1358 if (d->state == 0 && d->number == 0) {
1359 d->number = i;
1360 d->raid_disk = i;
1361 d->state = (1<<MD_DISK_REMOVED);
1362 d->state |= (1<<MD_DISK_FAULTY);
1363 failed++;
1366 sb->nr_disks = nr_disks;
1367 sb->active_disks = active;
1368 sb->working_disks = working;
1369 sb->failed_disks = failed;
1370 sb->spare_disks = spare;
1372 sb->this_disk = sb->disks[rdev->desc_nr];
1373 sb->sb_csum = calc_sb_csum(sb);
1377 * rdev_size_change for 0.90.0
1379 static unsigned long long
1380 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1382 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1383 return 0; /* component must fit device */
1384 if (rdev->mddev->bitmap_info.offset)
1385 return 0; /* can't move bitmap */
1386 rdev->sb_start = calc_dev_sboffset(rdev);
1387 if (!num_sectors || num_sectors > rdev->sb_start)
1388 num_sectors = rdev->sb_start;
1389 /* Limit to 4TB as metadata cannot record more than that.
1390 * 4TB == 2^32 KB, or 2*2^32 sectors.
1392 if (num_sectors >= (2ULL << 32) && rdev->mddev->level >= 1)
1393 num_sectors = (2ULL << 32) - 2;
1394 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1395 rdev->sb_page);
1396 md_super_wait(rdev->mddev);
1397 return num_sectors;
1400 static int
1401 super_90_allow_new_offset(struct md_rdev *rdev, unsigned long long new_offset)
1403 /* non-zero offset changes not possible with v0.90 */
1404 return new_offset == 0;
1408 * version 1 superblock
1411 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1413 __le32 disk_csum;
1414 u32 csum;
1415 unsigned long long newcsum;
1416 int size = 256 + le32_to_cpu(sb->max_dev)*2;
1417 __le32 *isuper = (__le32*)sb;
1419 disk_csum = sb->sb_csum;
1420 sb->sb_csum = 0;
1421 newcsum = 0;
1422 for (; size >= 4; size -= 4)
1423 newcsum += le32_to_cpu(*isuper++);
1425 if (size == 2)
1426 newcsum += le16_to_cpu(*(__le16*) isuper);
1428 csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1429 sb->sb_csum = disk_csum;
1430 return cpu_to_le32(csum);
1433 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
1434 int acknowledged);
1435 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1437 struct mdp_superblock_1 *sb;
1438 int ret;
1439 sector_t sb_start;
1440 sector_t sectors;
1441 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1442 int bmask;
1445 * Calculate the position of the superblock in 512byte sectors.
1446 * It is always aligned to a 4K boundary and
1447 * depeding on minor_version, it can be:
1448 * 0: At least 8K, but less than 12K, from end of device
1449 * 1: At start of device
1450 * 2: 4K from start of device.
1452 switch(minor_version) {
1453 case 0:
1454 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1455 sb_start -= 8*2;
1456 sb_start &= ~(sector_t)(4*2-1);
1457 break;
1458 case 1:
1459 sb_start = 0;
1460 break;
1461 case 2:
1462 sb_start = 8;
1463 break;
1464 default:
1465 return -EINVAL;
1467 rdev->sb_start = sb_start;
1469 /* superblock is rarely larger than 1K, but it can be larger,
1470 * and it is safe to read 4k, so we do that
1472 ret = read_disk_sb(rdev, 4096);
1473 if (ret) return ret;
1476 sb = page_address(rdev->sb_page);
1478 if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1479 sb->major_version != cpu_to_le32(1) ||
1480 le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1481 le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1482 (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1483 return -EINVAL;
1485 if (calc_sb_1_csum(sb) != sb->sb_csum) {
1486 printk("md: invalid superblock checksum on %s\n",
1487 bdevname(rdev->bdev,b));
1488 return -EINVAL;
1490 if (le64_to_cpu(sb->data_size) < 10) {
1491 printk("md: data_size too small on %s\n",
1492 bdevname(rdev->bdev,b));
1493 return -EINVAL;
1495 if (sb->pad0 ||
1496 sb->pad3[0] ||
1497 memcmp(sb->pad3, sb->pad3+1, sizeof(sb->pad3) - sizeof(sb->pad3[1])))
1498 /* Some padding is non-zero, might be a new feature */
1499 return -EINVAL;
1501 rdev->preferred_minor = 0xffff;
1502 rdev->data_offset = le64_to_cpu(sb->data_offset);
1503 rdev->new_data_offset = rdev->data_offset;
1504 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE) &&
1505 (le32_to_cpu(sb->feature_map) & MD_FEATURE_NEW_OFFSET))
1506 rdev->new_data_offset += (s32)le32_to_cpu(sb->new_offset);
1507 atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1509 rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1510 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1511 if (rdev->sb_size & bmask)
1512 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1514 if (minor_version
1515 && rdev->data_offset < sb_start + (rdev->sb_size/512))
1516 return -EINVAL;
1517 if (minor_version
1518 && rdev->new_data_offset < sb_start + (rdev->sb_size/512))
1519 return -EINVAL;
1521 if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1522 rdev->desc_nr = -1;
1523 else
1524 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1526 if (!rdev->bb_page) {
1527 rdev->bb_page = alloc_page(GFP_KERNEL);
1528 if (!rdev->bb_page)
1529 return -ENOMEM;
1531 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1532 rdev->badblocks.count == 0) {
1533 /* need to load the bad block list.
1534 * Currently we limit it to one page.
1536 s32 offset;
1537 sector_t bb_sector;
1538 u64 *bbp;
1539 int i;
1540 int sectors = le16_to_cpu(sb->bblog_size);
1541 if (sectors > (PAGE_SIZE / 512))
1542 return -EINVAL;
1543 offset = le32_to_cpu(sb->bblog_offset);
1544 if (offset == 0)
1545 return -EINVAL;
1546 bb_sector = (long long)offset;
1547 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1548 rdev->bb_page, READ, true))
1549 return -EIO;
1550 bbp = (u64 *)page_address(rdev->bb_page);
1551 rdev->badblocks.shift = sb->bblog_shift;
1552 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1553 u64 bb = le64_to_cpu(*bbp);
1554 int count = bb & (0x3ff);
1555 u64 sector = bb >> 10;
1556 sector <<= sb->bblog_shift;
1557 count <<= sb->bblog_shift;
1558 if (bb + 1 == 0)
1559 break;
1560 if (md_set_badblocks(&rdev->badblocks,
1561 sector, count, 1) == 0)
1562 return -EINVAL;
1564 } else if (sb->bblog_offset != 0)
1565 rdev->badblocks.shift = 0;
1567 if (!refdev) {
1568 ret = 1;
1569 } else {
1570 __u64 ev1, ev2;
1571 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1573 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1574 sb->level != refsb->level ||
1575 sb->layout != refsb->layout ||
1576 sb->chunksize != refsb->chunksize) {
1577 printk(KERN_WARNING "md: %s has strangely different"
1578 " superblock to %s\n",
1579 bdevname(rdev->bdev,b),
1580 bdevname(refdev->bdev,b2));
1581 return -EINVAL;
1583 ev1 = le64_to_cpu(sb->events);
1584 ev2 = le64_to_cpu(refsb->events);
1586 if (ev1 > ev2)
1587 ret = 1;
1588 else
1589 ret = 0;
1591 if (minor_version) {
1592 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9);
1593 sectors -= rdev->data_offset;
1594 } else
1595 sectors = rdev->sb_start;
1596 if (sectors < le64_to_cpu(sb->data_size))
1597 return -EINVAL;
1598 rdev->sectors = le64_to_cpu(sb->data_size);
1599 return ret;
1602 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1604 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1605 __u64 ev1 = le64_to_cpu(sb->events);
1607 rdev->raid_disk = -1;
1608 clear_bit(Faulty, &rdev->flags);
1609 clear_bit(In_sync, &rdev->flags);
1610 clear_bit(Bitmap_sync, &rdev->flags);
1611 clear_bit(WriteMostly, &rdev->flags);
1613 if (mddev->raid_disks == 0) {
1614 mddev->major_version = 1;
1615 mddev->patch_version = 0;
1616 mddev->external = 0;
1617 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1618 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1619 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1620 mddev->level = le32_to_cpu(sb->level);
1621 mddev->clevel[0] = 0;
1622 mddev->layout = le32_to_cpu(sb->layout);
1623 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1624 mddev->dev_sectors = le64_to_cpu(sb->size);
1625 mddev->events = ev1;
1626 mddev->bitmap_info.offset = 0;
1627 mddev->bitmap_info.space = 0;
1628 /* Default location for bitmap is 1K after superblock
1629 * using 3K - total of 4K
1631 mddev->bitmap_info.default_offset = 1024 >> 9;
1632 mddev->bitmap_info.default_space = (4096-1024) >> 9;
1633 mddev->reshape_backwards = 0;
1635 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1636 memcpy(mddev->uuid, sb->set_uuid, 16);
1638 mddev->max_disks = (4096-256)/2;
1640 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1641 mddev->bitmap_info.file == NULL) {
1642 mddev->bitmap_info.offset =
1643 (__s32)le32_to_cpu(sb->bitmap_offset);
1644 /* Metadata doesn't record how much space is available.
1645 * For 1.0, we assume we can use up to the superblock
1646 * if before, else to 4K beyond superblock.
1647 * For others, assume no change is possible.
1649 if (mddev->minor_version > 0)
1650 mddev->bitmap_info.space = 0;
1651 else if (mddev->bitmap_info.offset > 0)
1652 mddev->bitmap_info.space =
1653 8 - mddev->bitmap_info.offset;
1654 else
1655 mddev->bitmap_info.space =
1656 -mddev->bitmap_info.offset;
1659 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1660 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1661 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1662 mddev->new_level = le32_to_cpu(sb->new_level);
1663 mddev->new_layout = le32_to_cpu(sb->new_layout);
1664 mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1665 if (mddev->delta_disks < 0 ||
1666 (mddev->delta_disks == 0 &&
1667 (le32_to_cpu(sb->feature_map)
1668 & MD_FEATURE_RESHAPE_BACKWARDS)))
1669 mddev->reshape_backwards = 1;
1670 } else {
1671 mddev->reshape_position = MaxSector;
1672 mddev->delta_disks = 0;
1673 mddev->new_level = mddev->level;
1674 mddev->new_layout = mddev->layout;
1675 mddev->new_chunk_sectors = mddev->chunk_sectors;
1678 } else if (mddev->pers == NULL) {
1679 /* Insist of good event counter while assembling, except for
1680 * spares (which don't need an event count) */
1681 ++ev1;
1682 if (rdev->desc_nr >= 0 &&
1683 rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1684 le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1685 if (ev1 < mddev->events)
1686 return -EINVAL;
1687 } else if (mddev->bitmap) {
1688 /* If adding to array with a bitmap, then we can accept an
1689 * older device, but not too old.
1691 if (ev1 < mddev->bitmap->events_cleared)
1692 return 0;
1693 if (ev1 < mddev->events)
1694 set_bit(Bitmap_sync, &rdev->flags);
1695 } else {
1696 if (ev1 < mddev->events)
1697 /* just a hot-add of a new device, leave raid_disk at -1 */
1698 return 0;
1700 if (mddev->level != LEVEL_MULTIPATH) {
1701 int role;
1702 if (rdev->desc_nr < 0 ||
1703 rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1704 role = 0xffff;
1705 rdev->desc_nr = -1;
1706 } else
1707 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1708 switch(role) {
1709 case 0xffff: /* spare */
1710 break;
1711 case 0xfffe: /* faulty */
1712 set_bit(Faulty, &rdev->flags);
1713 break;
1714 default:
1715 if ((le32_to_cpu(sb->feature_map) &
1716 MD_FEATURE_RECOVERY_OFFSET))
1717 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1718 else
1719 set_bit(In_sync, &rdev->flags);
1720 rdev->raid_disk = role;
1721 break;
1723 if (sb->devflags & WriteMostly1)
1724 set_bit(WriteMostly, &rdev->flags);
1725 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1726 set_bit(Replacement, &rdev->flags);
1727 } else /* MULTIPATH are always insync */
1728 set_bit(In_sync, &rdev->flags);
1730 return 0;
1733 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1735 struct mdp_superblock_1 *sb;
1736 struct md_rdev *rdev2;
1737 int max_dev, i;
1738 /* make rdev->sb match mddev and rdev data. */
1740 sb = page_address(rdev->sb_page);
1742 sb->feature_map = 0;
1743 sb->pad0 = 0;
1744 sb->recovery_offset = cpu_to_le64(0);
1745 memset(sb->pad3, 0, sizeof(sb->pad3));
1747 sb->utime = cpu_to_le64((__u64)mddev->utime);
1748 sb->events = cpu_to_le64(mddev->events);
1749 if (mddev->in_sync)
1750 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1751 else
1752 sb->resync_offset = cpu_to_le64(0);
1754 sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1756 sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1757 sb->size = cpu_to_le64(mddev->dev_sectors);
1758 sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1759 sb->level = cpu_to_le32(mddev->level);
1760 sb->layout = cpu_to_le32(mddev->layout);
1762 if (test_bit(WriteMostly, &rdev->flags))
1763 sb->devflags |= WriteMostly1;
1764 else
1765 sb->devflags &= ~WriteMostly1;
1766 sb->data_offset = cpu_to_le64(rdev->data_offset);
1767 sb->data_size = cpu_to_le64(rdev->sectors);
1769 if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1770 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1771 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1774 if (rdev->raid_disk >= 0 &&
1775 !test_bit(In_sync, &rdev->flags)) {
1776 sb->feature_map |=
1777 cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1778 sb->recovery_offset =
1779 cpu_to_le64(rdev->recovery_offset);
1781 if (test_bit(Replacement, &rdev->flags))
1782 sb->feature_map |=
1783 cpu_to_le32(MD_FEATURE_REPLACEMENT);
1785 if (mddev->reshape_position != MaxSector) {
1786 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1787 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1788 sb->new_layout = cpu_to_le32(mddev->new_layout);
1789 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1790 sb->new_level = cpu_to_le32(mddev->new_level);
1791 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1792 if (mddev->delta_disks == 0 &&
1793 mddev->reshape_backwards)
1794 sb->feature_map
1795 |= cpu_to_le32(MD_FEATURE_RESHAPE_BACKWARDS);
1796 if (rdev->new_data_offset != rdev->data_offset) {
1797 sb->feature_map
1798 |= cpu_to_le32(MD_FEATURE_NEW_OFFSET);
1799 sb->new_offset = cpu_to_le32((__u32)(rdev->new_data_offset
1800 - rdev->data_offset));
1804 if (rdev->badblocks.count == 0)
1805 /* Nothing to do for bad blocks*/ ;
1806 else if (sb->bblog_offset == 0)
1807 /* Cannot record bad blocks on this device */
1808 md_error(mddev, rdev);
1809 else {
1810 struct badblocks *bb = &rdev->badblocks;
1811 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1812 u64 *p = bb->page;
1813 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1814 if (bb->changed) {
1815 unsigned seq;
1817 retry:
1818 seq = read_seqbegin(&bb->lock);
1820 memset(bbp, 0xff, PAGE_SIZE);
1822 for (i = 0 ; i < bb->count ; i++) {
1823 u64 internal_bb = p[i];
1824 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1825 | BB_LEN(internal_bb));
1826 bbp[i] = cpu_to_le64(store_bb);
1828 bb->changed = 0;
1829 if (read_seqretry(&bb->lock, seq))
1830 goto retry;
1832 bb->sector = (rdev->sb_start +
1833 (int)le32_to_cpu(sb->bblog_offset));
1834 bb->size = le16_to_cpu(sb->bblog_size);
1838 max_dev = 0;
1839 rdev_for_each(rdev2, mddev)
1840 if (rdev2->desc_nr+1 > max_dev)
1841 max_dev = rdev2->desc_nr+1;
1843 if (max_dev > le32_to_cpu(sb->max_dev)) {
1844 int bmask;
1845 sb->max_dev = cpu_to_le32(max_dev);
1846 rdev->sb_size = max_dev * 2 + 256;
1847 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1848 if (rdev->sb_size & bmask)
1849 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1850 } else
1851 max_dev = le32_to_cpu(sb->max_dev);
1853 for (i=0; i<max_dev;i++)
1854 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1856 rdev_for_each(rdev2, mddev) {
1857 i = rdev2->desc_nr;
1858 if (test_bit(Faulty, &rdev2->flags))
1859 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1860 else if (test_bit(In_sync, &rdev2->flags))
1861 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1862 else if (rdev2->raid_disk >= 0)
1863 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1864 else
1865 sb->dev_roles[i] = cpu_to_le16(0xffff);
1868 sb->sb_csum = calc_sb_1_csum(sb);
1871 static unsigned long long
1872 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1874 struct mdp_superblock_1 *sb;
1875 sector_t max_sectors;
1876 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1877 return 0; /* component must fit device */
1878 if (rdev->data_offset != rdev->new_data_offset)
1879 return 0; /* too confusing */
1880 if (rdev->sb_start < rdev->data_offset) {
1881 /* minor versions 1 and 2; superblock before data */
1882 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1883 max_sectors -= rdev->data_offset;
1884 if (!num_sectors || num_sectors > max_sectors)
1885 num_sectors = max_sectors;
1886 } else if (rdev->mddev->bitmap_info.offset) {
1887 /* minor version 0 with bitmap we can't move */
1888 return 0;
1889 } else {
1890 /* minor version 0; superblock after data */
1891 sector_t sb_start;
1892 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1893 sb_start &= ~(sector_t)(4*2 - 1);
1894 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1895 if (!num_sectors || num_sectors > max_sectors)
1896 num_sectors = max_sectors;
1897 rdev->sb_start = sb_start;
1899 sb = page_address(rdev->sb_page);
1900 sb->data_size = cpu_to_le64(num_sectors);
1901 sb->super_offset = rdev->sb_start;
1902 sb->sb_csum = calc_sb_1_csum(sb);
1903 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1904 rdev->sb_page);
1905 md_super_wait(rdev->mddev);
1906 return num_sectors;
1910 static int
1911 super_1_allow_new_offset(struct md_rdev *rdev,
1912 unsigned long long new_offset)
1914 /* All necessary checks on new >= old have been done */
1915 struct bitmap *bitmap;
1916 if (new_offset >= rdev->data_offset)
1917 return 1;
1919 /* with 1.0 metadata, there is no metadata to tread on
1920 * so we can always move back */
1921 if (rdev->mddev->minor_version == 0)
1922 return 1;
1924 /* otherwise we must be sure not to step on
1925 * any metadata, so stay:
1926 * 36K beyond start of superblock
1927 * beyond end of badblocks
1928 * beyond write-intent bitmap
1930 if (rdev->sb_start + (32+4)*2 > new_offset)
1931 return 0;
1932 bitmap = rdev->mddev->bitmap;
1933 if (bitmap && !rdev->mddev->bitmap_info.file &&
1934 rdev->sb_start + rdev->mddev->bitmap_info.offset +
1935 bitmap->storage.file_pages * (PAGE_SIZE>>9) > new_offset)
1936 return 0;
1937 if (rdev->badblocks.sector + rdev->badblocks.size > new_offset)
1938 return 0;
1940 return 1;
1943 static struct super_type super_types[] = {
1944 [0] = {
1945 .name = "0.90.0",
1946 .owner = THIS_MODULE,
1947 .load_super = super_90_load,
1948 .validate_super = super_90_validate,
1949 .sync_super = super_90_sync,
1950 .rdev_size_change = super_90_rdev_size_change,
1951 .allow_new_offset = super_90_allow_new_offset,
1953 [1] = {
1954 .name = "md-1",
1955 .owner = THIS_MODULE,
1956 .load_super = super_1_load,
1957 .validate_super = super_1_validate,
1958 .sync_super = super_1_sync,
1959 .rdev_size_change = super_1_rdev_size_change,
1960 .allow_new_offset = super_1_allow_new_offset,
1964 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
1966 if (mddev->sync_super) {
1967 mddev->sync_super(mddev, rdev);
1968 return;
1971 BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
1973 super_types[mddev->major_version].sync_super(mddev, rdev);
1976 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
1978 struct md_rdev *rdev, *rdev2;
1980 rcu_read_lock();
1981 rdev_for_each_rcu(rdev, mddev1)
1982 rdev_for_each_rcu(rdev2, mddev2)
1983 if (rdev->bdev->bd_contains ==
1984 rdev2->bdev->bd_contains) {
1985 rcu_read_unlock();
1986 return 1;
1988 rcu_read_unlock();
1989 return 0;
1992 static LIST_HEAD(pending_raid_disks);
1995 * Try to register data integrity profile for an mddev
1997 * This is called when an array is started and after a disk has been kicked
1998 * from the array. It only succeeds if all working and active component devices
1999 * are integrity capable with matching profiles.
2001 int md_integrity_register(struct mddev *mddev)
2003 struct md_rdev *rdev, *reference = NULL;
2005 if (list_empty(&mddev->disks))
2006 return 0; /* nothing to do */
2007 if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
2008 return 0; /* shouldn't register, or already is */
2009 rdev_for_each(rdev, mddev) {
2010 /* skip spares and non-functional disks */
2011 if (test_bit(Faulty, &rdev->flags))
2012 continue;
2013 if (rdev->raid_disk < 0)
2014 continue;
2015 if (!reference) {
2016 /* Use the first rdev as the reference */
2017 reference = rdev;
2018 continue;
2020 /* does this rdev's profile match the reference profile? */
2021 if (blk_integrity_compare(reference->bdev->bd_disk,
2022 rdev->bdev->bd_disk) < 0)
2023 return -EINVAL;
2025 if (!reference || !bdev_get_integrity(reference->bdev))
2026 return 0;
2028 * All component devices are integrity capable and have matching
2029 * profiles, register the common profile for the md device.
2031 if (blk_integrity_register(mddev->gendisk,
2032 bdev_get_integrity(reference->bdev)) != 0) {
2033 printk(KERN_ERR "md: failed to register integrity for %s\n",
2034 mdname(mddev));
2035 return -EINVAL;
2037 printk(KERN_NOTICE "md: data integrity enabled on %s\n", mdname(mddev));
2038 if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
2039 printk(KERN_ERR "md: failed to create integrity pool for %s\n",
2040 mdname(mddev));
2041 return -EINVAL;
2043 return 0;
2045 EXPORT_SYMBOL(md_integrity_register);
2047 /* Disable data integrity if non-capable/non-matching disk is being added */
2048 void md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
2050 struct blk_integrity *bi_rdev;
2051 struct blk_integrity *bi_mddev;
2053 if (!mddev->gendisk)
2054 return;
2056 bi_rdev = bdev_get_integrity(rdev->bdev);
2057 bi_mddev = blk_get_integrity(mddev->gendisk);
2059 if (!bi_mddev) /* nothing to do */
2060 return;
2061 if (rdev->raid_disk < 0) /* skip spares */
2062 return;
2063 if (bi_rdev && blk_integrity_compare(mddev->gendisk,
2064 rdev->bdev->bd_disk) >= 0)
2065 return;
2066 printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
2067 blk_integrity_unregister(mddev->gendisk);
2069 EXPORT_SYMBOL(md_integrity_add_rdev);
2071 static int bind_rdev_to_array(struct md_rdev * rdev, struct mddev * mddev)
2073 char b[BDEVNAME_SIZE];
2074 struct kobject *ko;
2075 char *s;
2076 int err;
2078 if (rdev->mddev) {
2079 MD_BUG();
2080 return -EINVAL;
2083 /* prevent duplicates */
2084 if (find_rdev(mddev, rdev->bdev->bd_dev))
2085 return -EEXIST;
2087 /* make sure rdev->sectors exceeds mddev->dev_sectors */
2088 if (rdev->sectors && (mddev->dev_sectors == 0 ||
2089 rdev->sectors < mddev->dev_sectors)) {
2090 if (mddev->pers) {
2091 /* Cannot change size, so fail
2092 * If mddev->level <= 0, then we don't care
2093 * about aligning sizes (e.g. linear)
2095 if (mddev->level > 0)
2096 return -ENOSPC;
2097 } else
2098 mddev->dev_sectors = rdev->sectors;
2101 /* Verify rdev->desc_nr is unique.
2102 * If it is -1, assign a free number, else
2103 * check number is not in use
2105 if (rdev->desc_nr < 0) {
2106 int choice = 0;
2107 if (mddev->pers) choice = mddev->raid_disks;
2108 while (find_rdev_nr(mddev, choice))
2109 choice++;
2110 rdev->desc_nr = choice;
2111 } else {
2112 if (find_rdev_nr(mddev, rdev->desc_nr))
2113 return -EBUSY;
2115 if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2116 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
2117 mdname(mddev), mddev->max_disks);
2118 return -EBUSY;
2120 bdevname(rdev->bdev,b);
2121 while ( (s=strchr(b, '/')) != NULL)
2122 *s = '!';
2124 rdev->mddev = mddev;
2125 printk(KERN_INFO "md: bind<%s>\n", b);
2127 if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2128 goto fail;
2130 ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2131 if (sysfs_create_link(&rdev->kobj, ko, "block"))
2132 /* failure here is OK */;
2133 rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2135 list_add_rcu(&rdev->same_set, &mddev->disks);
2136 bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2138 /* May as well allow recovery to be retried once */
2139 mddev->recovery_disabled++;
2141 return 0;
2143 fail:
2144 printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
2145 b, mdname(mddev));
2146 return err;
2149 static void md_delayed_delete(struct work_struct *ws)
2151 struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2152 kobject_del(&rdev->kobj);
2153 kobject_put(&rdev->kobj);
2156 static void unbind_rdev_from_array(struct md_rdev * rdev)
2158 char b[BDEVNAME_SIZE];
2159 if (!rdev->mddev) {
2160 MD_BUG();
2161 return;
2163 bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2164 list_del_rcu(&rdev->same_set);
2165 printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
2166 rdev->mddev = NULL;
2167 sysfs_remove_link(&rdev->kobj, "block");
2168 sysfs_put(rdev->sysfs_state);
2169 rdev->sysfs_state = NULL;
2170 rdev->badblocks.count = 0;
2171 /* We need to delay this, otherwise we can deadlock when
2172 * writing to 'remove' to "dev/state". We also need
2173 * to delay it due to rcu usage.
2175 synchronize_rcu();
2176 INIT_WORK(&rdev->del_work, md_delayed_delete);
2177 kobject_get(&rdev->kobj);
2178 queue_work(md_misc_wq, &rdev->del_work);
2182 * prevent the device from being mounted, repartitioned or
2183 * otherwise reused by a RAID array (or any other kernel
2184 * subsystem), by bd_claiming the device.
2186 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2188 int err = 0;
2189 struct block_device *bdev;
2190 char b[BDEVNAME_SIZE];
2192 bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2193 shared ? (struct md_rdev *)lock_rdev : rdev);
2194 if (IS_ERR(bdev)) {
2195 printk(KERN_ERR "md: could not open %s.\n",
2196 __bdevname(dev, b));
2197 return PTR_ERR(bdev);
2199 rdev->bdev = bdev;
2200 return err;
2203 static void unlock_rdev(struct md_rdev *rdev)
2205 struct block_device *bdev = rdev->bdev;
2206 rdev->bdev = NULL;
2207 if (!bdev)
2208 MD_BUG();
2209 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2212 void md_autodetect_dev(dev_t dev);
2214 static void export_rdev(struct md_rdev * rdev)
2216 char b[BDEVNAME_SIZE];
2217 printk(KERN_INFO "md: export_rdev(%s)\n",
2218 bdevname(rdev->bdev,b));
2219 if (rdev->mddev)
2220 MD_BUG();
2221 md_rdev_clear(rdev);
2222 #ifndef MODULE
2223 if (test_bit(AutoDetected, &rdev->flags))
2224 md_autodetect_dev(rdev->bdev->bd_dev);
2225 #endif
2226 unlock_rdev(rdev);
2227 kobject_put(&rdev->kobj);
2230 static void kick_rdev_from_array(struct md_rdev * rdev)
2232 unbind_rdev_from_array(rdev);
2233 export_rdev(rdev);
2236 static void export_array(struct mddev *mddev)
2238 struct md_rdev *rdev, *tmp;
2240 rdev_for_each_safe(rdev, tmp, mddev) {
2241 if (!rdev->mddev) {
2242 MD_BUG();
2243 continue;
2245 kick_rdev_from_array(rdev);
2247 if (!list_empty(&mddev->disks))
2248 MD_BUG();
2249 mddev->raid_disks = 0;
2250 mddev->major_version = 0;
2253 static void print_desc(mdp_disk_t *desc)
2255 printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
2256 desc->major,desc->minor,desc->raid_disk,desc->state);
2259 static void print_sb_90(mdp_super_t *sb)
2261 int i;
2263 printk(KERN_INFO
2264 "md: SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
2265 sb->major_version, sb->minor_version, sb->patch_version,
2266 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
2267 sb->ctime);
2268 printk(KERN_INFO "md: L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
2269 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
2270 sb->md_minor, sb->layout, sb->chunk_size);
2271 printk(KERN_INFO "md: UT:%08x ST:%d AD:%d WD:%d"
2272 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
2273 sb->utime, sb->state, sb->active_disks, sb->working_disks,
2274 sb->failed_disks, sb->spare_disks,
2275 sb->sb_csum, (unsigned long)sb->events_lo);
2277 printk(KERN_INFO);
2278 for (i = 0; i < MD_SB_DISKS; i++) {
2279 mdp_disk_t *desc;
2281 desc = sb->disks + i;
2282 if (desc->number || desc->major || desc->minor ||
2283 desc->raid_disk || (desc->state && (desc->state != 4))) {
2284 printk(" D %2d: ", i);
2285 print_desc(desc);
2288 printk(KERN_INFO "md: THIS: ");
2289 print_desc(&sb->this_disk);
2292 static void print_sb_1(struct mdp_superblock_1 *sb)
2294 __u8 *uuid;
2296 uuid = sb->set_uuid;
2297 printk(KERN_INFO
2298 "md: SB: (V:%u) (F:0x%08x) Array-ID:<%pU>\n"
2299 "md: Name: \"%s\" CT:%llu\n",
2300 le32_to_cpu(sb->major_version),
2301 le32_to_cpu(sb->feature_map),
2302 uuid,
2303 sb->set_name,
2304 (unsigned long long)le64_to_cpu(sb->ctime)
2305 & MD_SUPERBLOCK_1_TIME_SEC_MASK);
2307 uuid = sb->device_uuid;
2308 printk(KERN_INFO
2309 "md: L%u SZ%llu RD:%u LO:%u CS:%u DO:%llu DS:%llu SO:%llu"
2310 " RO:%llu\n"
2311 "md: Dev:%08x UUID: %pU\n"
2312 "md: (F:0x%08x) UT:%llu Events:%llu ResyncOffset:%llu CSUM:0x%08x\n"
2313 "md: (MaxDev:%u) \n",
2314 le32_to_cpu(sb->level),
2315 (unsigned long long)le64_to_cpu(sb->size),
2316 le32_to_cpu(sb->raid_disks),
2317 le32_to_cpu(sb->layout),
2318 le32_to_cpu(sb->chunksize),
2319 (unsigned long long)le64_to_cpu(sb->data_offset),
2320 (unsigned long long)le64_to_cpu(sb->data_size),
2321 (unsigned long long)le64_to_cpu(sb->super_offset),
2322 (unsigned long long)le64_to_cpu(sb->recovery_offset),
2323 le32_to_cpu(sb->dev_number),
2324 uuid,
2325 sb->devflags,
2326 (unsigned long long)le64_to_cpu(sb->utime) & MD_SUPERBLOCK_1_TIME_SEC_MASK,
2327 (unsigned long long)le64_to_cpu(sb->events),
2328 (unsigned long long)le64_to_cpu(sb->resync_offset),
2329 le32_to_cpu(sb->sb_csum),
2330 le32_to_cpu(sb->max_dev)
2334 static void print_rdev(struct md_rdev *rdev, int major_version)
2336 char b[BDEVNAME_SIZE];
2337 printk(KERN_INFO "md: rdev %s, Sect:%08llu F:%d S:%d DN:%u\n",
2338 bdevname(rdev->bdev, b), (unsigned long long)rdev->sectors,
2339 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
2340 rdev->desc_nr);
2341 if (rdev->sb_loaded) {
2342 printk(KERN_INFO "md: rdev superblock (MJ:%d):\n", major_version);
2343 switch (major_version) {
2344 case 0:
2345 print_sb_90(page_address(rdev->sb_page));
2346 break;
2347 case 1:
2348 print_sb_1(page_address(rdev->sb_page));
2349 break;
2351 } else
2352 printk(KERN_INFO "md: no rdev superblock!\n");
2355 static void md_print_devices(void)
2357 struct list_head *tmp;
2358 struct md_rdev *rdev;
2359 struct mddev *mddev;
2360 char b[BDEVNAME_SIZE];
2362 printk("\n");
2363 printk("md: **********************************\n");
2364 printk("md: * <COMPLETE RAID STATE PRINTOUT> *\n");
2365 printk("md: **********************************\n");
2366 for_each_mddev(mddev, tmp) {
2368 if (mddev->bitmap)
2369 bitmap_print_sb(mddev->bitmap);
2370 else
2371 printk("%s: ", mdname(mddev));
2372 rdev_for_each(rdev, mddev)
2373 printk("<%s>", bdevname(rdev->bdev,b));
2374 printk("\n");
2376 rdev_for_each(rdev, mddev)
2377 print_rdev(rdev, mddev->major_version);
2379 printk("md: **********************************\n");
2380 printk("\n");
2384 static void sync_sbs(struct mddev * mddev, int nospares)
2386 /* Update each superblock (in-memory image), but
2387 * if we are allowed to, skip spares which already
2388 * have the right event counter, or have one earlier
2389 * (which would mean they aren't being marked as dirty
2390 * with the rest of the array)
2392 struct md_rdev *rdev;
2393 rdev_for_each(rdev, mddev) {
2394 if (rdev->sb_events == mddev->events ||
2395 (nospares &&
2396 rdev->raid_disk < 0 &&
2397 rdev->sb_events+1 == mddev->events)) {
2398 /* Don't update this superblock */
2399 rdev->sb_loaded = 2;
2400 } else {
2401 sync_super(mddev, rdev);
2402 rdev->sb_loaded = 1;
2407 static void md_update_sb(struct mddev * mddev, int force_change)
2409 struct md_rdev *rdev;
2410 int sync_req;
2411 int nospares = 0;
2412 int any_badblocks_changed = 0;
2414 if (mddev->ro) {
2415 if (force_change)
2416 set_bit(MD_CHANGE_DEVS, &mddev->flags);
2417 return;
2419 repeat:
2420 /* First make sure individual recovery_offsets are correct */
2421 rdev_for_each(rdev, mddev) {
2422 if (rdev->raid_disk >= 0 &&
2423 mddev->delta_disks >= 0 &&
2424 !test_bit(In_sync, &rdev->flags) &&
2425 mddev->curr_resync_completed > rdev->recovery_offset)
2426 rdev->recovery_offset = mddev->curr_resync_completed;
2429 if (!mddev->persistent) {
2430 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2431 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2432 if (!mddev->external) {
2433 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2434 rdev_for_each(rdev, mddev) {
2435 if (rdev->badblocks.changed) {
2436 rdev->badblocks.changed = 0;
2437 md_ack_all_badblocks(&rdev->badblocks);
2438 md_error(mddev, rdev);
2440 clear_bit(Blocked, &rdev->flags);
2441 clear_bit(BlockedBadBlocks, &rdev->flags);
2442 wake_up(&rdev->blocked_wait);
2445 wake_up(&mddev->sb_wait);
2446 return;
2449 spin_lock_irq(&mddev->write_lock);
2451 mddev->utime = get_seconds();
2453 if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2454 force_change = 1;
2455 if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2456 /* just a clean<-> dirty transition, possibly leave spares alone,
2457 * though if events isn't the right even/odd, we will have to do
2458 * spares after all
2460 nospares = 1;
2461 if (force_change)
2462 nospares = 0;
2463 if (mddev->degraded)
2464 /* If the array is degraded, then skipping spares is both
2465 * dangerous and fairly pointless.
2466 * Dangerous because a device that was removed from the array
2467 * might have a event_count that still looks up-to-date,
2468 * so it can be re-added without a resync.
2469 * Pointless because if there are any spares to skip,
2470 * then a recovery will happen and soon that array won't
2471 * be degraded any more and the spare can go back to sleep then.
2473 nospares = 0;
2475 sync_req = mddev->in_sync;
2477 /* If this is just a dirty<->clean transition, and the array is clean
2478 * and 'events' is odd, we can roll back to the previous clean state */
2479 if (nospares
2480 && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2481 && mddev->can_decrease_events
2482 && mddev->events != 1) {
2483 mddev->events--;
2484 mddev->can_decrease_events = 0;
2485 } else {
2486 /* otherwise we have to go forward and ... */
2487 mddev->events ++;
2488 mddev->can_decrease_events = nospares;
2491 if (!mddev->events) {
2493 * oops, this 64-bit counter should never wrap.
2494 * Either we are in around ~1 trillion A.C., assuming
2495 * 1 reboot per second, or we have a bug:
2497 MD_BUG();
2498 mddev->events --;
2501 rdev_for_each(rdev, mddev) {
2502 if (rdev->badblocks.changed)
2503 any_badblocks_changed++;
2504 if (test_bit(Faulty, &rdev->flags))
2505 set_bit(FaultRecorded, &rdev->flags);
2508 sync_sbs(mddev, nospares);
2509 spin_unlock_irq(&mddev->write_lock);
2511 pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2512 mdname(mddev), mddev->in_sync);
2514 bitmap_update_sb(mddev->bitmap);
2515 rdev_for_each(rdev, mddev) {
2516 char b[BDEVNAME_SIZE];
2518 if (rdev->sb_loaded != 1)
2519 continue; /* no noise on spare devices */
2521 if (!test_bit(Faulty, &rdev->flags) &&
2522 rdev->saved_raid_disk == -1) {
2523 md_super_write(mddev,rdev,
2524 rdev->sb_start, rdev->sb_size,
2525 rdev->sb_page);
2526 pr_debug("md: (write) %s's sb offset: %llu\n",
2527 bdevname(rdev->bdev, b),
2528 (unsigned long long)rdev->sb_start);
2529 rdev->sb_events = mddev->events;
2530 if (rdev->badblocks.size) {
2531 md_super_write(mddev, rdev,
2532 rdev->badblocks.sector,
2533 rdev->badblocks.size << 9,
2534 rdev->bb_page);
2535 rdev->badblocks.size = 0;
2538 } else if (test_bit(Faulty, &rdev->flags))
2539 pr_debug("md: %s (skipping faulty)\n",
2540 bdevname(rdev->bdev, b));
2541 else
2542 pr_debug("(skipping incremental s/r ");
2544 if (mddev->level == LEVEL_MULTIPATH)
2545 /* only need to write one superblock... */
2546 break;
2548 md_super_wait(mddev);
2549 /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2551 spin_lock_irq(&mddev->write_lock);
2552 if (mddev->in_sync != sync_req ||
2553 test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2554 /* have to write it out again */
2555 spin_unlock_irq(&mddev->write_lock);
2556 goto repeat;
2558 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2559 spin_unlock_irq(&mddev->write_lock);
2560 wake_up(&mddev->sb_wait);
2561 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2562 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2564 rdev_for_each(rdev, mddev) {
2565 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2566 clear_bit(Blocked, &rdev->flags);
2568 if (any_badblocks_changed)
2569 md_ack_all_badblocks(&rdev->badblocks);
2570 clear_bit(BlockedBadBlocks, &rdev->flags);
2571 wake_up(&rdev->blocked_wait);
2575 /* words written to sysfs files may, or may not, be \n terminated.
2576 * We want to accept with case. For this we use cmd_match.
2578 static int cmd_match(const char *cmd, const char *str)
2580 /* See if cmd, written into a sysfs file, matches
2581 * str. They must either be the same, or cmd can
2582 * have a trailing newline
2584 while (*cmd && *str && *cmd == *str) {
2585 cmd++;
2586 str++;
2588 if (*cmd == '\n')
2589 cmd++;
2590 if (*str || *cmd)
2591 return 0;
2592 return 1;
2595 struct rdev_sysfs_entry {
2596 struct attribute attr;
2597 ssize_t (*show)(struct md_rdev *, char *);
2598 ssize_t (*store)(struct md_rdev *, const char *, size_t);
2601 static ssize_t
2602 state_show(struct md_rdev *rdev, char *page)
2604 char *sep = "";
2605 size_t len = 0;
2607 if (test_bit(Faulty, &rdev->flags) ||
2608 rdev->badblocks.unacked_exist) {
2609 len+= sprintf(page+len, "%sfaulty",sep);
2610 sep = ",";
2612 if (test_bit(In_sync, &rdev->flags)) {
2613 len += sprintf(page+len, "%sin_sync",sep);
2614 sep = ",";
2616 if (test_bit(WriteMostly, &rdev->flags)) {
2617 len += sprintf(page+len, "%swrite_mostly",sep);
2618 sep = ",";
2620 if (test_bit(Blocked, &rdev->flags) ||
2621 (rdev->badblocks.unacked_exist
2622 && !test_bit(Faulty, &rdev->flags))) {
2623 len += sprintf(page+len, "%sblocked", sep);
2624 sep = ",";
2626 if (!test_bit(Faulty, &rdev->flags) &&
2627 !test_bit(In_sync, &rdev->flags)) {
2628 len += sprintf(page+len, "%sspare", sep);
2629 sep = ",";
2631 if (test_bit(WriteErrorSeen, &rdev->flags)) {
2632 len += sprintf(page+len, "%swrite_error", sep);
2633 sep = ",";
2635 if (test_bit(WantReplacement, &rdev->flags)) {
2636 len += sprintf(page+len, "%swant_replacement", sep);
2637 sep = ",";
2639 if (test_bit(Replacement, &rdev->flags)) {
2640 len += sprintf(page+len, "%sreplacement", sep);
2641 sep = ",";
2644 return len+sprintf(page+len, "\n");
2647 static ssize_t
2648 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2650 /* can write
2651 * faulty - simulates an error
2652 * remove - disconnects the device
2653 * writemostly - sets write_mostly
2654 * -writemostly - clears write_mostly
2655 * blocked - sets the Blocked flags
2656 * -blocked - clears the Blocked and possibly simulates an error
2657 * insync - sets Insync providing device isn't active
2658 * write_error - sets WriteErrorSeen
2659 * -write_error - clears WriteErrorSeen
2661 int err = -EINVAL;
2662 if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2663 md_error(rdev->mddev, rdev);
2664 if (test_bit(Faulty, &rdev->flags))
2665 err = 0;
2666 else
2667 err = -EBUSY;
2668 } else if (cmd_match(buf, "remove")) {
2669 if (rdev->raid_disk >= 0)
2670 err = -EBUSY;
2671 else {
2672 struct mddev *mddev = rdev->mddev;
2673 kick_rdev_from_array(rdev);
2674 if (mddev->pers)
2675 md_update_sb(mddev, 1);
2676 md_new_event(mddev);
2677 err = 0;
2679 } else if (cmd_match(buf, "writemostly")) {
2680 set_bit(WriteMostly, &rdev->flags);
2681 err = 0;
2682 } else if (cmd_match(buf, "-writemostly")) {
2683 clear_bit(WriteMostly, &rdev->flags);
2684 err = 0;
2685 } else if (cmd_match(buf, "blocked")) {
2686 set_bit(Blocked, &rdev->flags);
2687 err = 0;
2688 } else if (cmd_match(buf, "-blocked")) {
2689 if (!test_bit(Faulty, &rdev->flags) &&
2690 rdev->badblocks.unacked_exist) {
2691 /* metadata handler doesn't understand badblocks,
2692 * so we need to fail the device
2694 md_error(rdev->mddev, rdev);
2696 clear_bit(Blocked, &rdev->flags);
2697 clear_bit(BlockedBadBlocks, &rdev->flags);
2698 wake_up(&rdev->blocked_wait);
2699 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2700 md_wakeup_thread(rdev->mddev->thread);
2702 err = 0;
2703 } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2704 set_bit(In_sync, &rdev->flags);
2705 err = 0;
2706 } else if (cmd_match(buf, "write_error")) {
2707 set_bit(WriteErrorSeen, &rdev->flags);
2708 err = 0;
2709 } else if (cmd_match(buf, "-write_error")) {
2710 clear_bit(WriteErrorSeen, &rdev->flags);
2711 err = 0;
2712 } else if (cmd_match(buf, "want_replacement")) {
2713 /* Any non-spare device that is not a replacement can
2714 * become want_replacement at any time, but we then need to
2715 * check if recovery is needed.
2717 if (rdev->raid_disk >= 0 &&
2718 !test_bit(Replacement, &rdev->flags))
2719 set_bit(WantReplacement, &rdev->flags);
2720 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2721 md_wakeup_thread(rdev->mddev->thread);
2722 err = 0;
2723 } else if (cmd_match(buf, "-want_replacement")) {
2724 /* Clearing 'want_replacement' is always allowed.
2725 * Once replacements starts it is too late though.
2727 err = 0;
2728 clear_bit(WantReplacement, &rdev->flags);
2729 } else if (cmd_match(buf, "replacement")) {
2730 /* Can only set a device as a replacement when array has not
2731 * yet been started. Once running, replacement is automatic
2732 * from spares, or by assigning 'slot'.
2734 if (rdev->mddev->pers)
2735 err = -EBUSY;
2736 else {
2737 set_bit(Replacement, &rdev->flags);
2738 err = 0;
2740 } else if (cmd_match(buf, "-replacement")) {
2741 /* Similarly, can only clear Replacement before start */
2742 if (rdev->mddev->pers)
2743 err = -EBUSY;
2744 else {
2745 clear_bit(Replacement, &rdev->flags);
2746 err = 0;
2749 if (!err)
2750 sysfs_notify_dirent_safe(rdev->sysfs_state);
2751 return err ? err : len;
2753 static struct rdev_sysfs_entry rdev_state =
2754 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
2756 static ssize_t
2757 errors_show(struct md_rdev *rdev, char *page)
2759 return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2762 static ssize_t
2763 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2765 char *e;
2766 unsigned long n = simple_strtoul(buf, &e, 10);
2767 if (*buf && (*e == 0 || *e == '\n')) {
2768 atomic_set(&rdev->corrected_errors, n);
2769 return len;
2771 return -EINVAL;
2773 static struct rdev_sysfs_entry rdev_errors =
2774 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2776 static ssize_t
2777 slot_show(struct md_rdev *rdev, char *page)
2779 if (rdev->raid_disk < 0)
2780 return sprintf(page, "none\n");
2781 else
2782 return sprintf(page, "%d\n", rdev->raid_disk);
2785 static ssize_t
2786 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2788 char *e;
2789 int err;
2790 int slot = simple_strtoul(buf, &e, 10);
2791 if (strncmp(buf, "none", 4)==0)
2792 slot = -1;
2793 else if (e==buf || (*e && *e!= '\n'))
2794 return -EINVAL;
2795 if (rdev->mddev->pers && slot == -1) {
2796 /* Setting 'slot' on an active array requires also
2797 * updating the 'rd%d' link, and communicating
2798 * with the personality with ->hot_*_disk.
2799 * For now we only support removing
2800 * failed/spare devices. This normally happens automatically,
2801 * but not when the metadata is externally managed.
2803 if (rdev->raid_disk == -1)
2804 return -EEXIST;
2805 /* personality does all needed checks */
2806 if (rdev->mddev->pers->hot_remove_disk == NULL)
2807 return -EINVAL;
2808 clear_bit(Blocked, &rdev->flags);
2809 remove_and_add_spares(rdev->mddev, rdev);
2810 if (rdev->raid_disk >= 0)
2811 return -EBUSY;
2812 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2813 md_wakeup_thread(rdev->mddev->thread);
2814 } else if (rdev->mddev->pers) {
2815 /* Activating a spare .. or possibly reactivating
2816 * if we ever get bitmaps working here.
2819 if (rdev->raid_disk != -1)
2820 return -EBUSY;
2822 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2823 return -EBUSY;
2825 if (rdev->mddev->pers->hot_add_disk == NULL)
2826 return -EINVAL;
2828 if (slot >= rdev->mddev->raid_disks &&
2829 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2830 return -ENOSPC;
2832 rdev->raid_disk = slot;
2833 if (test_bit(In_sync, &rdev->flags))
2834 rdev->saved_raid_disk = slot;
2835 else
2836 rdev->saved_raid_disk = -1;
2837 clear_bit(In_sync, &rdev->flags);
2838 clear_bit(Bitmap_sync, &rdev->flags);
2839 err = rdev->mddev->pers->
2840 hot_add_disk(rdev->mddev, rdev);
2841 if (err) {
2842 rdev->raid_disk = -1;
2843 return err;
2844 } else
2845 sysfs_notify_dirent_safe(rdev->sysfs_state);
2846 if (sysfs_link_rdev(rdev->mddev, rdev))
2847 /* failure here is OK */;
2848 /* don't wakeup anyone, leave that to userspace. */
2849 } else {
2850 if (slot >= rdev->mddev->raid_disks &&
2851 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2852 return -ENOSPC;
2853 rdev->raid_disk = slot;
2854 /* assume it is working */
2855 clear_bit(Faulty, &rdev->flags);
2856 clear_bit(WriteMostly, &rdev->flags);
2857 set_bit(In_sync, &rdev->flags);
2858 sysfs_notify_dirent_safe(rdev->sysfs_state);
2860 return len;
2864 static struct rdev_sysfs_entry rdev_slot =
2865 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2867 static ssize_t
2868 offset_show(struct md_rdev *rdev, char *page)
2870 return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2873 static ssize_t
2874 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
2876 unsigned long long offset;
2877 if (strict_strtoull(buf, 10, &offset) < 0)
2878 return -EINVAL;
2879 if (rdev->mddev->pers && rdev->raid_disk >= 0)
2880 return -EBUSY;
2881 if (rdev->sectors && rdev->mddev->external)
2882 /* Must set offset before size, so overlap checks
2883 * can be sane */
2884 return -EBUSY;
2885 rdev->data_offset = offset;
2886 rdev->new_data_offset = offset;
2887 return len;
2890 static struct rdev_sysfs_entry rdev_offset =
2891 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2893 static ssize_t new_offset_show(struct md_rdev *rdev, char *page)
2895 return sprintf(page, "%llu\n",
2896 (unsigned long long)rdev->new_data_offset);
2899 static ssize_t new_offset_store(struct md_rdev *rdev,
2900 const char *buf, size_t len)
2902 unsigned long long new_offset;
2903 struct mddev *mddev = rdev->mddev;
2905 if (strict_strtoull(buf, 10, &new_offset) < 0)
2906 return -EINVAL;
2908 if (mddev->sync_thread)
2909 return -EBUSY;
2910 if (new_offset == rdev->data_offset)
2911 /* reset is always permitted */
2913 else if (new_offset > rdev->data_offset) {
2914 /* must not push array size beyond rdev_sectors */
2915 if (new_offset - rdev->data_offset
2916 + mddev->dev_sectors > rdev->sectors)
2917 return -E2BIG;
2919 /* Metadata worries about other space details. */
2921 /* decreasing the offset is inconsistent with a backwards
2922 * reshape.
2924 if (new_offset < rdev->data_offset &&
2925 mddev->reshape_backwards)
2926 return -EINVAL;
2927 /* Increasing offset is inconsistent with forwards
2928 * reshape. reshape_direction should be set to
2929 * 'backwards' first.
2931 if (new_offset > rdev->data_offset &&
2932 !mddev->reshape_backwards)
2933 return -EINVAL;
2935 if (mddev->pers && mddev->persistent &&
2936 !super_types[mddev->major_version]
2937 .allow_new_offset(rdev, new_offset))
2938 return -E2BIG;
2939 rdev->new_data_offset = new_offset;
2940 if (new_offset > rdev->data_offset)
2941 mddev->reshape_backwards = 1;
2942 else if (new_offset < rdev->data_offset)
2943 mddev->reshape_backwards = 0;
2945 return len;
2947 static struct rdev_sysfs_entry rdev_new_offset =
2948 __ATTR(new_offset, S_IRUGO|S_IWUSR, new_offset_show, new_offset_store);
2950 static ssize_t
2951 rdev_size_show(struct md_rdev *rdev, char *page)
2953 return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2956 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2958 /* check if two start/length pairs overlap */
2959 if (s1+l1 <= s2)
2960 return 0;
2961 if (s2+l2 <= s1)
2962 return 0;
2963 return 1;
2966 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2968 unsigned long long blocks;
2969 sector_t new;
2971 if (strict_strtoull(buf, 10, &blocks) < 0)
2972 return -EINVAL;
2974 if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2975 return -EINVAL; /* sector conversion overflow */
2977 new = blocks * 2;
2978 if (new != blocks * 2)
2979 return -EINVAL; /* unsigned long long to sector_t overflow */
2981 *sectors = new;
2982 return 0;
2985 static ssize_t
2986 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
2988 struct mddev *my_mddev = rdev->mddev;
2989 sector_t oldsectors = rdev->sectors;
2990 sector_t sectors;
2992 if (strict_blocks_to_sectors(buf, &sectors) < 0)
2993 return -EINVAL;
2994 if (rdev->data_offset != rdev->new_data_offset)
2995 return -EINVAL; /* too confusing */
2996 if (my_mddev->pers && rdev->raid_disk >= 0) {
2997 if (my_mddev->persistent) {
2998 sectors = super_types[my_mddev->major_version].
2999 rdev_size_change(rdev, sectors);
3000 if (!sectors)
3001 return -EBUSY;
3002 } else if (!sectors)
3003 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
3004 rdev->data_offset;
3005 if (!my_mddev->pers->resize)
3006 /* Cannot change size for RAID0 or Linear etc */
3007 return -EINVAL;
3009 if (sectors < my_mddev->dev_sectors)
3010 return -EINVAL; /* component must fit device */
3012 rdev->sectors = sectors;
3013 if (sectors > oldsectors && my_mddev->external) {
3014 /* need to check that all other rdevs with the same ->bdev
3015 * do not overlap. We need to unlock the mddev to avoid
3016 * a deadlock. We have already changed rdev->sectors, and if
3017 * we have to change it back, we will have the lock again.
3019 struct mddev *mddev;
3020 int overlap = 0;
3021 struct list_head *tmp;
3023 mddev_unlock(my_mddev);
3024 for_each_mddev(mddev, tmp) {
3025 struct md_rdev *rdev2;
3027 mddev_lock(mddev);
3028 rdev_for_each(rdev2, mddev)
3029 if (rdev->bdev == rdev2->bdev &&
3030 rdev != rdev2 &&
3031 overlaps(rdev->data_offset, rdev->sectors,
3032 rdev2->data_offset,
3033 rdev2->sectors)) {
3034 overlap = 1;
3035 break;
3037 mddev_unlock(mddev);
3038 if (overlap) {
3039 mddev_put(mddev);
3040 break;
3043 mddev_lock(my_mddev);
3044 if (overlap) {
3045 /* Someone else could have slipped in a size
3046 * change here, but doing so is just silly.
3047 * We put oldsectors back because we *know* it is
3048 * safe, and trust userspace not to race with
3049 * itself
3051 rdev->sectors = oldsectors;
3052 return -EBUSY;
3055 return len;
3058 static struct rdev_sysfs_entry rdev_size =
3059 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
3062 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
3064 unsigned long long recovery_start = rdev->recovery_offset;
3066 if (test_bit(In_sync, &rdev->flags) ||
3067 recovery_start == MaxSector)
3068 return sprintf(page, "none\n");
3070 return sprintf(page, "%llu\n", recovery_start);
3073 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
3075 unsigned long long recovery_start;
3077 if (cmd_match(buf, "none"))
3078 recovery_start = MaxSector;
3079 else if (strict_strtoull(buf, 10, &recovery_start))
3080 return -EINVAL;
3082 if (rdev->mddev->pers &&
3083 rdev->raid_disk >= 0)
3084 return -EBUSY;
3086 rdev->recovery_offset = recovery_start;
3087 if (recovery_start == MaxSector)
3088 set_bit(In_sync, &rdev->flags);
3089 else
3090 clear_bit(In_sync, &rdev->flags);
3091 return len;
3094 static struct rdev_sysfs_entry rdev_recovery_start =
3095 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
3098 static ssize_t
3099 badblocks_show(struct badblocks *bb, char *page, int unack);
3100 static ssize_t
3101 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack);
3103 static ssize_t bb_show(struct md_rdev *rdev, char *page)
3105 return badblocks_show(&rdev->badblocks, page, 0);
3107 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
3109 int rv = badblocks_store(&rdev->badblocks, page, len, 0);
3110 /* Maybe that ack was all we needed */
3111 if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
3112 wake_up(&rdev->blocked_wait);
3113 return rv;
3115 static struct rdev_sysfs_entry rdev_bad_blocks =
3116 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
3119 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
3121 return badblocks_show(&rdev->badblocks, page, 1);
3123 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3125 return badblocks_store(&rdev->badblocks, page, len, 1);
3127 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3128 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3130 static struct attribute *rdev_default_attrs[] = {
3131 &rdev_state.attr,
3132 &rdev_errors.attr,
3133 &rdev_slot.attr,
3134 &rdev_offset.attr,
3135 &rdev_new_offset.attr,
3136 &rdev_size.attr,
3137 &rdev_recovery_start.attr,
3138 &rdev_bad_blocks.attr,
3139 &rdev_unack_bad_blocks.attr,
3140 NULL,
3142 static ssize_t
3143 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3145 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3146 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3147 struct mddev *mddev = rdev->mddev;
3148 ssize_t rv;
3150 if (!entry->show)
3151 return -EIO;
3153 rv = mddev ? mddev_lock(mddev) : -EBUSY;
3154 if (!rv) {
3155 if (rdev->mddev == NULL)
3156 rv = -EBUSY;
3157 else
3158 rv = entry->show(rdev, page);
3159 mddev_unlock(mddev);
3161 return rv;
3164 static ssize_t
3165 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3166 const char *page, size_t length)
3168 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3169 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3170 ssize_t rv;
3171 struct mddev *mddev = rdev->mddev;
3173 if (!entry->store)
3174 return -EIO;
3175 if (!capable(CAP_SYS_ADMIN))
3176 return -EACCES;
3177 rv = mddev ? mddev_lock(mddev): -EBUSY;
3178 if (!rv) {
3179 if (rdev->mddev == NULL)
3180 rv = -EBUSY;
3181 else
3182 rv = entry->store(rdev, page, length);
3183 mddev_unlock(mddev);
3185 return rv;
3188 static void rdev_free(struct kobject *ko)
3190 struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3191 kfree(rdev);
3193 static const struct sysfs_ops rdev_sysfs_ops = {
3194 .show = rdev_attr_show,
3195 .store = rdev_attr_store,
3197 static struct kobj_type rdev_ktype = {
3198 .release = rdev_free,
3199 .sysfs_ops = &rdev_sysfs_ops,
3200 .default_attrs = rdev_default_attrs,
3203 int md_rdev_init(struct md_rdev *rdev)
3205 rdev->desc_nr = -1;
3206 rdev->saved_raid_disk = -1;
3207 rdev->raid_disk = -1;
3208 rdev->flags = 0;
3209 rdev->data_offset = 0;
3210 rdev->new_data_offset = 0;
3211 rdev->sb_events = 0;
3212 rdev->last_read_error.tv_sec = 0;
3213 rdev->last_read_error.tv_nsec = 0;
3214 rdev->sb_loaded = 0;
3215 rdev->bb_page = NULL;
3216 atomic_set(&rdev->nr_pending, 0);
3217 atomic_set(&rdev->read_errors, 0);
3218 atomic_set(&rdev->corrected_errors, 0);
3220 INIT_LIST_HEAD(&rdev->same_set);
3221 init_waitqueue_head(&rdev->blocked_wait);
3223 /* Add space to store bad block list.
3224 * This reserves the space even on arrays where it cannot
3225 * be used - I wonder if that matters
3227 rdev->badblocks.count = 0;
3228 rdev->badblocks.shift = -1; /* disabled until explicitly enabled */
3229 rdev->badblocks.page = kmalloc(PAGE_SIZE, GFP_KERNEL);
3230 seqlock_init(&rdev->badblocks.lock);
3231 if (rdev->badblocks.page == NULL)
3232 return -ENOMEM;
3234 return 0;
3236 EXPORT_SYMBOL_GPL(md_rdev_init);
3238 * Import a device. If 'super_format' >= 0, then sanity check the superblock
3240 * mark the device faulty if:
3242 * - the device is nonexistent (zero size)
3243 * - the device has no valid superblock
3245 * a faulty rdev _never_ has rdev->sb set.
3247 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3249 char b[BDEVNAME_SIZE];
3250 int err;
3251 struct md_rdev *rdev;
3252 sector_t size;
3254 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3255 if (!rdev) {
3256 printk(KERN_ERR "md: could not alloc mem for new device!\n");
3257 return ERR_PTR(-ENOMEM);
3260 err = md_rdev_init(rdev);
3261 if (err)
3262 goto abort_free;
3263 err = alloc_disk_sb(rdev);
3264 if (err)
3265 goto abort_free;
3267 err = lock_rdev(rdev, newdev, super_format == -2);
3268 if (err)
3269 goto abort_free;
3271 kobject_init(&rdev->kobj, &rdev_ktype);
3273 size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3274 if (!size) {
3275 printk(KERN_WARNING
3276 "md: %s has zero or unknown size, marking faulty!\n",
3277 bdevname(rdev->bdev,b));
3278 err = -EINVAL;
3279 goto abort_free;
3282 if (super_format >= 0) {
3283 err = super_types[super_format].
3284 load_super(rdev, NULL, super_minor);
3285 if (err == -EINVAL) {
3286 printk(KERN_WARNING
3287 "md: %s does not have a valid v%d.%d "
3288 "superblock, not importing!\n",
3289 bdevname(rdev->bdev,b),
3290 super_format, super_minor);
3291 goto abort_free;
3293 if (err < 0) {
3294 printk(KERN_WARNING
3295 "md: could not read %s's sb, not importing!\n",
3296 bdevname(rdev->bdev,b));
3297 goto abort_free;
3301 return rdev;
3303 abort_free:
3304 if (rdev->bdev)
3305 unlock_rdev(rdev);
3306 md_rdev_clear(rdev);
3307 kfree(rdev);
3308 return ERR_PTR(err);
3312 * Check a full RAID array for plausibility
3316 static void analyze_sbs(struct mddev * mddev)
3318 int i;
3319 struct md_rdev *rdev, *freshest, *tmp;
3320 char b[BDEVNAME_SIZE];
3322 freshest = NULL;
3323 rdev_for_each_safe(rdev, tmp, mddev)
3324 switch (super_types[mddev->major_version].
3325 load_super(rdev, freshest, mddev->minor_version)) {
3326 case 1:
3327 freshest = rdev;
3328 break;
3329 case 0:
3330 break;
3331 default:
3332 printk( KERN_ERR \
3333 "md: fatal superblock inconsistency in %s"
3334 " -- removing from array\n",
3335 bdevname(rdev->bdev,b));
3336 kick_rdev_from_array(rdev);
3340 super_types[mddev->major_version].
3341 validate_super(mddev, freshest);
3343 i = 0;
3344 rdev_for_each_safe(rdev, tmp, mddev) {
3345 if (mddev->max_disks &&
3346 (rdev->desc_nr >= mddev->max_disks ||
3347 i > mddev->max_disks)) {
3348 printk(KERN_WARNING
3349 "md: %s: %s: only %d devices permitted\n",
3350 mdname(mddev), bdevname(rdev->bdev, b),
3351 mddev->max_disks);
3352 kick_rdev_from_array(rdev);
3353 continue;
3355 if (rdev != freshest)
3356 if (super_types[mddev->major_version].
3357 validate_super(mddev, rdev)) {
3358 printk(KERN_WARNING "md: kicking non-fresh %s"
3359 " from array!\n",
3360 bdevname(rdev->bdev,b));
3361 kick_rdev_from_array(rdev);
3362 continue;
3364 if (mddev->level == LEVEL_MULTIPATH) {
3365 rdev->desc_nr = i++;
3366 rdev->raid_disk = rdev->desc_nr;
3367 set_bit(In_sync, &rdev->flags);
3368 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
3369 rdev->raid_disk = -1;
3370 clear_bit(In_sync, &rdev->flags);
3375 /* Read a fixed-point number.
3376 * Numbers in sysfs attributes should be in "standard" units where
3377 * possible, so time should be in seconds.
3378 * However we internally use a a much smaller unit such as
3379 * milliseconds or jiffies.
3380 * This function takes a decimal number with a possible fractional
3381 * component, and produces an integer which is the result of
3382 * multiplying that number by 10^'scale'.
3383 * all without any floating-point arithmetic.
3385 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3387 unsigned long result = 0;
3388 long decimals = -1;
3389 while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3390 if (*cp == '.')
3391 decimals = 0;
3392 else if (decimals < scale) {
3393 unsigned int value;
3394 value = *cp - '0';
3395 result = result * 10 + value;
3396 if (decimals >= 0)
3397 decimals++;
3399 cp++;
3401 if (*cp == '\n')
3402 cp++;
3403 if (*cp)
3404 return -EINVAL;
3405 if (decimals < 0)
3406 decimals = 0;
3407 while (decimals < scale) {
3408 result *= 10;
3409 decimals ++;
3411 *res = result;
3412 return 0;
3416 static void md_safemode_timeout(unsigned long data);
3418 static ssize_t
3419 safe_delay_show(struct mddev *mddev, char *page)
3421 int msec = (mddev->safemode_delay*1000)/HZ;
3422 return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3424 static ssize_t
3425 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3427 unsigned long msec;
3429 if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3430 return -EINVAL;
3431 if (msec == 0)
3432 mddev->safemode_delay = 0;
3433 else {
3434 unsigned long old_delay = mddev->safemode_delay;
3435 mddev->safemode_delay = (msec*HZ)/1000;
3436 if (mddev->safemode_delay == 0)
3437 mddev->safemode_delay = 1;
3438 if (mddev->safemode_delay < old_delay)
3439 md_safemode_timeout((unsigned long)mddev);
3441 return len;
3443 static struct md_sysfs_entry md_safe_delay =
3444 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3446 static ssize_t
3447 level_show(struct mddev *mddev, char *page)
3449 struct md_personality *p = mddev->pers;
3450 if (p)
3451 return sprintf(page, "%s\n", p->name);
3452 else if (mddev->clevel[0])
3453 return sprintf(page, "%s\n", mddev->clevel);
3454 else if (mddev->level != LEVEL_NONE)
3455 return sprintf(page, "%d\n", mddev->level);
3456 else
3457 return 0;
3460 static ssize_t
3461 level_store(struct mddev *mddev, const char *buf, size_t len)
3463 char clevel[16];
3464 ssize_t rv = len;
3465 struct md_personality *pers;
3466 long level;
3467 void *priv;
3468 struct md_rdev *rdev;
3470 if (mddev->pers == NULL) {
3471 if (len == 0)
3472 return 0;
3473 if (len >= sizeof(mddev->clevel))
3474 return -ENOSPC;
3475 strncpy(mddev->clevel, buf, len);
3476 if (mddev->clevel[len-1] == '\n')
3477 len--;
3478 mddev->clevel[len] = 0;
3479 mddev->level = LEVEL_NONE;
3480 return rv;
3483 /* request to change the personality. Need to ensure:
3484 * - array is not engaged in resync/recovery/reshape
3485 * - old personality can be suspended
3486 * - new personality will access other array.
3489 if (mddev->sync_thread ||
3490 mddev->reshape_position != MaxSector ||
3491 mddev->sysfs_active)
3492 return -EBUSY;
3494 if (!mddev->pers->quiesce) {
3495 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3496 mdname(mddev), mddev->pers->name);
3497 return -EINVAL;
3500 /* Now find the new personality */
3501 if (len == 0 || len >= sizeof(clevel))
3502 return -EINVAL;
3503 strncpy(clevel, buf, len);
3504 if (clevel[len-1] == '\n')
3505 len--;
3506 clevel[len] = 0;
3507 if (strict_strtol(clevel, 10, &level))
3508 level = LEVEL_NONE;
3510 if (request_module("md-%s", clevel) != 0)
3511 request_module("md-level-%s", clevel);
3512 spin_lock(&pers_lock);
3513 pers = find_pers(level, clevel);
3514 if (!pers || !try_module_get(pers->owner)) {
3515 spin_unlock(&pers_lock);
3516 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3517 return -EINVAL;
3519 spin_unlock(&pers_lock);
3521 if (pers == mddev->pers) {
3522 /* Nothing to do! */
3523 module_put(pers->owner);
3524 return rv;
3526 if (!pers->takeover) {
3527 module_put(pers->owner);
3528 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3529 mdname(mddev), clevel);
3530 return -EINVAL;
3533 rdev_for_each(rdev, mddev)
3534 rdev->new_raid_disk = rdev->raid_disk;
3536 /* ->takeover must set new_* and/or delta_disks
3537 * if it succeeds, and may set them when it fails.
3539 priv = pers->takeover(mddev);
3540 if (IS_ERR(priv)) {
3541 mddev->new_level = mddev->level;
3542 mddev->new_layout = mddev->layout;
3543 mddev->new_chunk_sectors = mddev->chunk_sectors;
3544 mddev->raid_disks -= mddev->delta_disks;
3545 mddev->delta_disks = 0;
3546 mddev->reshape_backwards = 0;
3547 module_put(pers->owner);
3548 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3549 mdname(mddev), clevel);
3550 return PTR_ERR(priv);
3553 /* Looks like we have a winner */
3554 mddev_suspend(mddev);
3555 mddev->pers->stop(mddev);
3557 if (mddev->pers->sync_request == NULL &&
3558 pers->sync_request != NULL) {
3559 /* need to add the md_redundancy_group */
3560 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3561 printk(KERN_WARNING
3562 "md: cannot register extra attributes for %s\n",
3563 mdname(mddev));
3564 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, NULL, "sync_action");
3566 if (mddev->pers->sync_request != NULL &&
3567 pers->sync_request == NULL) {
3568 /* need to remove the md_redundancy_group */
3569 if (mddev->to_remove == NULL)
3570 mddev->to_remove = &md_redundancy_group;
3573 if (mddev->pers->sync_request == NULL &&
3574 mddev->external) {
3575 /* We are converting from a no-redundancy array
3576 * to a redundancy array and metadata is managed
3577 * externally so we need to be sure that writes
3578 * won't block due to a need to transition
3579 * clean->dirty
3580 * until external management is started.
3582 mddev->in_sync = 0;
3583 mddev->safemode_delay = 0;
3584 mddev->safemode = 0;
3587 rdev_for_each(rdev, mddev) {
3588 if (rdev->raid_disk < 0)
3589 continue;
3590 if (rdev->new_raid_disk >= mddev->raid_disks)
3591 rdev->new_raid_disk = -1;
3592 if (rdev->new_raid_disk == rdev->raid_disk)
3593 continue;
3594 sysfs_unlink_rdev(mddev, rdev);
3596 rdev_for_each(rdev, mddev) {
3597 if (rdev->raid_disk < 0)
3598 continue;
3599 if (rdev->new_raid_disk == rdev->raid_disk)
3600 continue;
3601 rdev->raid_disk = rdev->new_raid_disk;
3602 if (rdev->raid_disk < 0)
3603 clear_bit(In_sync, &rdev->flags);
3604 else {
3605 if (sysfs_link_rdev(mddev, rdev))
3606 printk(KERN_WARNING "md: cannot register rd%d"
3607 " for %s after level change\n",
3608 rdev->raid_disk, mdname(mddev));
3612 module_put(mddev->pers->owner);
3613 mddev->pers = pers;
3614 mddev->private = priv;
3615 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3616 mddev->level = mddev->new_level;
3617 mddev->layout = mddev->new_layout;
3618 mddev->chunk_sectors = mddev->new_chunk_sectors;
3619 mddev->delta_disks = 0;
3620 mddev->reshape_backwards = 0;
3621 mddev->degraded = 0;
3622 if (mddev->pers->sync_request == NULL) {
3623 /* this is now an array without redundancy, so
3624 * it must always be in_sync
3626 mddev->in_sync = 1;
3627 del_timer_sync(&mddev->safemode_timer);
3629 blk_set_stacking_limits(&mddev->queue->limits);
3630 pers->run(mddev);
3631 set_bit(MD_CHANGE_DEVS, &mddev->flags);
3632 mddev_resume(mddev);
3633 sysfs_notify(&mddev->kobj, NULL, "level");
3634 md_new_event(mddev);
3635 return rv;
3638 static struct md_sysfs_entry md_level =
3639 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3642 static ssize_t
3643 layout_show(struct mddev *mddev, char *page)
3645 /* just a number, not meaningful for all levels */
3646 if (mddev->reshape_position != MaxSector &&
3647 mddev->layout != mddev->new_layout)
3648 return sprintf(page, "%d (%d)\n",
3649 mddev->new_layout, mddev->layout);
3650 return sprintf(page, "%d\n", mddev->layout);
3653 static ssize_t
3654 layout_store(struct mddev *mddev, const char *buf, size_t len)
3656 char *e;
3657 unsigned long n = simple_strtoul(buf, &e, 10);
3659 if (!*buf || (*e && *e != '\n'))
3660 return -EINVAL;
3662 if (mddev->pers) {
3663 int err;
3664 if (mddev->pers->check_reshape == NULL)
3665 return -EBUSY;
3666 mddev->new_layout = n;
3667 err = mddev->pers->check_reshape(mddev);
3668 if (err) {
3669 mddev->new_layout = mddev->layout;
3670 return err;
3672 } else {
3673 mddev->new_layout = n;
3674 if (mddev->reshape_position == MaxSector)
3675 mddev->layout = n;
3677 return len;
3679 static struct md_sysfs_entry md_layout =
3680 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3683 static ssize_t
3684 raid_disks_show(struct mddev *mddev, char *page)
3686 if (mddev->raid_disks == 0)
3687 return 0;
3688 if (mddev->reshape_position != MaxSector &&
3689 mddev->delta_disks != 0)
3690 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3691 mddev->raid_disks - mddev->delta_disks);
3692 return sprintf(page, "%d\n", mddev->raid_disks);
3695 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3697 static ssize_t
3698 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3700 char *e;
3701 int rv = 0;
3702 unsigned long n = simple_strtoul(buf, &e, 10);
3704 if (!*buf || (*e && *e != '\n'))
3705 return -EINVAL;
3707 if (mddev->pers)
3708 rv = update_raid_disks(mddev, n);
3709 else if (mddev->reshape_position != MaxSector) {
3710 struct md_rdev *rdev;
3711 int olddisks = mddev->raid_disks - mddev->delta_disks;
3713 rdev_for_each(rdev, mddev) {
3714 if (olddisks < n &&
3715 rdev->data_offset < rdev->new_data_offset)
3716 return -EINVAL;
3717 if (olddisks > n &&
3718 rdev->data_offset > rdev->new_data_offset)
3719 return -EINVAL;
3721 mddev->delta_disks = n - olddisks;
3722 mddev->raid_disks = n;
3723 mddev->reshape_backwards = (mddev->delta_disks < 0);
3724 } else
3725 mddev->raid_disks = n;
3726 return rv ? rv : len;
3728 static struct md_sysfs_entry md_raid_disks =
3729 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3731 static ssize_t
3732 chunk_size_show(struct mddev *mddev, char *page)
3734 if (mddev->reshape_position != MaxSector &&
3735 mddev->chunk_sectors != mddev->new_chunk_sectors)
3736 return sprintf(page, "%d (%d)\n",
3737 mddev->new_chunk_sectors << 9,
3738 mddev->chunk_sectors << 9);
3739 return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3742 static ssize_t
3743 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3745 char *e;
3746 unsigned long n = simple_strtoul(buf, &e, 10);
3748 if (!*buf || (*e && *e != '\n'))
3749 return -EINVAL;
3751 if (mddev->pers) {
3752 int err;
3753 if (mddev->pers->check_reshape == NULL)
3754 return -EBUSY;
3755 mddev->new_chunk_sectors = n >> 9;
3756 err = mddev->pers->check_reshape(mddev);
3757 if (err) {
3758 mddev->new_chunk_sectors = mddev->chunk_sectors;
3759 return err;
3761 } else {
3762 mddev->new_chunk_sectors = n >> 9;
3763 if (mddev->reshape_position == MaxSector)
3764 mddev->chunk_sectors = n >> 9;
3766 return len;
3768 static struct md_sysfs_entry md_chunk_size =
3769 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3771 static ssize_t
3772 resync_start_show(struct mddev *mddev, char *page)
3774 if (mddev->recovery_cp == MaxSector)
3775 return sprintf(page, "none\n");
3776 return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3779 static ssize_t
3780 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
3782 char *e;
3783 unsigned long long n = simple_strtoull(buf, &e, 10);
3785 if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3786 return -EBUSY;
3787 if (cmd_match(buf, "none"))
3788 n = MaxSector;
3789 else if (!*buf || (*e && *e != '\n'))
3790 return -EINVAL;
3792 mddev->recovery_cp = n;
3793 if (mddev->pers)
3794 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3795 return len;
3797 static struct md_sysfs_entry md_resync_start =
3798 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
3801 * The array state can be:
3803 * clear
3804 * No devices, no size, no level
3805 * Equivalent to STOP_ARRAY ioctl
3806 * inactive
3807 * May have some settings, but array is not active
3808 * all IO results in error
3809 * When written, doesn't tear down array, but just stops it
3810 * suspended (not supported yet)
3811 * All IO requests will block. The array can be reconfigured.
3812 * Writing this, if accepted, will block until array is quiescent
3813 * readonly
3814 * no resync can happen. no superblocks get written.
3815 * write requests fail
3816 * read-auto
3817 * like readonly, but behaves like 'clean' on a write request.
3819 * clean - no pending writes, but otherwise active.
3820 * When written to inactive array, starts without resync
3821 * If a write request arrives then
3822 * if metadata is known, mark 'dirty' and switch to 'active'.
3823 * if not known, block and switch to write-pending
3824 * If written to an active array that has pending writes, then fails.
3825 * active
3826 * fully active: IO and resync can be happening.
3827 * When written to inactive array, starts with resync
3829 * write-pending
3830 * clean, but writes are blocked waiting for 'active' to be written.
3832 * active-idle
3833 * like active, but no writes have been seen for a while (100msec).
3836 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3837 write_pending, active_idle, bad_word};
3838 static char *array_states[] = {
3839 "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3840 "write-pending", "active-idle", NULL };
3842 static int match_word(const char *word, char **list)
3844 int n;
3845 for (n=0; list[n]; n++)
3846 if (cmd_match(word, list[n]))
3847 break;
3848 return n;
3851 static ssize_t
3852 array_state_show(struct mddev *mddev, char *page)
3854 enum array_state st = inactive;
3856 if (mddev->pers)
3857 switch(mddev->ro) {
3858 case 1:
3859 st = readonly;
3860 break;
3861 case 2:
3862 st = read_auto;
3863 break;
3864 case 0:
3865 if (mddev->in_sync)
3866 st = clean;
3867 else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3868 st = write_pending;
3869 else if (mddev->safemode)
3870 st = active_idle;
3871 else
3872 st = active;
3874 else {
3875 if (list_empty(&mddev->disks) &&
3876 mddev->raid_disks == 0 &&
3877 mddev->dev_sectors == 0)
3878 st = clear;
3879 else
3880 st = inactive;
3882 return sprintf(page, "%s\n", array_states[st]);
3885 static int do_md_stop(struct mddev * mddev, int ro, struct block_device *bdev);
3886 static int md_set_readonly(struct mddev * mddev, struct block_device *bdev);
3887 static int do_md_run(struct mddev * mddev);
3888 static int restart_array(struct mddev *mddev);
3890 static ssize_t
3891 array_state_store(struct mddev *mddev, const char *buf, size_t len)
3893 int err = -EINVAL;
3894 enum array_state st = match_word(buf, array_states);
3895 switch(st) {
3896 case bad_word:
3897 break;
3898 case clear:
3899 /* stopping an active array */
3900 err = do_md_stop(mddev, 0, NULL);
3901 break;
3902 case inactive:
3903 /* stopping an active array */
3904 if (mddev->pers)
3905 err = do_md_stop(mddev, 2, NULL);
3906 else
3907 err = 0; /* already inactive */
3908 break;
3909 case suspended:
3910 break; /* not supported yet */
3911 case readonly:
3912 if (mddev->pers)
3913 err = md_set_readonly(mddev, NULL);
3914 else {
3915 mddev->ro = 1;
3916 set_disk_ro(mddev->gendisk, 1);
3917 err = do_md_run(mddev);
3919 break;
3920 case read_auto:
3921 if (mddev->pers) {
3922 if (mddev->ro == 0)
3923 err = md_set_readonly(mddev, NULL);
3924 else if (mddev->ro == 1)
3925 err = restart_array(mddev);
3926 if (err == 0) {
3927 mddev->ro = 2;
3928 set_disk_ro(mddev->gendisk, 0);
3930 } else {
3931 mddev->ro = 2;
3932 err = do_md_run(mddev);
3934 break;
3935 case clean:
3936 if (mddev->pers) {
3937 restart_array(mddev);
3938 spin_lock_irq(&mddev->write_lock);
3939 if (atomic_read(&mddev->writes_pending) == 0) {
3940 if (mddev->in_sync == 0) {
3941 mddev->in_sync = 1;
3942 if (mddev->safemode == 1)
3943 mddev->safemode = 0;
3944 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3946 err = 0;
3947 } else
3948 err = -EBUSY;
3949 spin_unlock_irq(&mddev->write_lock);
3950 } else
3951 err = -EINVAL;
3952 break;
3953 case active:
3954 if (mddev->pers) {
3955 restart_array(mddev);
3956 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3957 wake_up(&mddev->sb_wait);
3958 err = 0;
3959 } else {
3960 mddev->ro = 0;
3961 set_disk_ro(mddev->gendisk, 0);
3962 err = do_md_run(mddev);
3964 break;
3965 case write_pending:
3966 case active_idle:
3967 /* these cannot be set */
3968 break;
3970 if (err)
3971 return err;
3972 else {
3973 if (mddev->hold_active == UNTIL_IOCTL)
3974 mddev->hold_active = 0;
3975 sysfs_notify_dirent_safe(mddev->sysfs_state);
3976 return len;
3979 static struct md_sysfs_entry md_array_state =
3980 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3982 static ssize_t
3983 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
3984 return sprintf(page, "%d\n",
3985 atomic_read(&mddev->max_corr_read_errors));
3988 static ssize_t
3989 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
3991 char *e;
3992 unsigned long n = simple_strtoul(buf, &e, 10);
3994 if (*buf && (*e == 0 || *e == '\n')) {
3995 atomic_set(&mddev->max_corr_read_errors, n);
3996 return len;
3998 return -EINVAL;
4001 static struct md_sysfs_entry max_corr_read_errors =
4002 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
4003 max_corrected_read_errors_store);
4005 static ssize_t
4006 null_show(struct mddev *mddev, char *page)
4008 return -EINVAL;
4011 static ssize_t
4012 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
4014 /* buf must be %d:%d\n? giving major and minor numbers */
4015 /* The new device is added to the array.
4016 * If the array has a persistent superblock, we read the
4017 * superblock to initialise info and check validity.
4018 * Otherwise, only checking done is that in bind_rdev_to_array,
4019 * which mainly checks size.
4021 char *e;
4022 int major = simple_strtoul(buf, &e, 10);
4023 int minor;
4024 dev_t dev;
4025 struct md_rdev *rdev;
4026 int err;
4028 if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
4029 return -EINVAL;
4030 minor = simple_strtoul(e+1, &e, 10);
4031 if (*e && *e != '\n')
4032 return -EINVAL;
4033 dev = MKDEV(major, minor);
4034 if (major != MAJOR(dev) ||
4035 minor != MINOR(dev))
4036 return -EOVERFLOW;
4039 if (mddev->persistent) {
4040 rdev = md_import_device(dev, mddev->major_version,
4041 mddev->minor_version);
4042 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
4043 struct md_rdev *rdev0
4044 = list_entry(mddev->disks.next,
4045 struct md_rdev, same_set);
4046 err = super_types[mddev->major_version]
4047 .load_super(rdev, rdev0, mddev->minor_version);
4048 if (err < 0)
4049 goto out;
4051 } else if (mddev->external)
4052 rdev = md_import_device(dev, -2, -1);
4053 else
4054 rdev = md_import_device(dev, -1, -1);
4056 if (IS_ERR(rdev))
4057 return PTR_ERR(rdev);
4058 err = bind_rdev_to_array(rdev, mddev);
4059 out:
4060 if (err)
4061 export_rdev(rdev);
4062 return err ? err : len;
4065 static struct md_sysfs_entry md_new_device =
4066 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
4068 static ssize_t
4069 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
4071 char *end;
4072 unsigned long chunk, end_chunk;
4074 if (!mddev->bitmap)
4075 goto out;
4076 /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
4077 while (*buf) {
4078 chunk = end_chunk = simple_strtoul(buf, &end, 0);
4079 if (buf == end) break;
4080 if (*end == '-') { /* range */
4081 buf = end + 1;
4082 end_chunk = simple_strtoul(buf, &end, 0);
4083 if (buf == end) break;
4085 if (*end && !isspace(*end)) break;
4086 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
4087 buf = skip_spaces(end);
4089 bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
4090 out:
4091 return len;
4094 static struct md_sysfs_entry md_bitmap =
4095 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
4097 static ssize_t
4098 size_show(struct mddev *mddev, char *page)
4100 return sprintf(page, "%llu\n",
4101 (unsigned long long)mddev->dev_sectors / 2);
4104 static int update_size(struct mddev *mddev, sector_t num_sectors);
4106 static ssize_t
4107 size_store(struct mddev *mddev, const char *buf, size_t len)
4109 /* If array is inactive, we can reduce the component size, but
4110 * not increase it (except from 0).
4111 * If array is active, we can try an on-line resize
4113 sector_t sectors;
4114 int err = strict_blocks_to_sectors(buf, &sectors);
4116 if (err < 0)
4117 return err;
4118 if (mddev->pers) {
4119 err = update_size(mddev, sectors);
4120 md_update_sb(mddev, 1);
4121 } else {
4122 if (mddev->dev_sectors == 0 ||
4123 mddev->dev_sectors > sectors)
4124 mddev->dev_sectors = sectors;
4125 else
4126 err = -ENOSPC;
4128 return err ? err : len;
4131 static struct md_sysfs_entry md_size =
4132 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4135 /* Metadata version.
4136 * This is one of
4137 * 'none' for arrays with no metadata (good luck...)
4138 * 'external' for arrays with externally managed metadata,
4139 * or N.M for internally known formats
4141 static ssize_t
4142 metadata_show(struct mddev *mddev, char *page)
4144 if (mddev->persistent)
4145 return sprintf(page, "%d.%d\n",
4146 mddev->major_version, mddev->minor_version);
4147 else if (mddev->external)
4148 return sprintf(page, "external:%s\n", mddev->metadata_type);
4149 else
4150 return sprintf(page, "none\n");
4153 static ssize_t
4154 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4156 int major, minor;
4157 char *e;
4158 /* Changing the details of 'external' metadata is
4159 * always permitted. Otherwise there must be
4160 * no devices attached to the array.
4162 if (mddev->external && strncmp(buf, "external:", 9) == 0)
4164 else if (!list_empty(&mddev->disks))
4165 return -EBUSY;
4167 if (cmd_match(buf, "none")) {
4168 mddev->persistent = 0;
4169 mddev->external = 0;
4170 mddev->major_version = 0;
4171 mddev->minor_version = 90;
4172 return len;
4174 if (strncmp(buf, "external:", 9) == 0) {
4175 size_t namelen = len-9;
4176 if (namelen >= sizeof(mddev->metadata_type))
4177 namelen = sizeof(mddev->metadata_type)-1;
4178 strncpy(mddev->metadata_type, buf+9, namelen);
4179 mddev->metadata_type[namelen] = 0;
4180 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4181 mddev->metadata_type[--namelen] = 0;
4182 mddev->persistent = 0;
4183 mddev->external = 1;
4184 mddev->major_version = 0;
4185 mddev->minor_version = 90;
4186 return len;
4188 major = simple_strtoul(buf, &e, 10);
4189 if (e==buf || *e != '.')
4190 return -EINVAL;
4191 buf = e+1;
4192 minor = simple_strtoul(buf, &e, 10);
4193 if (e==buf || (*e && *e != '\n') )
4194 return -EINVAL;
4195 if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4196 return -ENOENT;
4197 mddev->major_version = major;
4198 mddev->minor_version = minor;
4199 mddev->persistent = 1;
4200 mddev->external = 0;
4201 return len;
4204 static struct md_sysfs_entry md_metadata =
4205 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4207 static ssize_t
4208 action_show(struct mddev *mddev, char *page)
4210 char *type = "idle";
4211 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4212 type = "frozen";
4213 else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4214 (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
4215 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4216 type = "reshape";
4217 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4218 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
4219 type = "resync";
4220 else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
4221 type = "check";
4222 else
4223 type = "repair";
4224 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
4225 type = "recover";
4227 return sprintf(page, "%s\n", type);
4230 static ssize_t
4231 action_store(struct mddev *mddev, const char *page, size_t len)
4233 if (!mddev->pers || !mddev->pers->sync_request)
4234 return -EINVAL;
4236 if (cmd_match(page, "frozen"))
4237 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4238 else
4239 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4241 if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4242 if (mddev->sync_thread) {
4243 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4244 md_reap_sync_thread(mddev);
4246 } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4247 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
4248 return -EBUSY;
4249 else if (cmd_match(page, "resync"))
4250 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4251 else if (cmd_match(page, "recover")) {
4252 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4253 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4254 } else if (cmd_match(page, "reshape")) {
4255 int err;
4256 if (mddev->pers->start_reshape == NULL)
4257 return -EINVAL;
4258 err = mddev->pers->start_reshape(mddev);
4259 if (err)
4260 return err;
4261 sysfs_notify(&mddev->kobj, NULL, "degraded");
4262 } else {
4263 if (cmd_match(page, "check"))
4264 set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4265 else if (!cmd_match(page, "repair"))
4266 return -EINVAL;
4267 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4268 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4270 if (mddev->ro == 2) {
4271 /* A write to sync_action is enough to justify
4272 * canceling read-auto mode
4274 mddev->ro = 0;
4275 md_wakeup_thread(mddev->sync_thread);
4277 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4278 md_wakeup_thread(mddev->thread);
4279 sysfs_notify_dirent_safe(mddev->sysfs_action);
4280 return len;
4283 static ssize_t
4284 mismatch_cnt_show(struct mddev *mddev, char *page)
4286 return sprintf(page, "%llu\n",
4287 (unsigned long long)
4288 atomic64_read(&mddev->resync_mismatches));
4291 static struct md_sysfs_entry md_scan_mode =
4292 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4295 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4297 static ssize_t
4298 sync_min_show(struct mddev *mddev, char *page)
4300 return sprintf(page, "%d (%s)\n", speed_min(mddev),
4301 mddev->sync_speed_min ? "local": "system");
4304 static ssize_t
4305 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4307 int min;
4308 char *e;
4309 if (strncmp(buf, "system", 6)==0) {
4310 mddev->sync_speed_min = 0;
4311 return len;
4313 min = simple_strtoul(buf, &e, 10);
4314 if (buf == e || (*e && *e != '\n') || min <= 0)
4315 return -EINVAL;
4316 mddev->sync_speed_min = min;
4317 return len;
4320 static struct md_sysfs_entry md_sync_min =
4321 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4323 static ssize_t
4324 sync_max_show(struct mddev *mddev, char *page)
4326 return sprintf(page, "%d (%s)\n", speed_max(mddev),
4327 mddev->sync_speed_max ? "local": "system");
4330 static ssize_t
4331 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4333 int max;
4334 char *e;
4335 if (strncmp(buf, "system", 6)==0) {
4336 mddev->sync_speed_max = 0;
4337 return len;
4339 max = simple_strtoul(buf, &e, 10);
4340 if (buf == e || (*e && *e != '\n') || max <= 0)
4341 return -EINVAL;
4342 mddev->sync_speed_max = max;
4343 return len;
4346 static struct md_sysfs_entry md_sync_max =
4347 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4349 static ssize_t
4350 degraded_show(struct mddev *mddev, char *page)
4352 return sprintf(page, "%d\n", mddev->degraded);
4354 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4356 static ssize_t
4357 sync_force_parallel_show(struct mddev *mddev, char *page)
4359 return sprintf(page, "%d\n", mddev->parallel_resync);
4362 static ssize_t
4363 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4365 long n;
4367 if (strict_strtol(buf, 10, &n))
4368 return -EINVAL;
4370 if (n != 0 && n != 1)
4371 return -EINVAL;
4373 mddev->parallel_resync = n;
4375 if (mddev->sync_thread)
4376 wake_up(&resync_wait);
4378 return len;
4381 /* force parallel resync, even with shared block devices */
4382 static struct md_sysfs_entry md_sync_force_parallel =
4383 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4384 sync_force_parallel_show, sync_force_parallel_store);
4386 static ssize_t
4387 sync_speed_show(struct mddev *mddev, char *page)
4389 unsigned long resync, dt, db;
4390 if (mddev->curr_resync == 0)
4391 return sprintf(page, "none\n");
4392 resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4393 dt = (jiffies - mddev->resync_mark) / HZ;
4394 if (!dt) dt++;
4395 db = resync - mddev->resync_mark_cnt;
4396 return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4399 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4401 static ssize_t
4402 sync_completed_show(struct mddev *mddev, char *page)
4404 unsigned long long max_sectors, resync;
4406 if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4407 return sprintf(page, "none\n");
4409 if (mddev->curr_resync == 1 ||
4410 mddev->curr_resync == 2)
4411 return sprintf(page, "delayed\n");
4413 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
4414 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4415 max_sectors = mddev->resync_max_sectors;
4416 else
4417 max_sectors = mddev->dev_sectors;
4419 resync = mddev->curr_resync_completed;
4420 return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4423 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
4425 static ssize_t
4426 min_sync_show(struct mddev *mddev, char *page)
4428 return sprintf(page, "%llu\n",
4429 (unsigned long long)mddev->resync_min);
4431 static ssize_t
4432 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4434 unsigned long long min;
4435 if (strict_strtoull(buf, 10, &min))
4436 return -EINVAL;
4437 if (min > mddev->resync_max)
4438 return -EINVAL;
4439 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4440 return -EBUSY;
4442 /* Must be a multiple of chunk_size */
4443 if (mddev->chunk_sectors) {
4444 sector_t temp = min;
4445 if (sector_div(temp, mddev->chunk_sectors))
4446 return -EINVAL;
4448 mddev->resync_min = min;
4450 return len;
4453 static struct md_sysfs_entry md_min_sync =
4454 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4456 static ssize_t
4457 max_sync_show(struct mddev *mddev, char *page)
4459 if (mddev->resync_max == MaxSector)
4460 return sprintf(page, "max\n");
4461 else
4462 return sprintf(page, "%llu\n",
4463 (unsigned long long)mddev->resync_max);
4465 static ssize_t
4466 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4468 if (strncmp(buf, "max", 3) == 0)
4469 mddev->resync_max = MaxSector;
4470 else {
4471 unsigned long long max;
4472 if (strict_strtoull(buf, 10, &max))
4473 return -EINVAL;
4474 if (max < mddev->resync_min)
4475 return -EINVAL;
4476 if (max < mddev->resync_max &&
4477 mddev->ro == 0 &&
4478 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4479 return -EBUSY;
4481 /* Must be a multiple of chunk_size */
4482 if (mddev->chunk_sectors) {
4483 sector_t temp = max;
4484 if (sector_div(temp, mddev->chunk_sectors))
4485 return -EINVAL;
4487 mddev->resync_max = max;
4489 wake_up(&mddev->recovery_wait);
4490 return len;
4493 static struct md_sysfs_entry md_max_sync =
4494 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4496 static ssize_t
4497 suspend_lo_show(struct mddev *mddev, char *page)
4499 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4502 static ssize_t
4503 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4505 char *e;
4506 unsigned long long new = simple_strtoull(buf, &e, 10);
4507 unsigned long long old = mddev->suspend_lo;
4509 if (mddev->pers == NULL ||
4510 mddev->pers->quiesce == NULL)
4511 return -EINVAL;
4512 if (buf == e || (*e && *e != '\n'))
4513 return -EINVAL;
4515 mddev->suspend_lo = new;
4516 if (new >= old)
4517 /* Shrinking suspended region */
4518 mddev->pers->quiesce(mddev, 2);
4519 else {
4520 /* Expanding suspended region - need to wait */
4521 mddev->pers->quiesce(mddev, 1);
4522 mddev->pers->quiesce(mddev, 0);
4524 return len;
4526 static struct md_sysfs_entry md_suspend_lo =
4527 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4530 static ssize_t
4531 suspend_hi_show(struct mddev *mddev, char *page)
4533 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4536 static ssize_t
4537 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4539 char *e;
4540 unsigned long long new = simple_strtoull(buf, &e, 10);
4541 unsigned long long old = mddev->suspend_hi;
4543 if (mddev->pers == NULL ||
4544 mddev->pers->quiesce == NULL)
4545 return -EINVAL;
4546 if (buf == e || (*e && *e != '\n'))
4547 return -EINVAL;
4549 mddev->suspend_hi = new;
4550 if (new <= old)
4551 /* Shrinking suspended region */
4552 mddev->pers->quiesce(mddev, 2);
4553 else {
4554 /* Expanding suspended region - need to wait */
4555 mddev->pers->quiesce(mddev, 1);
4556 mddev->pers->quiesce(mddev, 0);
4558 return len;
4560 static struct md_sysfs_entry md_suspend_hi =
4561 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4563 static ssize_t
4564 reshape_position_show(struct mddev *mddev, char *page)
4566 if (mddev->reshape_position != MaxSector)
4567 return sprintf(page, "%llu\n",
4568 (unsigned long long)mddev->reshape_position);
4569 strcpy(page, "none\n");
4570 return 5;
4573 static ssize_t
4574 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4576 struct md_rdev *rdev;
4577 char *e;
4578 unsigned long long new = simple_strtoull(buf, &e, 10);
4579 if (mddev->pers)
4580 return -EBUSY;
4581 if (buf == e || (*e && *e != '\n'))
4582 return -EINVAL;
4583 mddev->reshape_position = new;
4584 mddev->delta_disks = 0;
4585 mddev->reshape_backwards = 0;
4586 mddev->new_level = mddev->level;
4587 mddev->new_layout = mddev->layout;
4588 mddev->new_chunk_sectors = mddev->chunk_sectors;
4589 rdev_for_each(rdev, mddev)
4590 rdev->new_data_offset = rdev->data_offset;
4591 return len;
4594 static struct md_sysfs_entry md_reshape_position =
4595 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4596 reshape_position_store);
4598 static ssize_t
4599 reshape_direction_show(struct mddev *mddev, char *page)
4601 return sprintf(page, "%s\n",
4602 mddev->reshape_backwards ? "backwards" : "forwards");
4605 static ssize_t
4606 reshape_direction_store(struct mddev *mddev, const char *buf, size_t len)
4608 int backwards = 0;
4609 if (cmd_match(buf, "forwards"))
4610 backwards = 0;
4611 else if (cmd_match(buf, "backwards"))
4612 backwards = 1;
4613 else
4614 return -EINVAL;
4615 if (mddev->reshape_backwards == backwards)
4616 return len;
4618 /* check if we are allowed to change */
4619 if (mddev->delta_disks)
4620 return -EBUSY;
4622 if (mddev->persistent &&
4623 mddev->major_version == 0)
4624 return -EINVAL;
4626 mddev->reshape_backwards = backwards;
4627 return len;
4630 static struct md_sysfs_entry md_reshape_direction =
4631 __ATTR(reshape_direction, S_IRUGO|S_IWUSR, reshape_direction_show,
4632 reshape_direction_store);
4634 static ssize_t
4635 array_size_show(struct mddev *mddev, char *page)
4637 if (mddev->external_size)
4638 return sprintf(page, "%llu\n",
4639 (unsigned long long)mddev->array_sectors/2);
4640 else
4641 return sprintf(page, "default\n");
4644 static ssize_t
4645 array_size_store(struct mddev *mddev, const char *buf, size_t len)
4647 sector_t sectors;
4649 if (strncmp(buf, "default", 7) == 0) {
4650 if (mddev->pers)
4651 sectors = mddev->pers->size(mddev, 0, 0);
4652 else
4653 sectors = mddev->array_sectors;
4655 mddev->external_size = 0;
4656 } else {
4657 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4658 return -EINVAL;
4659 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4660 return -E2BIG;
4662 mddev->external_size = 1;
4665 mddev->array_sectors = sectors;
4666 if (mddev->pers) {
4667 set_capacity(mddev->gendisk, mddev->array_sectors);
4668 revalidate_disk(mddev->gendisk);
4670 return len;
4673 static struct md_sysfs_entry md_array_size =
4674 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4675 array_size_store);
4677 static struct attribute *md_default_attrs[] = {
4678 &md_level.attr,
4679 &md_layout.attr,
4680 &md_raid_disks.attr,
4681 &md_chunk_size.attr,
4682 &md_size.attr,
4683 &md_resync_start.attr,
4684 &md_metadata.attr,
4685 &md_new_device.attr,
4686 &md_safe_delay.attr,
4687 &md_array_state.attr,
4688 &md_reshape_position.attr,
4689 &md_reshape_direction.attr,
4690 &md_array_size.attr,
4691 &max_corr_read_errors.attr,
4692 NULL,
4695 static struct attribute *md_redundancy_attrs[] = {
4696 &md_scan_mode.attr,
4697 &md_mismatches.attr,
4698 &md_sync_min.attr,
4699 &md_sync_max.attr,
4700 &md_sync_speed.attr,
4701 &md_sync_force_parallel.attr,
4702 &md_sync_completed.attr,
4703 &md_min_sync.attr,
4704 &md_max_sync.attr,
4705 &md_suspend_lo.attr,
4706 &md_suspend_hi.attr,
4707 &md_bitmap.attr,
4708 &md_degraded.attr,
4709 NULL,
4711 static struct attribute_group md_redundancy_group = {
4712 .name = NULL,
4713 .attrs = md_redundancy_attrs,
4717 static ssize_t
4718 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4720 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4721 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4722 ssize_t rv;
4724 if (!entry->show)
4725 return -EIO;
4726 spin_lock(&all_mddevs_lock);
4727 if (list_empty(&mddev->all_mddevs)) {
4728 spin_unlock(&all_mddevs_lock);
4729 return -EBUSY;
4731 mddev_get(mddev);
4732 spin_unlock(&all_mddevs_lock);
4734 rv = mddev_lock(mddev);
4735 if (!rv) {
4736 rv = entry->show(mddev, page);
4737 mddev_unlock(mddev);
4739 mddev_put(mddev);
4740 return rv;
4743 static ssize_t
4744 md_attr_store(struct kobject *kobj, struct attribute *attr,
4745 const char *page, size_t length)
4747 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4748 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4749 ssize_t rv;
4751 if (!entry->store)
4752 return -EIO;
4753 if (!capable(CAP_SYS_ADMIN))
4754 return -EACCES;
4755 spin_lock(&all_mddevs_lock);
4756 if (list_empty(&mddev->all_mddevs)) {
4757 spin_unlock(&all_mddevs_lock);
4758 return -EBUSY;
4760 mddev_get(mddev);
4761 spin_unlock(&all_mddevs_lock);
4762 if (entry->store == new_dev_store)
4763 flush_workqueue(md_misc_wq);
4764 rv = mddev_lock(mddev);
4765 if (!rv) {
4766 rv = entry->store(mddev, page, length);
4767 mddev_unlock(mddev);
4769 mddev_put(mddev);
4770 return rv;
4773 static void md_free(struct kobject *ko)
4775 struct mddev *mddev = container_of(ko, struct mddev, kobj);
4777 if (mddev->sysfs_state)
4778 sysfs_put(mddev->sysfs_state);
4780 if (mddev->gendisk) {
4781 del_gendisk(mddev->gendisk);
4782 put_disk(mddev->gendisk);
4784 if (mddev->queue)
4785 blk_cleanup_queue(mddev->queue);
4787 kfree(mddev);
4790 static const struct sysfs_ops md_sysfs_ops = {
4791 .show = md_attr_show,
4792 .store = md_attr_store,
4794 static struct kobj_type md_ktype = {
4795 .release = md_free,
4796 .sysfs_ops = &md_sysfs_ops,
4797 .default_attrs = md_default_attrs,
4800 int mdp_major = 0;
4802 static void mddev_delayed_delete(struct work_struct *ws)
4804 struct mddev *mddev = container_of(ws, struct mddev, del_work);
4806 sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4807 kobject_del(&mddev->kobj);
4808 kobject_put(&mddev->kobj);
4811 static int md_alloc(dev_t dev, char *name)
4813 static DEFINE_MUTEX(disks_mutex);
4814 struct mddev *mddev = mddev_find(dev);
4815 struct gendisk *disk;
4816 int partitioned;
4817 int shift;
4818 int unit;
4819 int error;
4821 if (!mddev)
4822 return -ENODEV;
4824 partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4825 shift = partitioned ? MdpMinorShift : 0;
4826 unit = MINOR(mddev->unit) >> shift;
4828 /* wait for any previous instance of this device to be
4829 * completely removed (mddev_delayed_delete).
4831 flush_workqueue(md_misc_wq);
4833 mutex_lock(&disks_mutex);
4834 error = -EEXIST;
4835 if (mddev->gendisk)
4836 goto abort;
4838 if (name) {
4839 /* Need to ensure that 'name' is not a duplicate.
4841 struct mddev *mddev2;
4842 spin_lock(&all_mddevs_lock);
4844 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4845 if (mddev2->gendisk &&
4846 strcmp(mddev2->gendisk->disk_name, name) == 0) {
4847 spin_unlock(&all_mddevs_lock);
4848 goto abort;
4850 spin_unlock(&all_mddevs_lock);
4853 error = -ENOMEM;
4854 mddev->queue = blk_alloc_queue(GFP_KERNEL);
4855 if (!mddev->queue)
4856 goto abort;
4857 mddev->queue->queuedata = mddev;
4859 blk_queue_make_request(mddev->queue, md_make_request);
4860 blk_set_stacking_limits(&mddev->queue->limits);
4862 disk = alloc_disk(1 << shift);
4863 if (!disk) {
4864 blk_cleanup_queue(mddev->queue);
4865 mddev->queue = NULL;
4866 goto abort;
4868 disk->major = MAJOR(mddev->unit);
4869 disk->first_minor = unit << shift;
4870 if (name)
4871 strcpy(disk->disk_name, name);
4872 else if (partitioned)
4873 sprintf(disk->disk_name, "md_d%d", unit);
4874 else
4875 sprintf(disk->disk_name, "md%d", unit);
4876 disk->fops = &md_fops;
4877 disk->private_data = mddev;
4878 disk->queue = mddev->queue;
4879 blk_queue_flush(mddev->queue, REQ_FLUSH | REQ_FUA);
4880 /* Allow extended partitions. This makes the
4881 * 'mdp' device redundant, but we can't really
4882 * remove it now.
4884 disk->flags |= GENHD_FL_EXT_DEVT;
4885 mddev->gendisk = disk;
4886 /* As soon as we call add_disk(), another thread could get
4887 * through to md_open, so make sure it doesn't get too far
4889 mutex_lock(&mddev->open_mutex);
4890 add_disk(disk);
4892 error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4893 &disk_to_dev(disk)->kobj, "%s", "md");
4894 if (error) {
4895 /* This isn't possible, but as kobject_init_and_add is marked
4896 * __must_check, we must do something with the result
4898 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4899 disk->disk_name);
4900 error = 0;
4902 if (mddev->kobj.sd &&
4903 sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4904 printk(KERN_DEBUG "pointless warning\n");
4905 mutex_unlock(&mddev->open_mutex);
4906 abort:
4907 mutex_unlock(&disks_mutex);
4908 if (!error && mddev->kobj.sd) {
4909 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4910 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4912 mddev_put(mddev);
4913 return error;
4916 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4918 md_alloc(dev, NULL);
4919 return NULL;
4922 static int add_named_array(const char *val, struct kernel_param *kp)
4924 /* val must be "md_*" where * is not all digits.
4925 * We allocate an array with a large free minor number, and
4926 * set the name to val. val must not already be an active name.
4928 int len = strlen(val);
4929 char buf[DISK_NAME_LEN];
4931 while (len && val[len-1] == '\n')
4932 len--;
4933 if (len >= DISK_NAME_LEN)
4934 return -E2BIG;
4935 strlcpy(buf, val, len+1);
4936 if (strncmp(buf, "md_", 3) != 0)
4937 return -EINVAL;
4938 return md_alloc(0, buf);
4941 static void md_safemode_timeout(unsigned long data)
4943 struct mddev *mddev = (struct mddev *) data;
4945 if (!atomic_read(&mddev->writes_pending)) {
4946 mddev->safemode = 1;
4947 if (mddev->external)
4948 sysfs_notify_dirent_safe(mddev->sysfs_state);
4950 md_wakeup_thread(mddev->thread);
4953 static int start_dirty_degraded;
4955 int md_run(struct mddev *mddev)
4957 int err;
4958 struct md_rdev *rdev;
4959 struct md_personality *pers;
4961 if (list_empty(&mddev->disks))
4962 /* cannot run an array with no devices.. */
4963 return -EINVAL;
4965 if (mddev->pers)
4966 return -EBUSY;
4967 /* Cannot run until previous stop completes properly */
4968 if (mddev->sysfs_active)
4969 return -EBUSY;
4972 * Analyze all RAID superblock(s)
4974 if (!mddev->raid_disks) {
4975 if (!mddev->persistent)
4976 return -EINVAL;
4977 analyze_sbs(mddev);
4980 if (mddev->level != LEVEL_NONE)
4981 request_module("md-level-%d", mddev->level);
4982 else if (mddev->clevel[0])
4983 request_module("md-%s", mddev->clevel);
4986 * Drop all container device buffers, from now on
4987 * the only valid external interface is through the md
4988 * device.
4990 rdev_for_each(rdev, mddev) {
4991 if (test_bit(Faulty, &rdev->flags))
4992 continue;
4993 sync_blockdev(rdev->bdev);
4994 invalidate_bdev(rdev->bdev);
4996 /* perform some consistency tests on the device.
4997 * We don't want the data to overlap the metadata,
4998 * Internal Bitmap issues have been handled elsewhere.
5000 if (rdev->meta_bdev) {
5001 /* Nothing to check */;
5002 } else if (rdev->data_offset < rdev->sb_start) {
5003 if (mddev->dev_sectors &&
5004 rdev->data_offset + mddev->dev_sectors
5005 > rdev->sb_start) {
5006 printk("md: %s: data overlaps metadata\n",
5007 mdname(mddev));
5008 return -EINVAL;
5010 } else {
5011 if (rdev->sb_start + rdev->sb_size/512
5012 > rdev->data_offset) {
5013 printk("md: %s: metadata overlaps data\n",
5014 mdname(mddev));
5015 return -EINVAL;
5018 sysfs_notify_dirent_safe(rdev->sysfs_state);
5021 if (mddev->bio_set == NULL)
5022 mddev->bio_set = bioset_create(BIO_POOL_SIZE, 0);
5024 spin_lock(&pers_lock);
5025 pers = find_pers(mddev->level, mddev->clevel);
5026 if (!pers || !try_module_get(pers->owner)) {
5027 spin_unlock(&pers_lock);
5028 if (mddev->level != LEVEL_NONE)
5029 printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
5030 mddev->level);
5031 else
5032 printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
5033 mddev->clevel);
5034 return -EINVAL;
5036 mddev->pers = pers;
5037 spin_unlock(&pers_lock);
5038 if (mddev->level != pers->level) {
5039 mddev->level = pers->level;
5040 mddev->new_level = pers->level;
5042 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
5044 if (mddev->reshape_position != MaxSector &&
5045 pers->start_reshape == NULL) {
5046 /* This personality cannot handle reshaping... */
5047 mddev->pers = NULL;
5048 module_put(pers->owner);
5049 return -EINVAL;
5052 if (pers->sync_request) {
5053 /* Warn if this is a potentially silly
5054 * configuration.
5056 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5057 struct md_rdev *rdev2;
5058 int warned = 0;
5060 rdev_for_each(rdev, mddev)
5061 rdev_for_each(rdev2, mddev) {
5062 if (rdev < rdev2 &&
5063 rdev->bdev->bd_contains ==
5064 rdev2->bdev->bd_contains) {
5065 printk(KERN_WARNING
5066 "%s: WARNING: %s appears to be"
5067 " on the same physical disk as"
5068 " %s.\n",
5069 mdname(mddev),
5070 bdevname(rdev->bdev,b),
5071 bdevname(rdev2->bdev,b2));
5072 warned = 1;
5076 if (warned)
5077 printk(KERN_WARNING
5078 "True protection against single-disk"
5079 " failure might be compromised.\n");
5082 mddev->recovery = 0;
5083 /* may be over-ridden by personality */
5084 mddev->resync_max_sectors = mddev->dev_sectors;
5086 mddev->ok_start_degraded = start_dirty_degraded;
5088 if (start_readonly && mddev->ro == 0)
5089 mddev->ro = 2; /* read-only, but switch on first write */
5091 err = mddev->pers->run(mddev);
5092 if (err)
5093 printk(KERN_ERR "md: pers->run() failed ...\n");
5094 else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
5095 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
5096 " but 'external_size' not in effect?\n", __func__);
5097 printk(KERN_ERR
5098 "md: invalid array_size %llu > default size %llu\n",
5099 (unsigned long long)mddev->array_sectors / 2,
5100 (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
5101 err = -EINVAL;
5102 mddev->pers->stop(mddev);
5104 if (err == 0 && mddev->pers->sync_request &&
5105 (mddev->bitmap_info.file || mddev->bitmap_info.offset)) {
5106 err = bitmap_create(mddev);
5107 if (err) {
5108 printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
5109 mdname(mddev), err);
5110 mddev->pers->stop(mddev);
5113 if (err) {
5114 module_put(mddev->pers->owner);
5115 mddev->pers = NULL;
5116 bitmap_destroy(mddev);
5117 return err;
5119 if (mddev->pers->sync_request) {
5120 if (mddev->kobj.sd &&
5121 sysfs_create_group(&mddev->kobj, &md_redundancy_group))
5122 printk(KERN_WARNING
5123 "md: cannot register extra attributes for %s\n",
5124 mdname(mddev));
5125 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
5126 } else if (mddev->ro == 2) /* auto-readonly not meaningful */
5127 mddev->ro = 0;
5129 atomic_set(&mddev->writes_pending,0);
5130 atomic_set(&mddev->max_corr_read_errors,
5131 MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
5132 mddev->safemode = 0;
5133 mddev->safemode_timer.function = md_safemode_timeout;
5134 mddev->safemode_timer.data = (unsigned long) mddev;
5135 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
5136 mddev->in_sync = 1;
5137 smp_wmb();
5138 mddev->ready = 1;
5139 rdev_for_each(rdev, mddev)
5140 if (rdev->raid_disk >= 0)
5141 if (sysfs_link_rdev(mddev, rdev))
5142 /* failure here is OK */;
5144 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5146 if (mddev->flags)
5147 md_update_sb(mddev, 0);
5149 md_new_event(mddev);
5150 sysfs_notify_dirent_safe(mddev->sysfs_state);
5151 sysfs_notify_dirent_safe(mddev->sysfs_action);
5152 sysfs_notify(&mddev->kobj, NULL, "degraded");
5153 return 0;
5155 EXPORT_SYMBOL_GPL(md_run);
5157 static int do_md_run(struct mddev *mddev)
5159 int err;
5161 err = md_run(mddev);
5162 if (err)
5163 goto out;
5164 err = bitmap_load(mddev);
5165 if (err) {
5166 bitmap_destroy(mddev);
5167 goto out;
5170 md_wakeup_thread(mddev->thread);
5171 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
5173 set_capacity(mddev->gendisk, mddev->array_sectors);
5174 revalidate_disk(mddev->gendisk);
5175 mddev->changed = 1;
5176 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5177 out:
5178 return err;
5181 static int restart_array(struct mddev *mddev)
5183 struct gendisk *disk = mddev->gendisk;
5185 /* Complain if it has no devices */
5186 if (list_empty(&mddev->disks))
5187 return -ENXIO;
5188 if (!mddev->pers)
5189 return -EINVAL;
5190 if (!mddev->ro)
5191 return -EBUSY;
5192 mddev->safemode = 0;
5193 mddev->ro = 0;
5194 set_disk_ro(disk, 0);
5195 printk(KERN_INFO "md: %s switched to read-write mode.\n",
5196 mdname(mddev));
5197 /* Kick recovery or resync if necessary */
5198 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5199 md_wakeup_thread(mddev->thread);
5200 md_wakeup_thread(mddev->sync_thread);
5201 sysfs_notify_dirent_safe(mddev->sysfs_state);
5202 return 0;
5205 /* similar to deny_write_access, but accounts for our holding a reference
5206 * to the file ourselves */
5207 static int deny_bitmap_write_access(struct file * file)
5209 struct inode *inode = file->f_mapping->host;
5211 spin_lock(&inode->i_lock);
5212 if (atomic_read(&inode->i_writecount) > 1) {
5213 spin_unlock(&inode->i_lock);
5214 return -ETXTBSY;
5216 atomic_set(&inode->i_writecount, -1);
5217 spin_unlock(&inode->i_lock);
5219 return 0;
5222 void restore_bitmap_write_access(struct file *file)
5224 struct inode *inode = file->f_mapping->host;
5226 spin_lock(&inode->i_lock);
5227 atomic_set(&inode->i_writecount, 1);
5228 spin_unlock(&inode->i_lock);
5231 static void md_clean(struct mddev *mddev)
5233 mddev->array_sectors = 0;
5234 mddev->external_size = 0;
5235 mddev->dev_sectors = 0;
5236 mddev->raid_disks = 0;
5237 mddev->recovery_cp = 0;
5238 mddev->resync_min = 0;
5239 mddev->resync_max = MaxSector;
5240 mddev->reshape_position = MaxSector;
5241 mddev->external = 0;
5242 mddev->persistent = 0;
5243 mddev->level = LEVEL_NONE;
5244 mddev->clevel[0] = 0;
5245 mddev->flags = 0;
5246 mddev->ro = 0;
5247 mddev->metadata_type[0] = 0;
5248 mddev->chunk_sectors = 0;
5249 mddev->ctime = mddev->utime = 0;
5250 mddev->layout = 0;
5251 mddev->max_disks = 0;
5252 mddev->events = 0;
5253 mddev->can_decrease_events = 0;
5254 mddev->delta_disks = 0;
5255 mddev->reshape_backwards = 0;
5256 mddev->new_level = LEVEL_NONE;
5257 mddev->new_layout = 0;
5258 mddev->new_chunk_sectors = 0;
5259 mddev->curr_resync = 0;
5260 atomic64_set(&mddev->resync_mismatches, 0);
5261 mddev->suspend_lo = mddev->suspend_hi = 0;
5262 mddev->sync_speed_min = mddev->sync_speed_max = 0;
5263 mddev->recovery = 0;
5264 mddev->in_sync = 0;
5265 mddev->changed = 0;
5266 mddev->degraded = 0;
5267 mddev->safemode = 0;
5268 mddev->merge_check_needed = 0;
5269 mddev->bitmap_info.offset = 0;
5270 mddev->bitmap_info.default_offset = 0;
5271 mddev->bitmap_info.default_space = 0;
5272 mddev->bitmap_info.chunksize = 0;
5273 mddev->bitmap_info.daemon_sleep = 0;
5274 mddev->bitmap_info.max_write_behind = 0;
5277 static void __md_stop_writes(struct mddev *mddev)
5279 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5280 if (mddev->sync_thread) {
5281 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5282 md_reap_sync_thread(mddev);
5285 del_timer_sync(&mddev->safemode_timer);
5287 bitmap_flush(mddev);
5288 md_super_wait(mddev);
5290 if (mddev->ro == 0 &&
5291 (!mddev->in_sync || mddev->flags)) {
5292 /* mark array as shutdown cleanly */
5293 mddev->in_sync = 1;
5294 md_update_sb(mddev, 1);
5298 void md_stop_writes(struct mddev *mddev)
5300 mddev_lock(mddev);
5301 __md_stop_writes(mddev);
5302 mddev_unlock(mddev);
5304 EXPORT_SYMBOL_GPL(md_stop_writes);
5306 static void __md_stop(struct mddev *mddev)
5308 mddev->ready = 0;
5309 /* Ensure ->event_work is done */
5310 flush_workqueue(md_misc_wq);
5311 mddev->pers->stop(mddev);
5312 if (mddev->pers->sync_request && mddev->to_remove == NULL)
5313 mddev->to_remove = &md_redundancy_group;
5314 module_put(mddev->pers->owner);
5315 mddev->pers = NULL;
5316 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5319 void md_stop(struct mddev *mddev)
5321 /* stop the array and free an attached data structures.
5322 * This is called from dm-raid
5324 __md_stop(mddev);
5325 bitmap_destroy(mddev);
5326 if (mddev->bio_set)
5327 bioset_free(mddev->bio_set);
5330 EXPORT_SYMBOL_GPL(md_stop);
5332 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5334 int err = 0;
5335 mutex_lock(&mddev->open_mutex);
5336 if (atomic_read(&mddev->openers) > !!bdev) {
5337 printk("md: %s still in use.\n",mdname(mddev));
5338 err = -EBUSY;
5339 goto out;
5341 if (bdev)
5342 sync_blockdev(bdev);
5343 if (mddev->pers) {
5344 __md_stop_writes(mddev);
5346 err = -ENXIO;
5347 if (mddev->ro==1)
5348 goto out;
5349 mddev->ro = 1;
5350 set_disk_ro(mddev->gendisk, 1);
5351 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5352 sysfs_notify_dirent_safe(mddev->sysfs_state);
5353 err = 0;
5355 out:
5356 mutex_unlock(&mddev->open_mutex);
5357 return err;
5360 /* mode:
5361 * 0 - completely stop and dis-assemble array
5362 * 2 - stop but do not disassemble array
5364 static int do_md_stop(struct mddev * mddev, int mode,
5365 struct block_device *bdev)
5367 struct gendisk *disk = mddev->gendisk;
5368 struct md_rdev *rdev;
5370 mutex_lock(&mddev->open_mutex);
5371 if (atomic_read(&mddev->openers) > !!bdev ||
5372 mddev->sysfs_active) {
5373 printk("md: %s still in use.\n",mdname(mddev));
5374 mutex_unlock(&mddev->open_mutex);
5375 return -EBUSY;
5377 if (bdev)
5378 /* It is possible IO was issued on some other
5379 * open file which was closed before we took ->open_mutex.
5380 * As that was not the last close __blkdev_put will not
5381 * have called sync_blockdev, so we must.
5383 sync_blockdev(bdev);
5385 if (mddev->pers) {
5386 if (mddev->ro)
5387 set_disk_ro(disk, 0);
5389 __md_stop_writes(mddev);
5390 __md_stop(mddev);
5391 mddev->queue->merge_bvec_fn = NULL;
5392 mddev->queue->backing_dev_info.congested_fn = NULL;
5394 /* tell userspace to handle 'inactive' */
5395 sysfs_notify_dirent_safe(mddev->sysfs_state);
5397 rdev_for_each(rdev, mddev)
5398 if (rdev->raid_disk >= 0)
5399 sysfs_unlink_rdev(mddev, rdev);
5401 set_capacity(disk, 0);
5402 mutex_unlock(&mddev->open_mutex);
5403 mddev->changed = 1;
5404 revalidate_disk(disk);
5406 if (mddev->ro)
5407 mddev->ro = 0;
5408 } else
5409 mutex_unlock(&mddev->open_mutex);
5411 * Free resources if final stop
5413 if (mode == 0) {
5414 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
5416 bitmap_destroy(mddev);
5417 if (mddev->bitmap_info.file) {
5418 restore_bitmap_write_access(mddev->bitmap_info.file);
5419 fput(mddev->bitmap_info.file);
5420 mddev->bitmap_info.file = NULL;
5422 mddev->bitmap_info.offset = 0;
5424 export_array(mddev);
5426 md_clean(mddev);
5427 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5428 if (mddev->hold_active == UNTIL_STOP)
5429 mddev->hold_active = 0;
5431 blk_integrity_unregister(disk);
5432 md_new_event(mddev);
5433 sysfs_notify_dirent_safe(mddev->sysfs_state);
5434 return 0;
5437 #ifndef MODULE
5438 static void autorun_array(struct mddev *mddev)
5440 struct md_rdev *rdev;
5441 int err;
5443 if (list_empty(&mddev->disks))
5444 return;
5446 printk(KERN_INFO "md: running: ");
5448 rdev_for_each(rdev, mddev) {
5449 char b[BDEVNAME_SIZE];
5450 printk("<%s>", bdevname(rdev->bdev,b));
5452 printk("\n");
5454 err = do_md_run(mddev);
5455 if (err) {
5456 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
5457 do_md_stop(mddev, 0, NULL);
5462 * lets try to run arrays based on all disks that have arrived
5463 * until now. (those are in pending_raid_disks)
5465 * the method: pick the first pending disk, collect all disks with
5466 * the same UUID, remove all from the pending list and put them into
5467 * the 'same_array' list. Then order this list based on superblock
5468 * update time (freshest comes first), kick out 'old' disks and
5469 * compare superblocks. If everything's fine then run it.
5471 * If "unit" is allocated, then bump its reference count
5473 static void autorun_devices(int part)
5475 struct md_rdev *rdev0, *rdev, *tmp;
5476 struct mddev *mddev;
5477 char b[BDEVNAME_SIZE];
5479 printk(KERN_INFO "md: autorun ...\n");
5480 while (!list_empty(&pending_raid_disks)) {
5481 int unit;
5482 dev_t dev;
5483 LIST_HEAD(candidates);
5484 rdev0 = list_entry(pending_raid_disks.next,
5485 struct md_rdev, same_set);
5487 printk(KERN_INFO "md: considering %s ...\n",
5488 bdevname(rdev0->bdev,b));
5489 INIT_LIST_HEAD(&candidates);
5490 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
5491 if (super_90_load(rdev, rdev0, 0) >= 0) {
5492 printk(KERN_INFO "md: adding %s ...\n",
5493 bdevname(rdev->bdev,b));
5494 list_move(&rdev->same_set, &candidates);
5497 * now we have a set of devices, with all of them having
5498 * mostly sane superblocks. It's time to allocate the
5499 * mddev.
5501 if (part) {
5502 dev = MKDEV(mdp_major,
5503 rdev0->preferred_minor << MdpMinorShift);
5504 unit = MINOR(dev) >> MdpMinorShift;
5505 } else {
5506 dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
5507 unit = MINOR(dev);
5509 if (rdev0->preferred_minor != unit) {
5510 printk(KERN_INFO "md: unit number in %s is bad: %d\n",
5511 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
5512 break;
5515 md_probe(dev, NULL, NULL);
5516 mddev = mddev_find(dev);
5517 if (!mddev || !mddev->gendisk) {
5518 if (mddev)
5519 mddev_put(mddev);
5520 printk(KERN_ERR
5521 "md: cannot allocate memory for md drive.\n");
5522 break;
5524 if (mddev_lock(mddev))
5525 printk(KERN_WARNING "md: %s locked, cannot run\n",
5526 mdname(mddev));
5527 else if (mddev->raid_disks || mddev->major_version
5528 || !list_empty(&mddev->disks)) {
5529 printk(KERN_WARNING
5530 "md: %s already running, cannot run %s\n",
5531 mdname(mddev), bdevname(rdev0->bdev,b));
5532 mddev_unlock(mddev);
5533 } else {
5534 printk(KERN_INFO "md: created %s\n", mdname(mddev));
5535 mddev->persistent = 1;
5536 rdev_for_each_list(rdev, tmp, &candidates) {
5537 list_del_init(&rdev->same_set);
5538 if (bind_rdev_to_array(rdev, mddev))
5539 export_rdev(rdev);
5541 autorun_array(mddev);
5542 mddev_unlock(mddev);
5544 /* on success, candidates will be empty, on error
5545 * it won't...
5547 rdev_for_each_list(rdev, tmp, &candidates) {
5548 list_del_init(&rdev->same_set);
5549 export_rdev(rdev);
5551 mddev_put(mddev);
5553 printk(KERN_INFO "md: ... autorun DONE.\n");
5555 #endif /* !MODULE */
5557 static int get_version(void __user * arg)
5559 mdu_version_t ver;
5561 ver.major = MD_MAJOR_VERSION;
5562 ver.minor = MD_MINOR_VERSION;
5563 ver.patchlevel = MD_PATCHLEVEL_VERSION;
5565 if (copy_to_user(arg, &ver, sizeof(ver)))
5566 return -EFAULT;
5568 return 0;
5571 static int get_array_info(struct mddev * mddev, void __user * arg)
5573 mdu_array_info_t info;
5574 int nr,working,insync,failed,spare;
5575 struct md_rdev *rdev;
5577 nr = working = insync = failed = spare = 0;
5578 rcu_read_lock();
5579 rdev_for_each_rcu(rdev, mddev) {
5580 nr++;
5581 if (test_bit(Faulty, &rdev->flags))
5582 failed++;
5583 else {
5584 working++;
5585 if (test_bit(In_sync, &rdev->flags))
5586 insync++;
5587 else
5588 spare++;
5591 rcu_read_unlock();
5593 info.major_version = mddev->major_version;
5594 info.minor_version = mddev->minor_version;
5595 info.patch_version = MD_PATCHLEVEL_VERSION;
5596 info.ctime = mddev->ctime;
5597 info.level = mddev->level;
5598 info.size = mddev->dev_sectors / 2;
5599 if (info.size != mddev->dev_sectors / 2) /* overflow */
5600 info.size = -1;
5601 info.nr_disks = nr;
5602 info.raid_disks = mddev->raid_disks;
5603 info.md_minor = mddev->md_minor;
5604 info.not_persistent= !mddev->persistent;
5606 info.utime = mddev->utime;
5607 info.state = 0;
5608 if (mddev->in_sync)
5609 info.state = (1<<MD_SB_CLEAN);
5610 if (mddev->bitmap && mddev->bitmap_info.offset)
5611 info.state = (1<<MD_SB_BITMAP_PRESENT);
5612 info.active_disks = insync;
5613 info.working_disks = working;
5614 info.failed_disks = failed;
5615 info.spare_disks = spare;
5617 info.layout = mddev->layout;
5618 info.chunk_size = mddev->chunk_sectors << 9;
5620 if (copy_to_user(arg, &info, sizeof(info)))
5621 return -EFAULT;
5623 return 0;
5626 static int get_bitmap_file(struct mddev * mddev, void __user * arg)
5628 mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5629 char *ptr, *buf = NULL;
5630 int err = -ENOMEM;
5632 if (md_allow_write(mddev))
5633 file = kzalloc(sizeof(*file), GFP_NOIO);
5634 else
5635 file = kzalloc(sizeof(*file), GFP_KERNEL);
5637 if (!file)
5638 goto out;
5640 /* bitmap disabled, zero the first byte and copy out */
5641 if (!mddev->bitmap || !mddev->bitmap->storage.file) {
5642 file->pathname[0] = '\0';
5643 goto copy_out;
5646 buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
5647 if (!buf)
5648 goto out;
5650 ptr = d_path(&mddev->bitmap->storage.file->f_path,
5651 buf, sizeof(file->pathname));
5652 if (IS_ERR(ptr))
5653 goto out;
5655 strcpy(file->pathname, ptr);
5657 copy_out:
5658 err = 0;
5659 if (copy_to_user(arg, file, sizeof(*file)))
5660 err = -EFAULT;
5661 out:
5662 kfree(buf);
5663 kfree(file);
5664 return err;
5667 static int get_disk_info(struct mddev * mddev, void __user * arg)
5669 mdu_disk_info_t info;
5670 struct md_rdev *rdev;
5672 if (copy_from_user(&info, arg, sizeof(info)))
5673 return -EFAULT;
5675 rcu_read_lock();
5676 rdev = find_rdev_nr_rcu(mddev, info.number);
5677 if (rdev) {
5678 info.major = MAJOR(rdev->bdev->bd_dev);
5679 info.minor = MINOR(rdev->bdev->bd_dev);
5680 info.raid_disk = rdev->raid_disk;
5681 info.state = 0;
5682 if (test_bit(Faulty, &rdev->flags))
5683 info.state |= (1<<MD_DISK_FAULTY);
5684 else if (test_bit(In_sync, &rdev->flags)) {
5685 info.state |= (1<<MD_DISK_ACTIVE);
5686 info.state |= (1<<MD_DISK_SYNC);
5688 if (test_bit(WriteMostly, &rdev->flags))
5689 info.state |= (1<<MD_DISK_WRITEMOSTLY);
5690 } else {
5691 info.major = info.minor = 0;
5692 info.raid_disk = -1;
5693 info.state = (1<<MD_DISK_REMOVED);
5695 rcu_read_unlock();
5697 if (copy_to_user(arg, &info, sizeof(info)))
5698 return -EFAULT;
5700 return 0;
5703 static int add_new_disk(struct mddev * mddev, mdu_disk_info_t *info)
5705 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5706 struct md_rdev *rdev;
5707 dev_t dev = MKDEV(info->major,info->minor);
5709 if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5710 return -EOVERFLOW;
5712 if (!mddev->raid_disks) {
5713 int err;
5714 /* expecting a device which has a superblock */
5715 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5716 if (IS_ERR(rdev)) {
5717 printk(KERN_WARNING
5718 "md: md_import_device returned %ld\n",
5719 PTR_ERR(rdev));
5720 return PTR_ERR(rdev);
5722 if (!list_empty(&mddev->disks)) {
5723 struct md_rdev *rdev0
5724 = list_entry(mddev->disks.next,
5725 struct md_rdev, same_set);
5726 err = super_types[mddev->major_version]
5727 .load_super(rdev, rdev0, mddev->minor_version);
5728 if (err < 0) {
5729 printk(KERN_WARNING
5730 "md: %s has different UUID to %s\n",
5731 bdevname(rdev->bdev,b),
5732 bdevname(rdev0->bdev,b2));
5733 export_rdev(rdev);
5734 return -EINVAL;
5737 err = bind_rdev_to_array(rdev, mddev);
5738 if (err)
5739 export_rdev(rdev);
5740 return err;
5744 * add_new_disk can be used once the array is assembled
5745 * to add "hot spares". They must already have a superblock
5746 * written
5748 if (mddev->pers) {
5749 int err;
5750 if (!mddev->pers->hot_add_disk) {
5751 printk(KERN_WARNING
5752 "%s: personality does not support diskops!\n",
5753 mdname(mddev));
5754 return -EINVAL;
5756 if (mddev->persistent)
5757 rdev = md_import_device(dev, mddev->major_version,
5758 mddev->minor_version);
5759 else
5760 rdev = md_import_device(dev, -1, -1);
5761 if (IS_ERR(rdev)) {
5762 printk(KERN_WARNING
5763 "md: md_import_device returned %ld\n",
5764 PTR_ERR(rdev));
5765 return PTR_ERR(rdev);
5767 /* set saved_raid_disk if appropriate */
5768 if (!mddev->persistent) {
5769 if (info->state & (1<<MD_DISK_SYNC) &&
5770 info->raid_disk < mddev->raid_disks) {
5771 rdev->raid_disk = info->raid_disk;
5772 set_bit(In_sync, &rdev->flags);
5773 clear_bit(Bitmap_sync, &rdev->flags);
5774 } else
5775 rdev->raid_disk = -1;
5776 } else
5777 super_types[mddev->major_version].
5778 validate_super(mddev, rdev);
5779 if ((info->state & (1<<MD_DISK_SYNC)) &&
5780 rdev->raid_disk != info->raid_disk) {
5781 /* This was a hot-add request, but events doesn't
5782 * match, so reject it.
5784 export_rdev(rdev);
5785 return -EINVAL;
5788 if (test_bit(In_sync, &rdev->flags))
5789 rdev->saved_raid_disk = rdev->raid_disk;
5790 else
5791 rdev->saved_raid_disk = -1;
5793 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5794 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5795 set_bit(WriteMostly, &rdev->flags);
5796 else
5797 clear_bit(WriteMostly, &rdev->flags);
5799 rdev->raid_disk = -1;
5800 err = bind_rdev_to_array(rdev, mddev);
5801 if (!err && !mddev->pers->hot_remove_disk) {
5802 /* If there is hot_add_disk but no hot_remove_disk
5803 * then added disks for geometry changes,
5804 * and should be added immediately.
5806 super_types[mddev->major_version].
5807 validate_super(mddev, rdev);
5808 err = mddev->pers->hot_add_disk(mddev, rdev);
5809 if (err)
5810 unbind_rdev_from_array(rdev);
5812 if (err)
5813 export_rdev(rdev);
5814 else
5815 sysfs_notify_dirent_safe(rdev->sysfs_state);
5817 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5818 if (mddev->degraded)
5819 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5820 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5821 if (!err)
5822 md_new_event(mddev);
5823 md_wakeup_thread(mddev->thread);
5824 return err;
5827 /* otherwise, add_new_disk is only allowed
5828 * for major_version==0 superblocks
5830 if (mddev->major_version != 0) {
5831 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5832 mdname(mddev));
5833 return -EINVAL;
5836 if (!(info->state & (1<<MD_DISK_FAULTY))) {
5837 int err;
5838 rdev = md_import_device(dev, -1, 0);
5839 if (IS_ERR(rdev)) {
5840 printk(KERN_WARNING
5841 "md: error, md_import_device() returned %ld\n",
5842 PTR_ERR(rdev));
5843 return PTR_ERR(rdev);
5845 rdev->desc_nr = info->number;
5846 if (info->raid_disk < mddev->raid_disks)
5847 rdev->raid_disk = info->raid_disk;
5848 else
5849 rdev->raid_disk = -1;
5851 if (rdev->raid_disk < mddev->raid_disks)
5852 if (info->state & (1<<MD_DISK_SYNC))
5853 set_bit(In_sync, &rdev->flags);
5855 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5856 set_bit(WriteMostly, &rdev->flags);
5858 if (!mddev->persistent) {
5859 printk(KERN_INFO "md: nonpersistent superblock ...\n");
5860 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5861 } else
5862 rdev->sb_start = calc_dev_sboffset(rdev);
5863 rdev->sectors = rdev->sb_start;
5865 err = bind_rdev_to_array(rdev, mddev);
5866 if (err) {
5867 export_rdev(rdev);
5868 return err;
5872 return 0;
5875 static int hot_remove_disk(struct mddev * mddev, dev_t dev)
5877 char b[BDEVNAME_SIZE];
5878 struct md_rdev *rdev;
5880 rdev = find_rdev(mddev, dev);
5881 if (!rdev)
5882 return -ENXIO;
5884 clear_bit(Blocked, &rdev->flags);
5885 remove_and_add_spares(mddev, rdev);
5887 if (rdev->raid_disk >= 0)
5888 goto busy;
5890 kick_rdev_from_array(rdev);
5891 md_update_sb(mddev, 1);
5892 md_new_event(mddev);
5894 return 0;
5895 busy:
5896 printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
5897 bdevname(rdev->bdev,b), mdname(mddev));
5898 return -EBUSY;
5901 static int hot_add_disk(struct mddev * mddev, dev_t dev)
5903 char b[BDEVNAME_SIZE];
5904 int err;
5905 struct md_rdev *rdev;
5907 if (!mddev->pers)
5908 return -ENODEV;
5910 if (mddev->major_version != 0) {
5911 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
5912 " version-0 superblocks.\n",
5913 mdname(mddev));
5914 return -EINVAL;
5916 if (!mddev->pers->hot_add_disk) {
5917 printk(KERN_WARNING
5918 "%s: personality does not support diskops!\n",
5919 mdname(mddev));
5920 return -EINVAL;
5923 rdev = md_import_device(dev, -1, 0);
5924 if (IS_ERR(rdev)) {
5925 printk(KERN_WARNING
5926 "md: error, md_import_device() returned %ld\n",
5927 PTR_ERR(rdev));
5928 return -EINVAL;
5931 if (mddev->persistent)
5932 rdev->sb_start = calc_dev_sboffset(rdev);
5933 else
5934 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5936 rdev->sectors = rdev->sb_start;
5938 if (test_bit(Faulty, &rdev->flags)) {
5939 printk(KERN_WARNING
5940 "md: can not hot-add faulty %s disk to %s!\n",
5941 bdevname(rdev->bdev,b), mdname(mddev));
5942 err = -EINVAL;
5943 goto abort_export;
5945 clear_bit(In_sync, &rdev->flags);
5946 rdev->desc_nr = -1;
5947 rdev->saved_raid_disk = -1;
5948 err = bind_rdev_to_array(rdev, mddev);
5949 if (err)
5950 goto abort_export;
5953 * The rest should better be atomic, we can have disk failures
5954 * noticed in interrupt contexts ...
5957 rdev->raid_disk = -1;
5959 md_update_sb(mddev, 1);
5962 * Kick recovery, maybe this spare has to be added to the
5963 * array immediately.
5965 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5966 md_wakeup_thread(mddev->thread);
5967 md_new_event(mddev);
5968 return 0;
5970 abort_export:
5971 export_rdev(rdev);
5972 return err;
5975 static int set_bitmap_file(struct mddev *mddev, int fd)
5977 int err;
5979 if (mddev->pers) {
5980 if (!mddev->pers->quiesce)
5981 return -EBUSY;
5982 if (mddev->recovery || mddev->sync_thread)
5983 return -EBUSY;
5984 /* we should be able to change the bitmap.. */
5988 if (fd >= 0) {
5989 if (mddev->bitmap)
5990 return -EEXIST; /* cannot add when bitmap is present */
5991 mddev->bitmap_info.file = fget(fd);
5993 if (mddev->bitmap_info.file == NULL) {
5994 printk(KERN_ERR "%s: error: failed to get bitmap file\n",
5995 mdname(mddev));
5996 return -EBADF;
5999 err = deny_bitmap_write_access(mddev->bitmap_info.file);
6000 if (err) {
6001 printk(KERN_ERR "%s: error: bitmap file is already in use\n",
6002 mdname(mddev));
6003 fput(mddev->bitmap_info.file);
6004 mddev->bitmap_info.file = NULL;
6005 return err;
6007 mddev->bitmap_info.offset = 0; /* file overrides offset */
6008 } else if (mddev->bitmap == NULL)
6009 return -ENOENT; /* cannot remove what isn't there */
6010 err = 0;
6011 if (mddev->pers) {
6012 mddev->pers->quiesce(mddev, 1);
6013 if (fd >= 0) {
6014 err = bitmap_create(mddev);
6015 if (!err)
6016 err = bitmap_load(mddev);
6018 if (fd < 0 || err) {
6019 bitmap_destroy(mddev);
6020 fd = -1; /* make sure to put the file */
6022 mddev->pers->quiesce(mddev, 0);
6024 if (fd < 0) {
6025 if (mddev->bitmap_info.file) {
6026 restore_bitmap_write_access(mddev->bitmap_info.file);
6027 fput(mddev->bitmap_info.file);
6029 mddev->bitmap_info.file = NULL;
6032 return err;
6036 * set_array_info is used two different ways
6037 * The original usage is when creating a new array.
6038 * In this usage, raid_disks is > 0 and it together with
6039 * level, size, not_persistent,layout,chunksize determine the
6040 * shape of the array.
6041 * This will always create an array with a type-0.90.0 superblock.
6042 * The newer usage is when assembling an array.
6043 * In this case raid_disks will be 0, and the major_version field is
6044 * use to determine which style super-blocks are to be found on the devices.
6045 * The minor and patch _version numbers are also kept incase the
6046 * super_block handler wishes to interpret them.
6048 static int set_array_info(struct mddev * mddev, mdu_array_info_t *info)
6051 if (info->raid_disks == 0) {
6052 /* just setting version number for superblock loading */
6053 if (info->major_version < 0 ||
6054 info->major_version >= ARRAY_SIZE(super_types) ||
6055 super_types[info->major_version].name == NULL) {
6056 /* maybe try to auto-load a module? */
6057 printk(KERN_INFO
6058 "md: superblock version %d not known\n",
6059 info->major_version);
6060 return -EINVAL;
6062 mddev->major_version = info->major_version;
6063 mddev->minor_version = info->minor_version;
6064 mddev->patch_version = info->patch_version;
6065 mddev->persistent = !info->not_persistent;
6066 /* ensure mddev_put doesn't delete this now that there
6067 * is some minimal configuration.
6069 mddev->ctime = get_seconds();
6070 return 0;
6072 mddev->major_version = MD_MAJOR_VERSION;
6073 mddev->minor_version = MD_MINOR_VERSION;
6074 mddev->patch_version = MD_PATCHLEVEL_VERSION;
6075 mddev->ctime = get_seconds();
6077 mddev->level = info->level;
6078 mddev->clevel[0] = 0;
6079 mddev->dev_sectors = 2 * (sector_t)info->size;
6080 mddev->raid_disks = info->raid_disks;
6081 /* don't set md_minor, it is determined by which /dev/md* was
6082 * openned
6084 if (info->state & (1<<MD_SB_CLEAN))
6085 mddev->recovery_cp = MaxSector;
6086 else
6087 mddev->recovery_cp = 0;
6088 mddev->persistent = ! info->not_persistent;
6089 mddev->external = 0;
6091 mddev->layout = info->layout;
6092 mddev->chunk_sectors = info->chunk_size >> 9;
6094 mddev->max_disks = MD_SB_DISKS;
6096 if (mddev->persistent)
6097 mddev->flags = 0;
6098 set_bit(MD_CHANGE_DEVS, &mddev->flags);
6100 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
6101 mddev->bitmap_info.default_space = 64*2 - (MD_SB_BYTES >> 9);
6102 mddev->bitmap_info.offset = 0;
6104 mddev->reshape_position = MaxSector;
6107 * Generate a 128 bit UUID
6109 get_random_bytes(mddev->uuid, 16);
6111 mddev->new_level = mddev->level;
6112 mddev->new_chunk_sectors = mddev->chunk_sectors;
6113 mddev->new_layout = mddev->layout;
6114 mddev->delta_disks = 0;
6115 mddev->reshape_backwards = 0;
6117 return 0;
6120 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
6122 WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
6124 if (mddev->external_size)
6125 return;
6127 mddev->array_sectors = array_sectors;
6129 EXPORT_SYMBOL(md_set_array_sectors);
6131 static int update_size(struct mddev *mddev, sector_t num_sectors)
6133 struct md_rdev *rdev;
6134 int rv;
6135 int fit = (num_sectors == 0);
6137 if (mddev->pers->resize == NULL)
6138 return -EINVAL;
6139 /* The "num_sectors" is the number of sectors of each device that
6140 * is used. This can only make sense for arrays with redundancy.
6141 * linear and raid0 always use whatever space is available. We can only
6142 * consider changing this number if no resync or reconstruction is
6143 * happening, and if the new size is acceptable. It must fit before the
6144 * sb_start or, if that is <data_offset, it must fit before the size
6145 * of each device. If num_sectors is zero, we find the largest size
6146 * that fits.
6148 if (mddev->sync_thread)
6149 return -EBUSY;
6151 rdev_for_each(rdev, mddev) {
6152 sector_t avail = rdev->sectors;
6154 if (fit && (num_sectors == 0 || num_sectors > avail))
6155 num_sectors = avail;
6156 if (avail < num_sectors)
6157 return -ENOSPC;
6159 rv = mddev->pers->resize(mddev, num_sectors);
6160 if (!rv)
6161 revalidate_disk(mddev->gendisk);
6162 return rv;
6165 static int update_raid_disks(struct mddev *mddev, int raid_disks)
6167 int rv;
6168 struct md_rdev *rdev;
6169 /* change the number of raid disks */
6170 if (mddev->pers->check_reshape == NULL)
6171 return -EINVAL;
6172 if (raid_disks <= 0 ||
6173 (mddev->max_disks && raid_disks >= mddev->max_disks))
6174 return -EINVAL;
6175 if (mddev->sync_thread || mddev->reshape_position != MaxSector)
6176 return -EBUSY;
6178 rdev_for_each(rdev, mddev) {
6179 if (mddev->raid_disks < raid_disks &&
6180 rdev->data_offset < rdev->new_data_offset)
6181 return -EINVAL;
6182 if (mddev->raid_disks > raid_disks &&
6183 rdev->data_offset > rdev->new_data_offset)
6184 return -EINVAL;
6187 mddev->delta_disks = raid_disks - mddev->raid_disks;
6188 if (mddev->delta_disks < 0)
6189 mddev->reshape_backwards = 1;
6190 else if (mddev->delta_disks > 0)
6191 mddev->reshape_backwards = 0;
6193 rv = mddev->pers->check_reshape(mddev);
6194 if (rv < 0) {
6195 mddev->delta_disks = 0;
6196 mddev->reshape_backwards = 0;
6198 return rv;
6203 * update_array_info is used to change the configuration of an
6204 * on-line array.
6205 * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
6206 * fields in the info are checked against the array.
6207 * Any differences that cannot be handled will cause an error.
6208 * Normally, only one change can be managed at a time.
6210 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
6212 int rv = 0;
6213 int cnt = 0;
6214 int state = 0;
6216 /* calculate expected state,ignoring low bits */
6217 if (mddev->bitmap && mddev->bitmap_info.offset)
6218 state |= (1 << MD_SB_BITMAP_PRESENT);
6220 if (mddev->major_version != info->major_version ||
6221 mddev->minor_version != info->minor_version ||
6222 /* mddev->patch_version != info->patch_version || */
6223 mddev->ctime != info->ctime ||
6224 mddev->level != info->level ||
6225 /* mddev->layout != info->layout || */
6226 mddev->persistent != !info->not_persistent ||
6227 mddev->chunk_sectors != info->chunk_size >> 9 ||
6228 /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6229 ((state^info->state) & 0xfffffe00)
6231 return -EINVAL;
6232 /* Check there is only one change */
6233 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6234 cnt++;
6235 if (mddev->raid_disks != info->raid_disks)
6236 cnt++;
6237 if (mddev->layout != info->layout)
6238 cnt++;
6239 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6240 cnt++;
6241 if (cnt == 0)
6242 return 0;
6243 if (cnt > 1)
6244 return -EINVAL;
6246 if (mddev->layout != info->layout) {
6247 /* Change layout
6248 * we don't need to do anything at the md level, the
6249 * personality will take care of it all.
6251 if (mddev->pers->check_reshape == NULL)
6252 return -EINVAL;
6253 else {
6254 mddev->new_layout = info->layout;
6255 rv = mddev->pers->check_reshape(mddev);
6256 if (rv)
6257 mddev->new_layout = mddev->layout;
6258 return rv;
6261 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6262 rv = update_size(mddev, (sector_t)info->size * 2);
6264 if (mddev->raid_disks != info->raid_disks)
6265 rv = update_raid_disks(mddev, info->raid_disks);
6267 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6268 if (mddev->pers->quiesce == NULL)
6269 return -EINVAL;
6270 if (mddev->recovery || mddev->sync_thread)
6271 return -EBUSY;
6272 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
6273 /* add the bitmap */
6274 if (mddev->bitmap)
6275 return -EEXIST;
6276 if (mddev->bitmap_info.default_offset == 0)
6277 return -EINVAL;
6278 mddev->bitmap_info.offset =
6279 mddev->bitmap_info.default_offset;
6280 mddev->bitmap_info.space =
6281 mddev->bitmap_info.default_space;
6282 mddev->pers->quiesce(mddev, 1);
6283 rv = bitmap_create(mddev);
6284 if (!rv)
6285 rv = bitmap_load(mddev);
6286 if (rv)
6287 bitmap_destroy(mddev);
6288 mddev->pers->quiesce(mddev, 0);
6289 } else {
6290 /* remove the bitmap */
6291 if (!mddev->bitmap)
6292 return -ENOENT;
6293 if (mddev->bitmap->storage.file)
6294 return -EINVAL;
6295 mddev->pers->quiesce(mddev, 1);
6296 bitmap_destroy(mddev);
6297 mddev->pers->quiesce(mddev, 0);
6298 mddev->bitmap_info.offset = 0;
6301 md_update_sb(mddev, 1);
6302 return rv;
6305 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
6307 struct md_rdev *rdev;
6308 int err = 0;
6310 if (mddev->pers == NULL)
6311 return -ENODEV;
6313 rcu_read_lock();
6314 rdev = find_rdev_rcu(mddev, dev);
6315 if (!rdev)
6316 err = -ENODEV;
6317 else {
6318 md_error(mddev, rdev);
6319 if (!test_bit(Faulty, &rdev->flags))
6320 err = -EBUSY;
6322 rcu_read_unlock();
6323 return err;
6327 * We have a problem here : there is no easy way to give a CHS
6328 * virtual geometry. We currently pretend that we have a 2 heads
6329 * 4 sectors (with a BIG number of cylinders...). This drives
6330 * dosfs just mad... ;-)
6332 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
6334 struct mddev *mddev = bdev->bd_disk->private_data;
6336 geo->heads = 2;
6337 geo->sectors = 4;
6338 geo->cylinders = mddev->array_sectors / 8;
6339 return 0;
6342 static int md_ioctl(struct block_device *bdev, fmode_t mode,
6343 unsigned int cmd, unsigned long arg)
6345 int err = 0;
6346 void __user *argp = (void __user *)arg;
6347 struct mddev *mddev = NULL;
6348 int ro;
6350 switch (cmd) {
6351 case RAID_VERSION:
6352 case GET_ARRAY_INFO:
6353 case GET_DISK_INFO:
6354 break;
6355 default:
6356 if (!capable(CAP_SYS_ADMIN))
6357 return -EACCES;
6361 * Commands dealing with the RAID driver but not any
6362 * particular array:
6364 switch (cmd) {
6365 case RAID_VERSION:
6366 err = get_version(argp);
6367 goto done;
6369 case PRINT_RAID_DEBUG:
6370 err = 0;
6371 md_print_devices();
6372 goto done;
6374 #ifndef MODULE
6375 case RAID_AUTORUN:
6376 err = 0;
6377 autostart_arrays(arg);
6378 goto done;
6379 #endif
6380 default:;
6384 * Commands creating/starting a new array:
6387 mddev = bdev->bd_disk->private_data;
6389 if (!mddev) {
6390 BUG();
6391 goto abort;
6394 /* Some actions do not requires the mutex */
6395 switch (cmd) {
6396 case GET_ARRAY_INFO:
6397 if (!mddev->raid_disks && !mddev->external)
6398 err = -ENODEV;
6399 else
6400 err = get_array_info(mddev, argp);
6401 goto abort;
6403 case GET_DISK_INFO:
6404 if (!mddev->raid_disks && !mddev->external)
6405 err = -ENODEV;
6406 else
6407 err = get_disk_info(mddev, argp);
6408 goto abort;
6410 case SET_DISK_FAULTY:
6411 err = set_disk_faulty(mddev, new_decode_dev(arg));
6412 goto abort;
6415 if (cmd == ADD_NEW_DISK)
6416 /* need to ensure md_delayed_delete() has completed */
6417 flush_workqueue(md_misc_wq);
6419 err = mddev_lock(mddev);
6420 if (err) {
6421 printk(KERN_INFO
6422 "md: ioctl lock interrupted, reason %d, cmd %d\n",
6423 err, cmd);
6424 goto abort;
6427 if (cmd == SET_ARRAY_INFO) {
6428 mdu_array_info_t info;
6429 if (!arg)
6430 memset(&info, 0, sizeof(info));
6431 else if (copy_from_user(&info, argp, sizeof(info))) {
6432 err = -EFAULT;
6433 goto abort_unlock;
6435 if (mddev->pers) {
6436 err = update_array_info(mddev, &info);
6437 if (err) {
6438 printk(KERN_WARNING "md: couldn't update"
6439 " array info. %d\n", err);
6440 goto abort_unlock;
6442 goto done_unlock;
6444 if (!list_empty(&mddev->disks)) {
6445 printk(KERN_WARNING
6446 "md: array %s already has disks!\n",
6447 mdname(mddev));
6448 err = -EBUSY;
6449 goto abort_unlock;
6451 if (mddev->raid_disks) {
6452 printk(KERN_WARNING
6453 "md: array %s already initialised!\n",
6454 mdname(mddev));
6455 err = -EBUSY;
6456 goto abort_unlock;
6458 err = set_array_info(mddev, &info);
6459 if (err) {
6460 printk(KERN_WARNING "md: couldn't set"
6461 " array info. %d\n", err);
6462 goto abort_unlock;
6464 goto done_unlock;
6468 * Commands querying/configuring an existing array:
6470 /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
6471 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
6472 if ((!mddev->raid_disks && !mddev->external)
6473 && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
6474 && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
6475 && cmd != GET_BITMAP_FILE) {
6476 err = -ENODEV;
6477 goto abort_unlock;
6481 * Commands even a read-only array can execute:
6483 switch (cmd) {
6484 case GET_BITMAP_FILE:
6485 err = get_bitmap_file(mddev, argp);
6486 goto done_unlock;
6488 case RESTART_ARRAY_RW:
6489 err = restart_array(mddev);
6490 goto done_unlock;
6492 case STOP_ARRAY:
6493 err = do_md_stop(mddev, 0, bdev);
6494 goto done_unlock;
6496 case STOP_ARRAY_RO:
6497 err = md_set_readonly(mddev, bdev);
6498 goto done_unlock;
6500 case HOT_REMOVE_DISK:
6501 err = hot_remove_disk(mddev, new_decode_dev(arg));
6502 goto done_unlock;
6504 case ADD_NEW_DISK:
6505 /* We can support ADD_NEW_DISK on read-only arrays
6506 * on if we are re-adding a preexisting device.
6507 * So require mddev->pers and MD_DISK_SYNC.
6509 if (mddev->pers) {
6510 mdu_disk_info_t info;
6511 if (copy_from_user(&info, argp, sizeof(info)))
6512 err = -EFAULT;
6513 else if (!(info.state & (1<<MD_DISK_SYNC)))
6514 /* Need to clear read-only for this */
6515 break;
6516 else
6517 err = add_new_disk(mddev, &info);
6518 goto done_unlock;
6520 break;
6522 case BLKROSET:
6523 if (get_user(ro, (int __user *)(arg))) {
6524 err = -EFAULT;
6525 goto done_unlock;
6527 err = -EINVAL;
6529 /* if the bdev is going readonly the value of mddev->ro
6530 * does not matter, no writes are coming
6532 if (ro)
6533 goto done_unlock;
6535 /* are we are already prepared for writes? */
6536 if (mddev->ro != 1)
6537 goto done_unlock;
6539 /* transitioning to readauto need only happen for
6540 * arrays that call md_write_start
6542 if (mddev->pers) {
6543 err = restart_array(mddev);
6544 if (err == 0) {
6545 mddev->ro = 2;
6546 set_disk_ro(mddev->gendisk, 0);
6549 goto done_unlock;
6553 * The remaining ioctls are changing the state of the
6554 * superblock, so we do not allow them on read-only arrays.
6555 * However non-MD ioctls (e.g. get-size) will still come through
6556 * here and hit the 'default' below, so only disallow
6557 * 'md' ioctls, and switch to rw mode if started auto-readonly.
6559 if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
6560 if (mddev->ro == 2) {
6561 mddev->ro = 0;
6562 sysfs_notify_dirent_safe(mddev->sysfs_state);
6563 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6564 /* mddev_unlock will wake thread */
6565 /* If a device failed while we were read-only, we
6566 * need to make sure the metadata is updated now.
6568 if (test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
6569 mddev_unlock(mddev);
6570 wait_event(mddev->sb_wait,
6571 !test_bit(MD_CHANGE_DEVS, &mddev->flags) &&
6572 !test_bit(MD_CHANGE_PENDING, &mddev->flags));
6573 mddev_lock(mddev);
6575 } else {
6576 err = -EROFS;
6577 goto abort_unlock;
6581 switch (cmd) {
6582 case ADD_NEW_DISK:
6584 mdu_disk_info_t info;
6585 if (copy_from_user(&info, argp, sizeof(info)))
6586 err = -EFAULT;
6587 else
6588 err = add_new_disk(mddev, &info);
6589 goto done_unlock;
6592 case HOT_ADD_DISK:
6593 err = hot_add_disk(mddev, new_decode_dev(arg));
6594 goto done_unlock;
6596 case RUN_ARRAY:
6597 err = do_md_run(mddev);
6598 goto done_unlock;
6600 case SET_BITMAP_FILE:
6601 err = set_bitmap_file(mddev, (int)arg);
6602 goto done_unlock;
6604 default:
6605 err = -EINVAL;
6606 goto abort_unlock;
6609 done_unlock:
6610 abort_unlock:
6611 if (mddev->hold_active == UNTIL_IOCTL &&
6612 err != -EINVAL)
6613 mddev->hold_active = 0;
6614 mddev_unlock(mddev);
6616 return err;
6617 done:
6618 if (err)
6619 MD_BUG();
6620 abort:
6621 return err;
6623 #ifdef CONFIG_COMPAT
6624 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
6625 unsigned int cmd, unsigned long arg)
6627 switch (cmd) {
6628 case HOT_REMOVE_DISK:
6629 case HOT_ADD_DISK:
6630 case SET_DISK_FAULTY:
6631 case SET_BITMAP_FILE:
6632 /* These take in integer arg, do not convert */
6633 break;
6634 default:
6635 arg = (unsigned long)compat_ptr(arg);
6636 break;
6639 return md_ioctl(bdev, mode, cmd, arg);
6641 #endif /* CONFIG_COMPAT */
6643 static int md_open(struct block_device *bdev, fmode_t mode)
6646 * Succeed if we can lock the mddev, which confirms that
6647 * it isn't being stopped right now.
6649 struct mddev *mddev = mddev_find(bdev->bd_dev);
6650 int err;
6652 if (!mddev)
6653 return -ENODEV;
6655 if (mddev->gendisk != bdev->bd_disk) {
6656 /* we are racing with mddev_put which is discarding this
6657 * bd_disk.
6659 mddev_put(mddev);
6660 /* Wait until bdev->bd_disk is definitely gone */
6661 flush_workqueue(md_misc_wq);
6662 /* Then retry the open from the top */
6663 return -ERESTARTSYS;
6665 BUG_ON(mddev != bdev->bd_disk->private_data);
6667 if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
6668 goto out;
6670 err = 0;
6671 atomic_inc(&mddev->openers);
6672 mutex_unlock(&mddev->open_mutex);
6674 check_disk_change(bdev);
6675 out:
6676 return err;
6679 static void md_release(struct gendisk *disk, fmode_t mode)
6681 struct mddev *mddev = disk->private_data;
6683 BUG_ON(!mddev);
6684 atomic_dec(&mddev->openers);
6685 mddev_put(mddev);
6688 static int md_media_changed(struct gendisk *disk)
6690 struct mddev *mddev = disk->private_data;
6692 return mddev->changed;
6695 static int md_revalidate(struct gendisk *disk)
6697 struct mddev *mddev = disk->private_data;
6699 mddev->changed = 0;
6700 return 0;
6702 static const struct block_device_operations md_fops =
6704 .owner = THIS_MODULE,
6705 .open = md_open,
6706 .release = md_release,
6707 .ioctl = md_ioctl,
6708 #ifdef CONFIG_COMPAT
6709 .compat_ioctl = md_compat_ioctl,
6710 #endif
6711 .getgeo = md_getgeo,
6712 .media_changed = md_media_changed,
6713 .revalidate_disk= md_revalidate,
6716 static int md_thread(void * arg)
6718 struct md_thread *thread = arg;
6721 * md_thread is a 'system-thread', it's priority should be very
6722 * high. We avoid resource deadlocks individually in each
6723 * raid personality. (RAID5 does preallocation) We also use RR and
6724 * the very same RT priority as kswapd, thus we will never get
6725 * into a priority inversion deadlock.
6727 * we definitely have to have equal or higher priority than
6728 * bdflush, otherwise bdflush will deadlock if there are too
6729 * many dirty RAID5 blocks.
6732 allow_signal(SIGKILL);
6733 while (!kthread_should_stop()) {
6735 /* We need to wait INTERRUPTIBLE so that
6736 * we don't add to the load-average.
6737 * That means we need to be sure no signals are
6738 * pending
6740 if (signal_pending(current))
6741 flush_signals(current);
6743 wait_event_interruptible_timeout
6744 (thread->wqueue,
6745 test_bit(THREAD_WAKEUP, &thread->flags)
6746 || kthread_should_stop(),
6747 thread->timeout);
6749 clear_bit(THREAD_WAKEUP, &thread->flags);
6750 if (!kthread_should_stop())
6751 thread->run(thread);
6754 return 0;
6757 void md_wakeup_thread(struct md_thread *thread)
6759 if (thread) {
6760 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
6761 set_bit(THREAD_WAKEUP, &thread->flags);
6762 wake_up(&thread->wqueue);
6766 struct md_thread *md_register_thread(void (*run) (struct md_thread *),
6767 struct mddev *mddev, const char *name)
6769 struct md_thread *thread;
6771 thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
6772 if (!thread)
6773 return NULL;
6775 init_waitqueue_head(&thread->wqueue);
6777 thread->run = run;
6778 thread->mddev = mddev;
6779 thread->timeout = MAX_SCHEDULE_TIMEOUT;
6780 thread->tsk = kthread_run(md_thread, thread,
6781 "%s_%s",
6782 mdname(thread->mddev),
6783 name);
6784 if (IS_ERR(thread->tsk)) {
6785 kfree(thread);
6786 return NULL;
6788 return thread;
6791 void md_unregister_thread(struct md_thread **threadp)
6793 struct md_thread *thread = *threadp;
6794 if (!thread)
6795 return;
6796 pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
6797 /* Locking ensures that mddev_unlock does not wake_up a
6798 * non-existent thread
6800 spin_lock(&pers_lock);
6801 *threadp = NULL;
6802 spin_unlock(&pers_lock);
6804 kthread_stop(thread->tsk);
6805 kfree(thread);
6808 void md_error(struct mddev *mddev, struct md_rdev *rdev)
6810 if (!mddev) {
6811 MD_BUG();
6812 return;
6815 if (!rdev || test_bit(Faulty, &rdev->flags))
6816 return;
6818 if (!mddev->pers || !mddev->pers->error_handler)
6819 return;
6820 mddev->pers->error_handler(mddev,rdev);
6821 if (mddev->degraded)
6822 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6823 sysfs_notify_dirent_safe(rdev->sysfs_state);
6824 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6825 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6826 md_wakeup_thread(mddev->thread);
6827 if (mddev->event_work.func)
6828 queue_work(md_misc_wq, &mddev->event_work);
6829 md_new_event_inintr(mddev);
6832 /* seq_file implementation /proc/mdstat */
6834 static void status_unused(struct seq_file *seq)
6836 int i = 0;
6837 struct md_rdev *rdev;
6839 seq_printf(seq, "unused devices: ");
6841 list_for_each_entry(rdev, &pending_raid_disks, same_set) {
6842 char b[BDEVNAME_SIZE];
6843 i++;
6844 seq_printf(seq, "%s ",
6845 bdevname(rdev->bdev,b));
6847 if (!i)
6848 seq_printf(seq, "<none>");
6850 seq_printf(seq, "\n");
6854 static void status_resync(struct seq_file *seq, struct mddev * mddev)
6856 sector_t max_sectors, resync, res;
6857 unsigned long dt, db;
6858 sector_t rt;
6859 int scale;
6860 unsigned int per_milli;
6862 if (mddev->curr_resync <= 3)
6863 resync = 0;
6864 else
6865 resync = mddev->curr_resync
6866 - atomic_read(&mddev->recovery_active);
6868 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ||
6869 test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6870 max_sectors = mddev->resync_max_sectors;
6871 else
6872 max_sectors = mddev->dev_sectors;
6875 * Should not happen.
6877 if (!max_sectors) {
6878 MD_BUG();
6879 return;
6881 /* Pick 'scale' such that (resync>>scale)*1000 will fit
6882 * in a sector_t, and (max_sectors>>scale) will fit in a
6883 * u32, as those are the requirements for sector_div.
6884 * Thus 'scale' must be at least 10
6886 scale = 10;
6887 if (sizeof(sector_t) > sizeof(unsigned long)) {
6888 while ( max_sectors/2 > (1ULL<<(scale+32)))
6889 scale++;
6891 res = (resync>>scale)*1000;
6892 sector_div(res, (u32)((max_sectors>>scale)+1));
6894 per_milli = res;
6896 int i, x = per_milli/50, y = 20-x;
6897 seq_printf(seq, "[");
6898 for (i = 0; i < x; i++)
6899 seq_printf(seq, "=");
6900 seq_printf(seq, ">");
6901 for (i = 0; i < y; i++)
6902 seq_printf(seq, ".");
6903 seq_printf(seq, "] ");
6905 seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
6906 (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
6907 "reshape" :
6908 (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
6909 "check" :
6910 (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
6911 "resync" : "recovery"))),
6912 per_milli/10, per_milli % 10,
6913 (unsigned long long) resync/2,
6914 (unsigned long long) max_sectors/2);
6917 * dt: time from mark until now
6918 * db: blocks written from mark until now
6919 * rt: remaining time
6921 * rt is a sector_t, so could be 32bit or 64bit.
6922 * So we divide before multiply in case it is 32bit and close
6923 * to the limit.
6924 * We scale the divisor (db) by 32 to avoid losing precision
6925 * near the end of resync when the number of remaining sectors
6926 * is close to 'db'.
6927 * We then divide rt by 32 after multiplying by db to compensate.
6928 * The '+1' avoids division by zero if db is very small.
6930 dt = ((jiffies - mddev->resync_mark) / HZ);
6931 if (!dt) dt++;
6932 db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
6933 - mddev->resync_mark_cnt;
6935 rt = max_sectors - resync; /* number of remaining sectors */
6936 sector_div(rt, db/32+1);
6937 rt *= dt;
6938 rt >>= 5;
6940 seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
6941 ((unsigned long)rt % 60)/6);
6943 seq_printf(seq, " speed=%ldK/sec", db/2/dt);
6946 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
6948 struct list_head *tmp;
6949 loff_t l = *pos;
6950 struct mddev *mddev;
6952 if (l >= 0x10000)
6953 return NULL;
6954 if (!l--)
6955 /* header */
6956 return (void*)1;
6958 spin_lock(&all_mddevs_lock);
6959 list_for_each(tmp,&all_mddevs)
6960 if (!l--) {
6961 mddev = list_entry(tmp, struct mddev, all_mddevs);
6962 mddev_get(mddev);
6963 spin_unlock(&all_mddevs_lock);
6964 return mddev;
6966 spin_unlock(&all_mddevs_lock);
6967 if (!l--)
6968 return (void*)2;/* tail */
6969 return NULL;
6972 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
6974 struct list_head *tmp;
6975 struct mddev *next_mddev, *mddev = v;
6977 ++*pos;
6978 if (v == (void*)2)
6979 return NULL;
6981 spin_lock(&all_mddevs_lock);
6982 if (v == (void*)1)
6983 tmp = all_mddevs.next;
6984 else
6985 tmp = mddev->all_mddevs.next;
6986 if (tmp != &all_mddevs)
6987 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
6988 else {
6989 next_mddev = (void*)2;
6990 *pos = 0x10000;
6992 spin_unlock(&all_mddevs_lock);
6994 if (v != (void*)1)
6995 mddev_put(mddev);
6996 return next_mddev;
7000 static void md_seq_stop(struct seq_file *seq, void *v)
7002 struct mddev *mddev = v;
7004 if (mddev && v != (void*)1 && v != (void*)2)
7005 mddev_put(mddev);
7008 static int md_seq_show(struct seq_file *seq, void *v)
7010 struct mddev *mddev = v;
7011 sector_t sectors;
7012 struct md_rdev *rdev;
7014 if (v == (void*)1) {
7015 struct md_personality *pers;
7016 seq_printf(seq, "Personalities : ");
7017 spin_lock(&pers_lock);
7018 list_for_each_entry(pers, &pers_list, list)
7019 seq_printf(seq, "[%s] ", pers->name);
7021 spin_unlock(&pers_lock);
7022 seq_printf(seq, "\n");
7023 seq->poll_event = atomic_read(&md_event_count);
7024 return 0;
7026 if (v == (void*)2) {
7027 status_unused(seq);
7028 return 0;
7031 if (mddev_lock(mddev) < 0)
7032 return -EINTR;
7034 if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
7035 seq_printf(seq, "%s : %sactive", mdname(mddev),
7036 mddev->pers ? "" : "in");
7037 if (mddev->pers) {
7038 if (mddev->ro==1)
7039 seq_printf(seq, " (read-only)");
7040 if (mddev->ro==2)
7041 seq_printf(seq, " (auto-read-only)");
7042 seq_printf(seq, " %s", mddev->pers->name);
7045 sectors = 0;
7046 rdev_for_each(rdev, mddev) {
7047 char b[BDEVNAME_SIZE];
7048 seq_printf(seq, " %s[%d]",
7049 bdevname(rdev->bdev,b), rdev->desc_nr);
7050 if (test_bit(WriteMostly, &rdev->flags))
7051 seq_printf(seq, "(W)");
7052 if (test_bit(Faulty, &rdev->flags)) {
7053 seq_printf(seq, "(F)");
7054 continue;
7056 if (rdev->raid_disk < 0)
7057 seq_printf(seq, "(S)"); /* spare */
7058 if (test_bit(Replacement, &rdev->flags))
7059 seq_printf(seq, "(R)");
7060 sectors += rdev->sectors;
7063 if (!list_empty(&mddev->disks)) {
7064 if (mddev->pers)
7065 seq_printf(seq, "\n %llu blocks",
7066 (unsigned long long)
7067 mddev->array_sectors / 2);
7068 else
7069 seq_printf(seq, "\n %llu blocks",
7070 (unsigned long long)sectors / 2);
7072 if (mddev->persistent) {
7073 if (mddev->major_version != 0 ||
7074 mddev->minor_version != 90) {
7075 seq_printf(seq," super %d.%d",
7076 mddev->major_version,
7077 mddev->minor_version);
7079 } else if (mddev->external)
7080 seq_printf(seq, " super external:%s",
7081 mddev->metadata_type);
7082 else
7083 seq_printf(seq, " super non-persistent");
7085 if (mddev->pers) {
7086 mddev->pers->status(seq, mddev);
7087 seq_printf(seq, "\n ");
7088 if (mddev->pers->sync_request) {
7089 if (mddev->curr_resync > 2) {
7090 status_resync(seq, mddev);
7091 seq_printf(seq, "\n ");
7092 } else if (mddev->curr_resync >= 1)
7093 seq_printf(seq, "\tresync=DELAYED\n ");
7094 else if (mddev->recovery_cp < MaxSector)
7095 seq_printf(seq, "\tresync=PENDING\n ");
7097 } else
7098 seq_printf(seq, "\n ");
7100 bitmap_status(seq, mddev->bitmap);
7102 seq_printf(seq, "\n");
7104 mddev_unlock(mddev);
7106 return 0;
7109 static const struct seq_operations md_seq_ops = {
7110 .start = md_seq_start,
7111 .next = md_seq_next,
7112 .stop = md_seq_stop,
7113 .show = md_seq_show,
7116 static int md_seq_open(struct inode *inode, struct file *file)
7118 struct seq_file *seq;
7119 int error;
7121 error = seq_open(file, &md_seq_ops);
7122 if (error)
7123 return error;
7125 seq = file->private_data;
7126 seq->poll_event = atomic_read(&md_event_count);
7127 return error;
7130 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
7132 struct seq_file *seq = filp->private_data;
7133 int mask;
7135 poll_wait(filp, &md_event_waiters, wait);
7137 /* always allow read */
7138 mask = POLLIN | POLLRDNORM;
7140 if (seq->poll_event != atomic_read(&md_event_count))
7141 mask |= POLLERR | POLLPRI;
7142 return mask;
7145 static const struct file_operations md_seq_fops = {
7146 .owner = THIS_MODULE,
7147 .open = md_seq_open,
7148 .read = seq_read,
7149 .llseek = seq_lseek,
7150 .release = seq_release_private,
7151 .poll = mdstat_poll,
7154 int register_md_personality(struct md_personality *p)
7156 spin_lock(&pers_lock);
7157 list_add_tail(&p->list, &pers_list);
7158 printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
7159 spin_unlock(&pers_lock);
7160 return 0;
7163 int unregister_md_personality(struct md_personality *p)
7165 printk(KERN_INFO "md: %s personality unregistered\n", p->name);
7166 spin_lock(&pers_lock);
7167 list_del_init(&p->list);
7168 spin_unlock(&pers_lock);
7169 return 0;
7172 static int is_mddev_idle(struct mddev *mddev, int init)
7174 struct md_rdev * rdev;
7175 int idle;
7176 int curr_events;
7178 idle = 1;
7179 rcu_read_lock();
7180 rdev_for_each_rcu(rdev, mddev) {
7181 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
7182 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
7183 (int)part_stat_read(&disk->part0, sectors[1]) -
7184 atomic_read(&disk->sync_io);
7185 /* sync IO will cause sync_io to increase before the disk_stats
7186 * as sync_io is counted when a request starts, and
7187 * disk_stats is counted when it completes.
7188 * So resync activity will cause curr_events to be smaller than
7189 * when there was no such activity.
7190 * non-sync IO will cause disk_stat to increase without
7191 * increasing sync_io so curr_events will (eventually)
7192 * be larger than it was before. Once it becomes
7193 * substantially larger, the test below will cause
7194 * the array to appear non-idle, and resync will slow
7195 * down.
7196 * If there is a lot of outstanding resync activity when
7197 * we set last_event to curr_events, then all that activity
7198 * completing might cause the array to appear non-idle
7199 * and resync will be slowed down even though there might
7200 * not have been non-resync activity. This will only
7201 * happen once though. 'last_events' will soon reflect
7202 * the state where there is little or no outstanding
7203 * resync requests, and further resync activity will
7204 * always make curr_events less than last_events.
7207 if (init || curr_events - rdev->last_events > 64) {
7208 rdev->last_events = curr_events;
7209 idle = 0;
7212 rcu_read_unlock();
7213 return idle;
7216 void md_done_sync(struct mddev *mddev, int blocks, int ok)
7218 /* another "blocks" (512byte) blocks have been synced */
7219 atomic_sub(blocks, &mddev->recovery_active);
7220 wake_up(&mddev->recovery_wait);
7221 if (!ok) {
7222 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7223 set_bit(MD_RECOVERY_ERROR, &mddev->recovery);
7224 md_wakeup_thread(mddev->thread);
7225 // stop recovery, signal do_sync ....
7230 /* md_write_start(mddev, bi)
7231 * If we need to update some array metadata (e.g. 'active' flag
7232 * in superblock) before writing, schedule a superblock update
7233 * and wait for it to complete.
7235 void md_write_start(struct mddev *mddev, struct bio *bi)
7237 int did_change = 0;
7238 if (bio_data_dir(bi) != WRITE)
7239 return;
7241 BUG_ON(mddev->ro == 1);
7242 if (mddev->ro == 2) {
7243 /* need to switch to read/write */
7244 mddev->ro = 0;
7245 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7246 md_wakeup_thread(mddev->thread);
7247 md_wakeup_thread(mddev->sync_thread);
7248 did_change = 1;
7250 atomic_inc(&mddev->writes_pending);
7251 if (mddev->safemode == 1)
7252 mddev->safemode = 0;
7253 if (mddev->in_sync) {
7254 spin_lock_irq(&mddev->write_lock);
7255 if (mddev->in_sync) {
7256 mddev->in_sync = 0;
7257 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7258 set_bit(MD_CHANGE_PENDING, &mddev->flags);
7259 md_wakeup_thread(mddev->thread);
7260 did_change = 1;
7262 spin_unlock_irq(&mddev->write_lock);
7264 if (did_change)
7265 sysfs_notify_dirent_safe(mddev->sysfs_state);
7266 wait_event(mddev->sb_wait,
7267 !test_bit(MD_CHANGE_PENDING, &mddev->flags));
7270 void md_write_end(struct mddev *mddev)
7272 if (atomic_dec_and_test(&mddev->writes_pending)) {
7273 if (mddev->safemode == 2)
7274 md_wakeup_thread(mddev->thread);
7275 else if (mddev->safemode_delay)
7276 mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
7280 /* md_allow_write(mddev)
7281 * Calling this ensures that the array is marked 'active' so that writes
7282 * may proceed without blocking. It is important to call this before
7283 * attempting a GFP_KERNEL allocation while holding the mddev lock.
7284 * Must be called with mddev_lock held.
7286 * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
7287 * is dropped, so return -EAGAIN after notifying userspace.
7289 int md_allow_write(struct mddev *mddev)
7291 if (!mddev->pers)
7292 return 0;
7293 if (mddev->ro)
7294 return 0;
7295 if (!mddev->pers->sync_request)
7296 return 0;
7298 spin_lock_irq(&mddev->write_lock);
7299 if (mddev->in_sync) {
7300 mddev->in_sync = 0;
7301 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7302 set_bit(MD_CHANGE_PENDING, &mddev->flags);
7303 if (mddev->safemode_delay &&
7304 mddev->safemode == 0)
7305 mddev->safemode = 1;
7306 spin_unlock_irq(&mddev->write_lock);
7307 md_update_sb(mddev, 0);
7308 sysfs_notify_dirent_safe(mddev->sysfs_state);
7309 } else
7310 spin_unlock_irq(&mddev->write_lock);
7312 if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
7313 return -EAGAIN;
7314 else
7315 return 0;
7317 EXPORT_SYMBOL_GPL(md_allow_write);
7319 #define SYNC_MARKS 10
7320 #define SYNC_MARK_STEP (3*HZ)
7321 #define UPDATE_FREQUENCY (5*60*HZ)
7322 void md_do_sync(struct md_thread *thread)
7324 struct mddev *mddev = thread->mddev;
7325 struct mddev *mddev2;
7326 unsigned int currspeed = 0,
7327 window;
7328 sector_t max_sectors,j, io_sectors;
7329 unsigned long mark[SYNC_MARKS];
7330 unsigned long update_time;
7331 sector_t mark_cnt[SYNC_MARKS];
7332 int last_mark,m;
7333 struct list_head *tmp;
7334 sector_t last_check;
7335 int skipped = 0;
7336 struct md_rdev *rdev;
7337 char *desc;
7338 struct blk_plug plug;
7340 /* just incase thread restarts... */
7341 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7342 return;
7343 if (mddev->ro) {/* never try to sync a read-only array */
7344 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7345 return;
7348 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7349 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
7350 desc = "data-check";
7351 else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7352 desc = "requested-resync";
7353 else
7354 desc = "resync";
7355 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7356 desc = "reshape";
7357 else
7358 desc = "recovery";
7360 /* we overload curr_resync somewhat here.
7361 * 0 == not engaged in resync at all
7362 * 2 == checking that there is no conflict with another sync
7363 * 1 == like 2, but have yielded to allow conflicting resync to
7364 * commense
7365 * other == active in resync - this many blocks
7367 * Before starting a resync we must have set curr_resync to
7368 * 2, and then checked that every "conflicting" array has curr_resync
7369 * less than ours. When we find one that is the same or higher
7370 * we wait on resync_wait. To avoid deadlock, we reduce curr_resync
7371 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
7372 * This will mean we have to start checking from the beginning again.
7376 do {
7377 mddev->curr_resync = 2;
7379 try_again:
7380 if (kthread_should_stop())
7381 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7383 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7384 goto skip;
7385 for_each_mddev(mddev2, tmp) {
7386 if (mddev2 == mddev)
7387 continue;
7388 if (!mddev->parallel_resync
7389 && mddev2->curr_resync
7390 && match_mddev_units(mddev, mddev2)) {
7391 DEFINE_WAIT(wq);
7392 if (mddev < mddev2 && mddev->curr_resync == 2) {
7393 /* arbitrarily yield */
7394 mddev->curr_resync = 1;
7395 wake_up(&resync_wait);
7397 if (mddev > mddev2 && mddev->curr_resync == 1)
7398 /* no need to wait here, we can wait the next
7399 * time 'round when curr_resync == 2
7401 continue;
7402 /* We need to wait 'interruptible' so as not to
7403 * contribute to the load average, and not to
7404 * be caught by 'softlockup'
7406 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
7407 if (!kthread_should_stop() &&
7408 mddev2->curr_resync >= mddev->curr_resync) {
7409 printk(KERN_INFO "md: delaying %s of %s"
7410 " until %s has finished (they"
7411 " share one or more physical units)\n",
7412 desc, mdname(mddev), mdname(mddev2));
7413 mddev_put(mddev2);
7414 if (signal_pending(current))
7415 flush_signals(current);
7416 schedule();
7417 finish_wait(&resync_wait, &wq);
7418 goto try_again;
7420 finish_wait(&resync_wait, &wq);
7423 } while (mddev->curr_resync < 2);
7425 j = 0;
7426 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7427 /* resync follows the size requested by the personality,
7428 * which defaults to physical size, but can be virtual size
7430 max_sectors = mddev->resync_max_sectors;
7431 atomic64_set(&mddev->resync_mismatches, 0);
7432 /* we don't use the checkpoint if there's a bitmap */
7433 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7434 j = mddev->resync_min;
7435 else if (!mddev->bitmap)
7436 j = mddev->recovery_cp;
7438 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7439 max_sectors = mddev->resync_max_sectors;
7440 else {
7441 /* recovery follows the physical size of devices */
7442 max_sectors = mddev->dev_sectors;
7443 j = MaxSector;
7444 rcu_read_lock();
7445 rdev_for_each_rcu(rdev, mddev)
7446 if (rdev->raid_disk >= 0 &&
7447 !test_bit(Faulty, &rdev->flags) &&
7448 !test_bit(In_sync, &rdev->flags) &&
7449 rdev->recovery_offset < j)
7450 j = rdev->recovery_offset;
7451 rcu_read_unlock();
7453 /* If there is a bitmap, we need to make sure all
7454 * writes that started before we added a spare
7455 * complete before we start doing a recovery.
7456 * Otherwise the write might complete and (via
7457 * bitmap_endwrite) set a bit in the bitmap after the
7458 * recovery has checked that bit and skipped that
7459 * region.
7461 if (mddev->bitmap) {
7462 mddev->pers->quiesce(mddev, 1);
7463 mddev->pers->quiesce(mddev, 0);
7467 printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
7468 printk(KERN_INFO "md: minimum _guaranteed_ speed:"
7469 " %d KB/sec/disk.\n", speed_min(mddev));
7470 printk(KERN_INFO "md: using maximum available idle IO bandwidth "
7471 "(but not more than %d KB/sec) for %s.\n",
7472 speed_max(mddev), desc);
7474 is_mddev_idle(mddev, 1); /* this initializes IO event counters */
7476 io_sectors = 0;
7477 for (m = 0; m < SYNC_MARKS; m++) {
7478 mark[m] = jiffies;
7479 mark_cnt[m] = io_sectors;
7481 last_mark = 0;
7482 mddev->resync_mark = mark[last_mark];
7483 mddev->resync_mark_cnt = mark_cnt[last_mark];
7486 * Tune reconstruction:
7488 window = 32*(PAGE_SIZE/512);
7489 printk(KERN_INFO "md: using %dk window, over a total of %lluk.\n",
7490 window/2, (unsigned long long)max_sectors/2);
7492 atomic_set(&mddev->recovery_active, 0);
7493 last_check = 0;
7495 if (j>2) {
7496 printk(KERN_INFO
7497 "md: resuming %s of %s from checkpoint.\n",
7498 desc, mdname(mddev));
7499 mddev->curr_resync = j;
7500 } else
7501 mddev->curr_resync = 3; /* no longer delayed */
7502 mddev->curr_resync_completed = j;
7503 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7504 md_new_event(mddev);
7505 update_time = jiffies;
7507 blk_start_plug(&plug);
7508 while (j < max_sectors) {
7509 sector_t sectors;
7511 skipped = 0;
7513 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7514 ((mddev->curr_resync > mddev->curr_resync_completed &&
7515 (mddev->curr_resync - mddev->curr_resync_completed)
7516 > (max_sectors >> 4)) ||
7517 time_after_eq(jiffies, update_time + UPDATE_FREQUENCY) ||
7518 (j - mddev->curr_resync_completed)*2
7519 >= mddev->resync_max - mddev->curr_resync_completed
7520 )) {
7521 /* time to update curr_resync_completed */
7522 wait_event(mddev->recovery_wait,
7523 atomic_read(&mddev->recovery_active) == 0);
7524 mddev->curr_resync_completed = j;
7525 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) &&
7526 j > mddev->recovery_cp)
7527 mddev->recovery_cp = j;
7528 update_time = jiffies;
7529 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7530 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7533 while (j >= mddev->resync_max && !kthread_should_stop()) {
7534 /* As this condition is controlled by user-space,
7535 * we can block indefinitely, so use '_interruptible'
7536 * to avoid triggering warnings.
7538 flush_signals(current); /* just in case */
7539 wait_event_interruptible(mddev->recovery_wait,
7540 mddev->resync_max > j
7541 || kthread_should_stop());
7544 if (kthread_should_stop())
7545 goto interrupted;
7547 sectors = mddev->pers->sync_request(mddev, j, &skipped,
7548 currspeed < speed_min(mddev));
7549 if (sectors == 0) {
7550 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7551 goto out;
7554 if (!skipped) { /* actual IO requested */
7555 io_sectors += sectors;
7556 atomic_add(sectors, &mddev->recovery_active);
7559 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7560 break;
7562 j += sectors;
7563 if (j > 2)
7564 mddev->curr_resync = j;
7565 mddev->curr_mark_cnt = io_sectors;
7566 if (last_check == 0)
7567 /* this is the earliest that rebuild will be
7568 * visible in /proc/mdstat
7570 md_new_event(mddev);
7572 if (last_check + window > io_sectors || j == max_sectors)
7573 continue;
7575 last_check = io_sectors;
7576 repeat:
7577 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
7578 /* step marks */
7579 int next = (last_mark+1) % SYNC_MARKS;
7581 mddev->resync_mark = mark[next];
7582 mddev->resync_mark_cnt = mark_cnt[next];
7583 mark[next] = jiffies;
7584 mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
7585 last_mark = next;
7589 if (kthread_should_stop())
7590 goto interrupted;
7594 * this loop exits only if either when we are slower than
7595 * the 'hard' speed limit, or the system was IO-idle for
7596 * a jiffy.
7597 * the system might be non-idle CPU-wise, but we only care
7598 * about not overloading the IO subsystem. (things like an
7599 * e2fsck being done on the RAID array should execute fast)
7601 cond_resched();
7603 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
7604 /((jiffies-mddev->resync_mark)/HZ +1) +1;
7606 if (currspeed > speed_min(mddev)) {
7607 if ((currspeed > speed_max(mddev)) ||
7608 !is_mddev_idle(mddev, 0)) {
7609 msleep(500);
7610 goto repeat;
7614 printk(KERN_INFO "md: %s: %s done.\n",mdname(mddev), desc);
7616 * this also signals 'finished resyncing' to md_stop
7618 out:
7619 blk_finish_plug(&plug);
7620 wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
7622 /* tell personality that we are finished */
7623 mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
7625 if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
7626 mddev->curr_resync > 2) {
7627 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7628 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7629 if (mddev->curr_resync >= mddev->recovery_cp) {
7630 printk(KERN_INFO
7631 "md: checkpointing %s of %s.\n",
7632 desc, mdname(mddev));
7633 if (test_bit(MD_RECOVERY_ERROR,
7634 &mddev->recovery))
7635 mddev->recovery_cp =
7636 mddev->curr_resync_completed;
7637 else
7638 mddev->recovery_cp =
7639 mddev->curr_resync;
7641 } else
7642 mddev->recovery_cp = MaxSector;
7643 } else {
7644 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7645 mddev->curr_resync = MaxSector;
7646 rcu_read_lock();
7647 rdev_for_each_rcu(rdev, mddev)
7648 if (rdev->raid_disk >= 0 &&
7649 mddev->delta_disks >= 0 &&
7650 !test_bit(Faulty, &rdev->flags) &&
7651 !test_bit(In_sync, &rdev->flags) &&
7652 rdev->recovery_offset < mddev->curr_resync)
7653 rdev->recovery_offset = mddev->curr_resync;
7654 rcu_read_unlock();
7657 skip:
7658 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7660 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7661 /* We completed so min/max setting can be forgotten if used. */
7662 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7663 mddev->resync_min = 0;
7664 mddev->resync_max = MaxSector;
7665 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7666 mddev->resync_min = mddev->curr_resync_completed;
7667 mddev->curr_resync = 0;
7668 wake_up(&resync_wait);
7669 set_bit(MD_RECOVERY_DONE, &mddev->recovery);
7670 md_wakeup_thread(mddev->thread);
7671 return;
7673 interrupted:
7675 * got a signal, exit.
7677 printk(KERN_INFO
7678 "md: md_do_sync() got signal ... exiting\n");
7679 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7680 goto out;
7683 EXPORT_SYMBOL_GPL(md_do_sync);
7685 static int remove_and_add_spares(struct mddev *mddev,
7686 struct md_rdev *this)
7688 struct md_rdev *rdev;
7689 int spares = 0;
7690 int removed = 0;
7692 rdev_for_each(rdev, mddev)
7693 if ((this == NULL || rdev == this) &&
7694 rdev->raid_disk >= 0 &&
7695 !test_bit(Blocked, &rdev->flags) &&
7696 (test_bit(Faulty, &rdev->flags) ||
7697 ! test_bit(In_sync, &rdev->flags)) &&
7698 atomic_read(&rdev->nr_pending)==0) {
7699 if (mddev->pers->hot_remove_disk(
7700 mddev, rdev) == 0) {
7701 sysfs_unlink_rdev(mddev, rdev);
7702 rdev->raid_disk = -1;
7703 removed++;
7706 if (removed && mddev->kobj.sd)
7707 sysfs_notify(&mddev->kobj, NULL, "degraded");
7709 if (this)
7710 goto no_add;
7712 rdev_for_each(rdev, mddev) {
7713 if (rdev->raid_disk >= 0 &&
7714 !test_bit(In_sync, &rdev->flags) &&
7715 !test_bit(Faulty, &rdev->flags))
7716 spares++;
7717 if (rdev->raid_disk >= 0)
7718 continue;
7719 if (test_bit(Faulty, &rdev->flags))
7720 continue;
7721 if (mddev->ro &&
7722 ! (rdev->saved_raid_disk >= 0 &&
7723 !test_bit(Bitmap_sync, &rdev->flags)))
7724 continue;
7726 rdev->recovery_offset = 0;
7727 if (mddev->pers->
7728 hot_add_disk(mddev, rdev) == 0) {
7729 if (sysfs_link_rdev(mddev, rdev))
7730 /* failure here is OK */;
7731 spares++;
7732 md_new_event(mddev);
7733 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7736 no_add:
7737 if (removed)
7738 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7739 return spares;
7743 * This routine is regularly called by all per-raid-array threads to
7744 * deal with generic issues like resync and super-block update.
7745 * Raid personalities that don't have a thread (linear/raid0) do not
7746 * need this as they never do any recovery or update the superblock.
7748 * It does not do any resync itself, but rather "forks" off other threads
7749 * to do that as needed.
7750 * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
7751 * "->recovery" and create a thread at ->sync_thread.
7752 * When the thread finishes it sets MD_RECOVERY_DONE
7753 * and wakeups up this thread which will reap the thread and finish up.
7754 * This thread also removes any faulty devices (with nr_pending == 0).
7756 * The overall approach is:
7757 * 1/ if the superblock needs updating, update it.
7758 * 2/ If a recovery thread is running, don't do anything else.
7759 * 3/ If recovery has finished, clean up, possibly marking spares active.
7760 * 4/ If there are any faulty devices, remove them.
7761 * 5/ If array is degraded, try to add spares devices
7762 * 6/ If array has spares or is not in-sync, start a resync thread.
7764 void md_check_recovery(struct mddev *mddev)
7766 if (mddev->suspended)
7767 return;
7769 if (mddev->bitmap)
7770 bitmap_daemon_work(mddev);
7772 if (signal_pending(current)) {
7773 if (mddev->pers->sync_request && !mddev->external) {
7774 printk(KERN_INFO "md: %s in immediate safe mode\n",
7775 mdname(mddev));
7776 mddev->safemode = 2;
7778 flush_signals(current);
7781 if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
7782 return;
7783 if ( ! (
7784 (mddev->flags & ~ (1<<MD_CHANGE_PENDING)) ||
7785 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7786 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
7787 (mddev->external == 0 && mddev->safemode == 1) ||
7788 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
7789 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
7791 return;
7793 if (mddev_trylock(mddev)) {
7794 int spares = 0;
7796 if (mddev->ro) {
7797 /* On a read-only array we can:
7798 * - remove failed devices
7799 * - add already-in_sync devices if the array itself
7800 * is in-sync.
7801 * As we only add devices that are already in-sync,
7802 * we can activate the spares immediately.
7804 remove_and_add_spares(mddev, NULL);
7805 /* There is no thread, but we need to call
7806 * ->spare_active and clear saved_raid_disk
7808 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7809 md_reap_sync_thread(mddev);
7810 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7811 goto unlock;
7814 if (!mddev->external) {
7815 int did_change = 0;
7816 spin_lock_irq(&mddev->write_lock);
7817 if (mddev->safemode &&
7818 !atomic_read(&mddev->writes_pending) &&
7819 !mddev->in_sync &&
7820 mddev->recovery_cp == MaxSector) {
7821 mddev->in_sync = 1;
7822 did_change = 1;
7823 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7825 if (mddev->safemode == 1)
7826 mddev->safemode = 0;
7827 spin_unlock_irq(&mddev->write_lock);
7828 if (did_change)
7829 sysfs_notify_dirent_safe(mddev->sysfs_state);
7832 if (mddev->flags)
7833 md_update_sb(mddev, 0);
7835 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
7836 !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
7837 /* resync/recovery still happening */
7838 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7839 goto unlock;
7841 if (mddev->sync_thread) {
7842 md_reap_sync_thread(mddev);
7843 goto unlock;
7845 /* Set RUNNING before clearing NEEDED to avoid
7846 * any transients in the value of "sync_action".
7848 mddev->curr_resync_completed = 0;
7849 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7850 /* Clear some bits that don't mean anything, but
7851 * might be left set
7853 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
7854 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7856 if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7857 test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
7858 goto unlock;
7859 /* no recovery is running.
7860 * remove any failed drives, then
7861 * add spares if possible.
7862 * Spares are also removed and re-added, to allow
7863 * the personality to fail the re-add.
7866 if (mddev->reshape_position != MaxSector) {
7867 if (mddev->pers->check_reshape == NULL ||
7868 mddev->pers->check_reshape(mddev) != 0)
7869 /* Cannot proceed */
7870 goto unlock;
7871 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7872 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7873 } else if ((spares = remove_and_add_spares(mddev, NULL))) {
7874 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7875 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7876 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7877 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7878 } else if (mddev->recovery_cp < MaxSector) {
7879 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7880 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7881 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
7882 /* nothing to be done ... */
7883 goto unlock;
7885 if (mddev->pers->sync_request) {
7886 if (spares) {
7887 /* We are adding a device or devices to an array
7888 * which has the bitmap stored on all devices.
7889 * So make sure all bitmap pages get written
7891 bitmap_write_all(mddev->bitmap);
7893 mddev->sync_thread = md_register_thread(md_do_sync,
7894 mddev,
7895 "resync");
7896 if (!mddev->sync_thread) {
7897 printk(KERN_ERR "%s: could not start resync"
7898 " thread...\n",
7899 mdname(mddev));
7900 /* leave the spares where they are, it shouldn't hurt */
7901 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7902 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7903 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7904 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7905 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7906 } else
7907 md_wakeup_thread(mddev->sync_thread);
7908 sysfs_notify_dirent_safe(mddev->sysfs_action);
7909 md_new_event(mddev);
7911 unlock:
7912 if (!mddev->sync_thread) {
7913 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7914 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
7915 &mddev->recovery))
7916 if (mddev->sysfs_action)
7917 sysfs_notify_dirent_safe(mddev->sysfs_action);
7919 mddev_unlock(mddev);
7923 void md_reap_sync_thread(struct mddev *mddev)
7925 struct md_rdev *rdev;
7927 /* resync has finished, collect result */
7928 md_unregister_thread(&mddev->sync_thread);
7929 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
7930 !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
7931 /* success...*/
7932 /* activate any spares */
7933 if (mddev->pers->spare_active(mddev)) {
7934 sysfs_notify(&mddev->kobj, NULL,
7935 "degraded");
7936 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7939 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7940 mddev->pers->finish_reshape)
7941 mddev->pers->finish_reshape(mddev);
7943 /* If array is no-longer degraded, then any saved_raid_disk
7944 * information must be scrapped. Also if any device is now
7945 * In_sync we must scrape the saved_raid_disk for that device
7946 * do the superblock for an incrementally recovered device
7947 * written out.
7949 rdev_for_each(rdev, mddev)
7950 if (!mddev->degraded ||
7951 test_bit(In_sync, &rdev->flags))
7952 rdev->saved_raid_disk = -1;
7954 md_update_sb(mddev, 1);
7955 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7956 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7957 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7958 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7959 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7960 /* flag recovery needed just to double check */
7961 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7962 sysfs_notify_dirent_safe(mddev->sysfs_action);
7963 md_new_event(mddev);
7964 if (mddev->event_work.func)
7965 queue_work(md_misc_wq, &mddev->event_work);
7968 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
7970 sysfs_notify_dirent_safe(rdev->sysfs_state);
7971 wait_event_timeout(rdev->blocked_wait,
7972 !test_bit(Blocked, &rdev->flags) &&
7973 !test_bit(BlockedBadBlocks, &rdev->flags),
7974 msecs_to_jiffies(5000));
7975 rdev_dec_pending(rdev, mddev);
7977 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
7979 void md_finish_reshape(struct mddev *mddev)
7981 /* called be personality module when reshape completes. */
7982 struct md_rdev *rdev;
7984 rdev_for_each(rdev, mddev) {
7985 if (rdev->data_offset > rdev->new_data_offset)
7986 rdev->sectors += rdev->data_offset - rdev->new_data_offset;
7987 else
7988 rdev->sectors -= rdev->new_data_offset - rdev->data_offset;
7989 rdev->data_offset = rdev->new_data_offset;
7992 EXPORT_SYMBOL(md_finish_reshape);
7994 /* Bad block management.
7995 * We can record which blocks on each device are 'bad' and so just
7996 * fail those blocks, or that stripe, rather than the whole device.
7997 * Entries in the bad-block table are 64bits wide. This comprises:
7998 * Length of bad-range, in sectors: 0-511 for lengths 1-512
7999 * Start of bad-range, sector offset, 54 bits (allows 8 exbibytes)
8000 * A 'shift' can be set so that larger blocks are tracked and
8001 * consequently larger devices can be covered.
8002 * 'Acknowledged' flag - 1 bit. - the most significant bit.
8004 * Locking of the bad-block table uses a seqlock so md_is_badblock
8005 * might need to retry if it is very unlucky.
8006 * We will sometimes want to check for bad blocks in a bi_end_io function,
8007 * so we use the write_seqlock_irq variant.
8009 * When looking for a bad block we specify a range and want to
8010 * know if any block in the range is bad. So we binary-search
8011 * to the last range that starts at-or-before the given endpoint,
8012 * (or "before the sector after the target range")
8013 * then see if it ends after the given start.
8014 * We return
8015 * 0 if there are no known bad blocks in the range
8016 * 1 if there are known bad block which are all acknowledged
8017 * -1 if there are bad blocks which have not yet been acknowledged in metadata.
8018 * plus the start/length of the first bad section we overlap.
8020 int md_is_badblock(struct badblocks *bb, sector_t s, int sectors,
8021 sector_t *first_bad, int *bad_sectors)
8023 int hi;
8024 int lo;
8025 u64 *p = bb->page;
8026 int rv;
8027 sector_t target = s + sectors;
8028 unsigned seq;
8030 if (bb->shift > 0) {
8031 /* round the start down, and the end up */
8032 s >>= bb->shift;
8033 target += (1<<bb->shift) - 1;
8034 target >>= bb->shift;
8035 sectors = target - s;
8037 /* 'target' is now the first block after the bad range */
8039 retry:
8040 seq = read_seqbegin(&bb->lock);
8041 lo = 0;
8042 rv = 0;
8043 hi = bb->count;
8045 /* Binary search between lo and hi for 'target'
8046 * i.e. for the last range that starts before 'target'
8048 /* INVARIANT: ranges before 'lo' and at-or-after 'hi'
8049 * are known not to be the last range before target.
8050 * VARIANT: hi-lo is the number of possible
8051 * ranges, and decreases until it reaches 1
8053 while (hi - lo > 1) {
8054 int mid = (lo + hi) / 2;
8055 sector_t a = BB_OFFSET(p[mid]);
8056 if (a < target)
8057 /* This could still be the one, earlier ranges
8058 * could not. */
8059 lo = mid;
8060 else
8061 /* This and later ranges are definitely out. */
8062 hi = mid;
8064 /* 'lo' might be the last that started before target, but 'hi' isn't */
8065 if (hi > lo) {
8066 /* need to check all range that end after 's' to see if
8067 * any are unacknowledged.
8069 while (lo >= 0 &&
8070 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
8071 if (BB_OFFSET(p[lo]) < target) {
8072 /* starts before the end, and finishes after
8073 * the start, so they must overlap
8075 if (rv != -1 && BB_ACK(p[lo]))
8076 rv = 1;
8077 else
8078 rv = -1;
8079 *first_bad = BB_OFFSET(p[lo]);
8080 *bad_sectors = BB_LEN(p[lo]);
8082 lo--;
8086 if (read_seqretry(&bb->lock, seq))
8087 goto retry;
8089 return rv;
8091 EXPORT_SYMBOL_GPL(md_is_badblock);
8094 * Add a range of bad blocks to the table.
8095 * This might extend the table, or might contract it
8096 * if two adjacent ranges can be merged.
8097 * We binary-search to find the 'insertion' point, then
8098 * decide how best to handle it.
8100 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
8101 int acknowledged)
8103 u64 *p;
8104 int lo, hi;
8105 int rv = 1;
8106 unsigned long flags;
8108 if (bb->shift < 0)
8109 /* badblocks are disabled */
8110 return 0;
8112 if (bb->shift) {
8113 /* round the start down, and the end up */
8114 sector_t next = s + sectors;
8115 s >>= bb->shift;
8116 next += (1<<bb->shift) - 1;
8117 next >>= bb->shift;
8118 sectors = next - s;
8121 write_seqlock_irqsave(&bb->lock, flags);
8123 p = bb->page;
8124 lo = 0;
8125 hi = bb->count;
8126 /* Find the last range that starts at-or-before 's' */
8127 while (hi - lo > 1) {
8128 int mid = (lo + hi) / 2;
8129 sector_t a = BB_OFFSET(p[mid]);
8130 if (a <= s)
8131 lo = mid;
8132 else
8133 hi = mid;
8135 if (hi > lo && BB_OFFSET(p[lo]) > s)
8136 hi = lo;
8138 if (hi > lo) {
8139 /* we found a range that might merge with the start
8140 * of our new range
8142 sector_t a = BB_OFFSET(p[lo]);
8143 sector_t e = a + BB_LEN(p[lo]);
8144 int ack = BB_ACK(p[lo]);
8145 if (e >= s) {
8146 /* Yes, we can merge with a previous range */
8147 if (s == a && s + sectors >= e)
8148 /* new range covers old */
8149 ack = acknowledged;
8150 else
8151 ack = ack && acknowledged;
8153 if (e < s + sectors)
8154 e = s + sectors;
8155 if (e - a <= BB_MAX_LEN) {
8156 p[lo] = BB_MAKE(a, e-a, ack);
8157 s = e;
8158 } else {
8159 /* does not all fit in one range,
8160 * make p[lo] maximal
8162 if (BB_LEN(p[lo]) != BB_MAX_LEN)
8163 p[lo] = BB_MAKE(a, BB_MAX_LEN, ack);
8164 s = a + BB_MAX_LEN;
8166 sectors = e - s;
8169 if (sectors && hi < bb->count) {
8170 /* 'hi' points to the first range that starts after 's'.
8171 * Maybe we can merge with the start of that range */
8172 sector_t a = BB_OFFSET(p[hi]);
8173 sector_t e = a + BB_LEN(p[hi]);
8174 int ack = BB_ACK(p[hi]);
8175 if (a <= s + sectors) {
8176 /* merging is possible */
8177 if (e <= s + sectors) {
8178 /* full overlap */
8179 e = s + sectors;
8180 ack = acknowledged;
8181 } else
8182 ack = ack && acknowledged;
8184 a = s;
8185 if (e - a <= BB_MAX_LEN) {
8186 p[hi] = BB_MAKE(a, e-a, ack);
8187 s = e;
8188 } else {
8189 p[hi] = BB_MAKE(a, BB_MAX_LEN, ack);
8190 s = a + BB_MAX_LEN;
8192 sectors = e - s;
8193 lo = hi;
8194 hi++;
8197 if (sectors == 0 && hi < bb->count) {
8198 /* we might be able to combine lo and hi */
8199 /* Note: 's' is at the end of 'lo' */
8200 sector_t a = BB_OFFSET(p[hi]);
8201 int lolen = BB_LEN(p[lo]);
8202 int hilen = BB_LEN(p[hi]);
8203 int newlen = lolen + hilen - (s - a);
8204 if (s >= a && newlen < BB_MAX_LEN) {
8205 /* yes, we can combine them */
8206 int ack = BB_ACK(p[lo]) && BB_ACK(p[hi]);
8207 p[lo] = BB_MAKE(BB_OFFSET(p[lo]), newlen, ack);
8208 memmove(p + hi, p + hi + 1,
8209 (bb->count - hi - 1) * 8);
8210 bb->count--;
8213 while (sectors) {
8214 /* didn't merge (it all).
8215 * Need to add a range just before 'hi' */
8216 if (bb->count >= MD_MAX_BADBLOCKS) {
8217 /* No room for more */
8218 rv = 0;
8219 break;
8220 } else {
8221 int this_sectors = sectors;
8222 memmove(p + hi + 1, p + hi,
8223 (bb->count - hi) * 8);
8224 bb->count++;
8226 if (this_sectors > BB_MAX_LEN)
8227 this_sectors = BB_MAX_LEN;
8228 p[hi] = BB_MAKE(s, this_sectors, acknowledged);
8229 sectors -= this_sectors;
8230 s += this_sectors;
8234 bb->changed = 1;
8235 if (!acknowledged)
8236 bb->unacked_exist = 1;
8237 write_sequnlock_irqrestore(&bb->lock, flags);
8239 return rv;
8242 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8243 int is_new)
8245 int rv;
8246 if (is_new)
8247 s += rdev->new_data_offset;
8248 else
8249 s += rdev->data_offset;
8250 rv = md_set_badblocks(&rdev->badblocks,
8251 s, sectors, 0);
8252 if (rv) {
8253 /* Make sure they get written out promptly */
8254 sysfs_notify_dirent_safe(rdev->sysfs_state);
8255 set_bit(MD_CHANGE_CLEAN, &rdev->mddev->flags);
8256 md_wakeup_thread(rdev->mddev->thread);
8258 return rv;
8260 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
8263 * Remove a range of bad blocks from the table.
8264 * This may involve extending the table if we spilt a region,
8265 * but it must not fail. So if the table becomes full, we just
8266 * drop the remove request.
8268 static int md_clear_badblocks(struct badblocks *bb, sector_t s, int sectors)
8270 u64 *p;
8271 int lo, hi;
8272 sector_t target = s + sectors;
8273 int rv = 0;
8275 if (bb->shift > 0) {
8276 /* When clearing we round the start up and the end down.
8277 * This should not matter as the shift should align with
8278 * the block size and no rounding should ever be needed.
8279 * However it is better the think a block is bad when it
8280 * isn't than to think a block is not bad when it is.
8282 s += (1<<bb->shift) - 1;
8283 s >>= bb->shift;
8284 target >>= bb->shift;
8285 sectors = target - s;
8288 write_seqlock_irq(&bb->lock);
8290 p = bb->page;
8291 lo = 0;
8292 hi = bb->count;
8293 /* Find the last range that starts before 'target' */
8294 while (hi - lo > 1) {
8295 int mid = (lo + hi) / 2;
8296 sector_t a = BB_OFFSET(p[mid]);
8297 if (a < target)
8298 lo = mid;
8299 else
8300 hi = mid;
8302 if (hi > lo) {
8303 /* p[lo] is the last range that could overlap the
8304 * current range. Earlier ranges could also overlap,
8305 * but only this one can overlap the end of the range.
8307 if (BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > target) {
8308 /* Partial overlap, leave the tail of this range */
8309 int ack = BB_ACK(p[lo]);
8310 sector_t a = BB_OFFSET(p[lo]);
8311 sector_t end = a + BB_LEN(p[lo]);
8313 if (a < s) {
8314 /* we need to split this range */
8315 if (bb->count >= MD_MAX_BADBLOCKS) {
8316 rv = 0;
8317 goto out;
8319 memmove(p+lo+1, p+lo, (bb->count - lo) * 8);
8320 bb->count++;
8321 p[lo] = BB_MAKE(a, s-a, ack);
8322 lo++;
8324 p[lo] = BB_MAKE(target, end - target, ack);
8325 /* there is no longer an overlap */
8326 hi = lo;
8327 lo--;
8329 while (lo >= 0 &&
8330 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
8331 /* This range does overlap */
8332 if (BB_OFFSET(p[lo]) < s) {
8333 /* Keep the early parts of this range. */
8334 int ack = BB_ACK(p[lo]);
8335 sector_t start = BB_OFFSET(p[lo]);
8336 p[lo] = BB_MAKE(start, s - start, ack);
8337 /* now low doesn't overlap, so.. */
8338 break;
8340 lo--;
8342 /* 'lo' is strictly before, 'hi' is strictly after,
8343 * anything between needs to be discarded
8345 if (hi - lo > 1) {
8346 memmove(p+lo+1, p+hi, (bb->count - hi) * 8);
8347 bb->count -= (hi - lo - 1);
8351 bb->changed = 1;
8352 out:
8353 write_sequnlock_irq(&bb->lock);
8354 return rv;
8357 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
8358 int is_new)
8360 if (is_new)
8361 s += rdev->new_data_offset;
8362 else
8363 s += rdev->data_offset;
8364 return md_clear_badblocks(&rdev->badblocks,
8365 s, sectors);
8367 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
8370 * Acknowledge all bad blocks in a list.
8371 * This only succeeds if ->changed is clear. It is used by
8372 * in-kernel metadata updates
8374 void md_ack_all_badblocks(struct badblocks *bb)
8376 if (bb->page == NULL || bb->changed)
8377 /* no point even trying */
8378 return;
8379 write_seqlock_irq(&bb->lock);
8381 if (bb->changed == 0 && bb->unacked_exist) {
8382 u64 *p = bb->page;
8383 int i;
8384 for (i = 0; i < bb->count ; i++) {
8385 if (!BB_ACK(p[i])) {
8386 sector_t start = BB_OFFSET(p[i]);
8387 int len = BB_LEN(p[i]);
8388 p[i] = BB_MAKE(start, len, 1);
8391 bb->unacked_exist = 0;
8393 write_sequnlock_irq(&bb->lock);
8395 EXPORT_SYMBOL_GPL(md_ack_all_badblocks);
8397 /* sysfs access to bad-blocks list.
8398 * We present two files.
8399 * 'bad-blocks' lists sector numbers and lengths of ranges that
8400 * are recorded as bad. The list is truncated to fit within
8401 * the one-page limit of sysfs.
8402 * Writing "sector length" to this file adds an acknowledged
8403 * bad block list.
8404 * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
8405 * been acknowledged. Writing to this file adds bad blocks
8406 * without acknowledging them. This is largely for testing.
8409 static ssize_t
8410 badblocks_show(struct badblocks *bb, char *page, int unack)
8412 size_t len;
8413 int i;
8414 u64 *p = bb->page;
8415 unsigned seq;
8417 if (bb->shift < 0)
8418 return 0;
8420 retry:
8421 seq = read_seqbegin(&bb->lock);
8423 len = 0;
8424 i = 0;
8426 while (len < PAGE_SIZE && i < bb->count) {
8427 sector_t s = BB_OFFSET(p[i]);
8428 unsigned int length = BB_LEN(p[i]);
8429 int ack = BB_ACK(p[i]);
8430 i++;
8432 if (unack && ack)
8433 continue;
8435 len += snprintf(page+len, PAGE_SIZE-len, "%llu %u\n",
8436 (unsigned long long)s << bb->shift,
8437 length << bb->shift);
8439 if (unack && len == 0)
8440 bb->unacked_exist = 0;
8442 if (read_seqretry(&bb->lock, seq))
8443 goto retry;
8445 return len;
8448 #define DO_DEBUG 1
8450 static ssize_t
8451 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack)
8453 unsigned long long sector;
8454 int length;
8455 char newline;
8456 #ifdef DO_DEBUG
8457 /* Allow clearing via sysfs *only* for testing/debugging.
8458 * Normally only a successful write may clear a badblock
8460 int clear = 0;
8461 if (page[0] == '-') {
8462 clear = 1;
8463 page++;
8465 #endif /* DO_DEBUG */
8467 switch (sscanf(page, "%llu %d%c", &sector, &length, &newline)) {
8468 case 3:
8469 if (newline != '\n')
8470 return -EINVAL;
8471 case 2:
8472 if (length <= 0)
8473 return -EINVAL;
8474 break;
8475 default:
8476 return -EINVAL;
8479 #ifdef DO_DEBUG
8480 if (clear) {
8481 md_clear_badblocks(bb, sector, length);
8482 return len;
8484 #endif /* DO_DEBUG */
8485 if (md_set_badblocks(bb, sector, length, !unack))
8486 return len;
8487 else
8488 return -ENOSPC;
8491 static int md_notify_reboot(struct notifier_block *this,
8492 unsigned long code, void *x)
8494 struct list_head *tmp;
8495 struct mddev *mddev;
8496 int need_delay = 0;
8498 for_each_mddev(mddev, tmp) {
8499 if (mddev_trylock(mddev)) {
8500 if (mddev->pers)
8501 __md_stop_writes(mddev);
8502 if (mddev->persistent)
8503 mddev->safemode = 2;
8504 mddev_unlock(mddev);
8506 need_delay = 1;
8509 * certain more exotic SCSI devices are known to be
8510 * volatile wrt too early system reboots. While the
8511 * right place to handle this issue is the given
8512 * driver, we do want to have a safe RAID driver ...
8514 if (need_delay)
8515 mdelay(1000*1);
8517 return NOTIFY_DONE;
8520 static struct notifier_block md_notifier = {
8521 .notifier_call = md_notify_reboot,
8522 .next = NULL,
8523 .priority = INT_MAX, /* before any real devices */
8526 static void md_geninit(void)
8528 pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
8530 proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
8533 static int __init md_init(void)
8535 int ret = -ENOMEM;
8537 md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
8538 if (!md_wq)
8539 goto err_wq;
8541 md_misc_wq = alloc_workqueue("md_misc", 0, 0);
8542 if (!md_misc_wq)
8543 goto err_misc_wq;
8545 if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
8546 goto err_md;
8548 if ((ret = register_blkdev(0, "mdp")) < 0)
8549 goto err_mdp;
8550 mdp_major = ret;
8552 blk_register_region(MKDEV(MD_MAJOR, 0), 1UL<<MINORBITS, THIS_MODULE,
8553 md_probe, NULL, NULL);
8554 blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
8555 md_probe, NULL, NULL);
8557 register_reboot_notifier(&md_notifier);
8558 raid_table_header = register_sysctl_table(raid_root_table);
8560 md_geninit();
8561 return 0;
8563 err_mdp:
8564 unregister_blkdev(MD_MAJOR, "md");
8565 err_md:
8566 destroy_workqueue(md_misc_wq);
8567 err_misc_wq:
8568 destroy_workqueue(md_wq);
8569 err_wq:
8570 return ret;
8573 #ifndef MODULE
8576 * Searches all registered partitions for autorun RAID arrays
8577 * at boot time.
8580 static LIST_HEAD(all_detected_devices);
8581 struct detected_devices_node {
8582 struct list_head list;
8583 dev_t dev;
8586 void md_autodetect_dev(dev_t dev)
8588 struct detected_devices_node *node_detected_dev;
8590 node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
8591 if (node_detected_dev) {
8592 node_detected_dev->dev = dev;
8593 list_add_tail(&node_detected_dev->list, &all_detected_devices);
8594 } else {
8595 printk(KERN_CRIT "md: md_autodetect_dev: kzalloc failed"
8596 ", skipping dev(%d,%d)\n", MAJOR(dev), MINOR(dev));
8601 static void autostart_arrays(int part)
8603 struct md_rdev *rdev;
8604 struct detected_devices_node *node_detected_dev;
8605 dev_t dev;
8606 int i_scanned, i_passed;
8608 i_scanned = 0;
8609 i_passed = 0;
8611 printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
8613 while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
8614 i_scanned++;
8615 node_detected_dev = list_entry(all_detected_devices.next,
8616 struct detected_devices_node, list);
8617 list_del(&node_detected_dev->list);
8618 dev = node_detected_dev->dev;
8619 kfree(node_detected_dev);
8620 rdev = md_import_device(dev,0, 90);
8621 if (IS_ERR(rdev))
8622 continue;
8624 if (test_bit(Faulty, &rdev->flags)) {
8625 MD_BUG();
8626 continue;
8628 set_bit(AutoDetected, &rdev->flags);
8629 list_add(&rdev->same_set, &pending_raid_disks);
8630 i_passed++;
8633 printk(KERN_INFO "md: Scanned %d and added %d devices.\n",
8634 i_scanned, i_passed);
8636 autorun_devices(part);
8639 #endif /* !MODULE */
8641 static __exit void md_exit(void)
8643 struct mddev *mddev;
8644 struct list_head *tmp;
8646 blk_unregister_region(MKDEV(MD_MAJOR,0), 1U << MINORBITS);
8647 blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
8649 unregister_blkdev(MD_MAJOR,"md");
8650 unregister_blkdev(mdp_major, "mdp");
8651 unregister_reboot_notifier(&md_notifier);
8652 unregister_sysctl_table(raid_table_header);
8653 remove_proc_entry("mdstat", NULL);
8654 for_each_mddev(mddev, tmp) {
8655 export_array(mddev);
8656 mddev->hold_active = 0;
8658 destroy_workqueue(md_misc_wq);
8659 destroy_workqueue(md_wq);
8662 subsys_initcall(md_init);
8663 module_exit(md_exit)
8665 static int get_ro(char *buffer, struct kernel_param *kp)
8667 return sprintf(buffer, "%d", start_readonly);
8669 static int set_ro(const char *val, struct kernel_param *kp)
8671 char *e;
8672 int num = simple_strtoul(val, &e, 10);
8673 if (*val && (*e == '\0' || *e == '\n')) {
8674 start_readonly = num;
8675 return 0;
8677 return -EINVAL;
8680 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
8681 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
8683 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
8685 EXPORT_SYMBOL(register_md_personality);
8686 EXPORT_SYMBOL(unregister_md_personality);
8687 EXPORT_SYMBOL(md_error);
8688 EXPORT_SYMBOL(md_done_sync);
8689 EXPORT_SYMBOL(md_write_start);
8690 EXPORT_SYMBOL(md_write_end);
8691 EXPORT_SYMBOL(md_register_thread);
8692 EXPORT_SYMBOL(md_unregister_thread);
8693 EXPORT_SYMBOL(md_wakeup_thread);
8694 EXPORT_SYMBOL(md_check_recovery);
8695 EXPORT_SYMBOL(md_reap_sync_thread);
8696 MODULE_LICENSE("GPL");
8697 MODULE_DESCRIPTION("MD RAID framework");
8698 MODULE_ALIAS("md");
8699 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);