USB: usb-storage: unusual_devs update for Super TOP SATA bridge
[linux/fpc-iii.git] / drivers / md / md.c
blob0a447a1be2ca8c78da3e25c768ec3a47ec08a5a6
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 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
78 * Default number of read corrections we'll attempt on an rdev
79 * before ejecting it from the array. We divide the read error
80 * count by 2 for every hour elapsed between read errors.
82 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
84 * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
85 * is 1000 KB/sec, so the extra system load does not show up that much.
86 * Increase it if you want to have more _guaranteed_ speed. Note that
87 * the RAID driver will use the maximum available bandwidth if the IO
88 * subsystem is idle. There is also an 'absolute maximum' reconstruction
89 * speed limit - in case reconstruction slows down your system despite
90 * idle IO detection.
92 * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
93 * or /sys/block/mdX/md/sync_speed_{min,max}
96 static int sysctl_speed_limit_min = 1000;
97 static int sysctl_speed_limit_max = 200000;
98 static inline int speed_min(struct mddev *mddev)
100 return mddev->sync_speed_min ?
101 mddev->sync_speed_min : sysctl_speed_limit_min;
104 static inline int speed_max(struct mddev *mddev)
106 return mddev->sync_speed_max ?
107 mddev->sync_speed_max : sysctl_speed_limit_max;
110 static struct ctl_table_header *raid_table_header;
112 static ctl_table raid_table[] = {
114 .procname = "speed_limit_min",
115 .data = &sysctl_speed_limit_min,
116 .maxlen = sizeof(int),
117 .mode = S_IRUGO|S_IWUSR,
118 .proc_handler = proc_dointvec,
121 .procname = "speed_limit_max",
122 .data = &sysctl_speed_limit_max,
123 .maxlen = sizeof(int),
124 .mode = S_IRUGO|S_IWUSR,
125 .proc_handler = proc_dointvec,
130 static ctl_table raid_dir_table[] = {
132 .procname = "raid",
133 .maxlen = 0,
134 .mode = S_IRUGO|S_IXUGO,
135 .child = raid_table,
140 static ctl_table raid_root_table[] = {
142 .procname = "dev",
143 .maxlen = 0,
144 .mode = 0555,
145 .child = raid_dir_table,
150 static const struct block_device_operations md_fops;
152 static int start_readonly;
154 /* bio_clone_mddev
155 * like bio_clone, but with a local bio set
158 static void mddev_bio_destructor(struct bio *bio)
160 struct mddev *mddev, **mddevp;
162 mddevp = (void*)bio;
163 mddev = mddevp[-1];
165 bio_free(bio, mddev->bio_set);
168 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
169 struct mddev *mddev)
171 struct bio *b;
172 struct mddev **mddevp;
174 if (!mddev || !mddev->bio_set)
175 return bio_alloc(gfp_mask, nr_iovecs);
177 b = bio_alloc_bioset(gfp_mask, nr_iovecs,
178 mddev->bio_set);
179 if (!b)
180 return NULL;
181 mddevp = (void*)b;
182 mddevp[-1] = mddev;
183 b->bi_destructor = mddev_bio_destructor;
184 return b;
186 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
188 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
189 struct mddev *mddev)
191 struct bio *b;
192 struct mddev **mddevp;
194 if (!mddev || !mddev->bio_set)
195 return bio_clone(bio, gfp_mask);
197 b = bio_alloc_bioset(gfp_mask, bio->bi_max_vecs,
198 mddev->bio_set);
199 if (!b)
200 return NULL;
201 mddevp = (void*)b;
202 mddevp[-1] = mddev;
203 b->bi_destructor = mddev_bio_destructor;
204 __bio_clone(b, bio);
205 if (bio_integrity(bio)) {
206 int ret;
208 ret = bio_integrity_clone(b, bio, gfp_mask, mddev->bio_set);
210 if (ret < 0) {
211 bio_put(b);
212 return NULL;
216 return b;
218 EXPORT_SYMBOL_GPL(bio_clone_mddev);
220 void md_trim_bio(struct bio *bio, int offset, int size)
222 /* 'bio' is a cloned bio which we need to trim to match
223 * the given offset and size.
224 * This requires adjusting bi_sector, bi_size, and bi_io_vec
226 int i;
227 struct bio_vec *bvec;
228 int sofar = 0;
230 size <<= 9;
231 if (offset == 0 && size == bio->bi_size)
232 return;
234 bio->bi_sector += offset;
235 bio->bi_size = size;
236 offset <<= 9;
237 clear_bit(BIO_SEG_VALID, &bio->bi_flags);
239 while (bio->bi_idx < bio->bi_vcnt &&
240 bio->bi_io_vec[bio->bi_idx].bv_len <= offset) {
241 /* remove this whole bio_vec */
242 offset -= bio->bi_io_vec[bio->bi_idx].bv_len;
243 bio->bi_idx++;
245 if (bio->bi_idx < bio->bi_vcnt) {
246 bio->bi_io_vec[bio->bi_idx].bv_offset += offset;
247 bio->bi_io_vec[bio->bi_idx].bv_len -= offset;
249 /* avoid any complications with bi_idx being non-zero*/
250 if (bio->bi_idx) {
251 memmove(bio->bi_io_vec, bio->bi_io_vec+bio->bi_idx,
252 (bio->bi_vcnt - bio->bi_idx) * sizeof(struct bio_vec));
253 bio->bi_vcnt -= bio->bi_idx;
254 bio->bi_idx = 0;
256 /* Make sure vcnt and last bv are not too big */
257 bio_for_each_segment(bvec, bio, i) {
258 if (sofar + bvec->bv_len > size)
259 bvec->bv_len = size - sofar;
260 if (bvec->bv_len == 0) {
261 bio->bi_vcnt = i;
262 break;
264 sofar += bvec->bv_len;
267 EXPORT_SYMBOL_GPL(md_trim_bio);
270 * We have a system wide 'event count' that is incremented
271 * on any 'interesting' event, and readers of /proc/mdstat
272 * can use 'poll' or 'select' to find out when the event
273 * count increases.
275 * Events are:
276 * start array, stop array, error, add device, remove device,
277 * start build, activate spare
279 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
280 static atomic_t md_event_count;
281 void md_new_event(struct mddev *mddev)
283 atomic_inc(&md_event_count);
284 wake_up(&md_event_waiters);
286 EXPORT_SYMBOL_GPL(md_new_event);
288 /* Alternate version that can be called from interrupts
289 * when calling sysfs_notify isn't needed.
291 static void md_new_event_inintr(struct mddev *mddev)
293 atomic_inc(&md_event_count);
294 wake_up(&md_event_waiters);
298 * Enables to iterate over all existing md arrays
299 * all_mddevs_lock protects this list.
301 static LIST_HEAD(all_mddevs);
302 static DEFINE_SPINLOCK(all_mddevs_lock);
306 * iterates through all used mddevs in the system.
307 * We take care to grab the all_mddevs_lock whenever navigating
308 * the list, and to always hold a refcount when unlocked.
309 * Any code which breaks out of this loop while own
310 * a reference to the current mddev and must mddev_put it.
312 #define for_each_mddev(_mddev,_tmp) \
314 for (({ spin_lock(&all_mddevs_lock); \
315 _tmp = all_mddevs.next; \
316 _mddev = NULL;}); \
317 ({ if (_tmp != &all_mddevs) \
318 mddev_get(list_entry(_tmp, struct mddev, all_mddevs));\
319 spin_unlock(&all_mddevs_lock); \
320 if (_mddev) mddev_put(_mddev); \
321 _mddev = list_entry(_tmp, struct mddev, all_mddevs); \
322 _tmp != &all_mddevs;}); \
323 ({ spin_lock(&all_mddevs_lock); \
324 _tmp = _tmp->next;}) \
328 /* Rather than calling directly into the personality make_request function,
329 * IO requests come here first so that we can check if the device is
330 * being suspended pending a reconfiguration.
331 * We hold a refcount over the call to ->make_request. By the time that
332 * call has finished, the bio has been linked into some internal structure
333 * and so is visible to ->quiesce(), so we don't need the refcount any more.
335 static void md_make_request(struct request_queue *q, struct bio *bio)
337 const int rw = bio_data_dir(bio);
338 struct mddev *mddev = q->queuedata;
339 int cpu;
340 unsigned int sectors;
342 if (mddev == NULL || mddev->pers == NULL
343 || !mddev->ready) {
344 bio_io_error(bio);
345 return;
347 smp_rmb(); /* Ensure implications of 'active' are visible */
348 rcu_read_lock();
349 if (mddev->suspended) {
350 DEFINE_WAIT(__wait);
351 for (;;) {
352 prepare_to_wait(&mddev->sb_wait, &__wait,
353 TASK_UNINTERRUPTIBLE);
354 if (!mddev->suspended)
355 break;
356 rcu_read_unlock();
357 schedule();
358 rcu_read_lock();
360 finish_wait(&mddev->sb_wait, &__wait);
362 atomic_inc(&mddev->active_io);
363 rcu_read_unlock();
366 * save the sectors now since our bio can
367 * go away inside make_request
369 sectors = bio_sectors(bio);
370 mddev->pers->make_request(mddev, bio);
372 cpu = part_stat_lock();
373 part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
374 part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
375 part_stat_unlock();
377 if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
378 wake_up(&mddev->sb_wait);
381 /* mddev_suspend makes sure no new requests are submitted
382 * to the device, and that any requests that have been submitted
383 * are completely handled.
384 * Once ->stop is called and completes, the module will be completely
385 * unused.
387 void mddev_suspend(struct mddev *mddev)
389 BUG_ON(mddev->suspended);
390 mddev->suspended = 1;
391 synchronize_rcu();
392 wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
393 mddev->pers->quiesce(mddev, 1);
395 del_timer_sync(&mddev->safemode_timer);
397 EXPORT_SYMBOL_GPL(mddev_suspend);
399 void mddev_resume(struct mddev *mddev)
401 mddev->suspended = 0;
402 wake_up(&mddev->sb_wait);
403 mddev->pers->quiesce(mddev, 0);
405 md_wakeup_thread(mddev->thread);
406 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
408 EXPORT_SYMBOL_GPL(mddev_resume);
410 int mddev_congested(struct mddev *mddev, int bits)
412 return mddev->suspended;
414 EXPORT_SYMBOL(mddev_congested);
417 * Generic flush handling for md
420 static void md_end_flush(struct bio *bio, int err)
422 struct md_rdev *rdev = bio->bi_private;
423 struct mddev *mddev = rdev->mddev;
425 rdev_dec_pending(rdev, mddev);
427 if (atomic_dec_and_test(&mddev->flush_pending)) {
428 /* The pre-request flush has finished */
429 queue_work(md_wq, &mddev->flush_work);
431 bio_put(bio);
434 static void md_submit_flush_data(struct work_struct *ws);
436 static void submit_flushes(struct work_struct *ws)
438 struct mddev *mddev = container_of(ws, struct mddev, flush_work);
439 struct md_rdev *rdev;
441 INIT_WORK(&mddev->flush_work, md_submit_flush_data);
442 atomic_set(&mddev->flush_pending, 1);
443 rcu_read_lock();
444 rdev_for_each_rcu(rdev, mddev)
445 if (rdev->raid_disk >= 0 &&
446 !test_bit(Faulty, &rdev->flags)) {
447 /* Take two references, one is dropped
448 * when request finishes, one after
449 * we reclaim rcu_read_lock
451 struct bio *bi;
452 atomic_inc(&rdev->nr_pending);
453 atomic_inc(&rdev->nr_pending);
454 rcu_read_unlock();
455 bi = bio_alloc_mddev(GFP_NOIO, 0, mddev);
456 bi->bi_end_io = md_end_flush;
457 bi->bi_private = rdev;
458 bi->bi_bdev = rdev->bdev;
459 atomic_inc(&mddev->flush_pending);
460 submit_bio(WRITE_FLUSH, bi);
461 rcu_read_lock();
462 rdev_dec_pending(rdev, mddev);
464 rcu_read_unlock();
465 if (atomic_dec_and_test(&mddev->flush_pending))
466 queue_work(md_wq, &mddev->flush_work);
469 static void md_submit_flush_data(struct work_struct *ws)
471 struct mddev *mddev = container_of(ws, struct mddev, flush_work);
472 struct bio *bio = mddev->flush_bio;
474 if (bio->bi_size == 0)
475 /* an empty barrier - all done */
476 bio_endio(bio, 0);
477 else {
478 bio->bi_rw &= ~REQ_FLUSH;
479 mddev->pers->make_request(mddev, bio);
482 mddev->flush_bio = NULL;
483 wake_up(&mddev->sb_wait);
486 void md_flush_request(struct mddev *mddev, struct bio *bio)
488 spin_lock_irq(&mddev->write_lock);
489 wait_event_lock_irq(mddev->sb_wait,
490 !mddev->flush_bio,
491 mddev->write_lock, /*nothing*/);
492 mddev->flush_bio = bio;
493 spin_unlock_irq(&mddev->write_lock);
495 INIT_WORK(&mddev->flush_work, submit_flushes);
496 queue_work(md_wq, &mddev->flush_work);
498 EXPORT_SYMBOL(md_flush_request);
500 /* Support for plugging.
501 * This mirrors the plugging support in request_queue, but does not
502 * require having a whole queue or request structures.
503 * We allocate an md_plug_cb for each md device and each thread it gets
504 * plugged on. This links tot the private plug_handle structure in the
505 * personality data where we keep a count of the number of outstanding
506 * plugs so other code can see if a plug is active.
508 struct md_plug_cb {
509 struct blk_plug_cb cb;
510 struct mddev *mddev;
513 static void plugger_unplug(struct blk_plug_cb *cb)
515 struct md_plug_cb *mdcb = container_of(cb, struct md_plug_cb, cb);
516 if (atomic_dec_and_test(&mdcb->mddev->plug_cnt))
517 md_wakeup_thread(mdcb->mddev->thread);
518 kfree(mdcb);
521 /* Check that an unplug wakeup will come shortly.
522 * If not, wakeup the md thread immediately
524 int mddev_check_plugged(struct mddev *mddev)
526 struct blk_plug *plug = current->plug;
527 struct md_plug_cb *mdcb;
529 if (!plug)
530 return 0;
532 list_for_each_entry(mdcb, &plug->cb_list, cb.list) {
533 if (mdcb->cb.callback == plugger_unplug &&
534 mdcb->mddev == mddev) {
535 /* Already on the list, move to top */
536 if (mdcb != list_first_entry(&plug->cb_list,
537 struct md_plug_cb,
538 cb.list))
539 list_move(&mdcb->cb.list, &plug->cb_list);
540 return 1;
543 /* Not currently on the callback list */
544 mdcb = kmalloc(sizeof(*mdcb), GFP_ATOMIC);
545 if (!mdcb)
546 return 0;
548 mdcb->mddev = mddev;
549 mdcb->cb.callback = plugger_unplug;
550 atomic_inc(&mddev->plug_cnt);
551 list_add(&mdcb->cb.list, &plug->cb_list);
552 return 1;
554 EXPORT_SYMBOL_GPL(mddev_check_plugged);
556 static inline struct mddev *mddev_get(struct mddev *mddev)
558 atomic_inc(&mddev->active);
559 return mddev;
562 static void mddev_delayed_delete(struct work_struct *ws);
564 static void mddev_put(struct mddev *mddev)
566 struct bio_set *bs = NULL;
568 if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
569 return;
570 if (!mddev->raid_disks && list_empty(&mddev->disks) &&
571 mddev->ctime == 0 && !mddev->hold_active) {
572 /* Array is not configured at all, and not held active,
573 * so destroy it */
574 list_del_init(&mddev->all_mddevs);
575 bs = mddev->bio_set;
576 mddev->bio_set = NULL;
577 if (mddev->gendisk) {
578 /* We did a probe so need to clean up. Call
579 * queue_work inside the spinlock so that
580 * flush_workqueue() after mddev_find will
581 * succeed in waiting for the work to be done.
583 INIT_WORK(&mddev->del_work, mddev_delayed_delete);
584 queue_work(md_misc_wq, &mddev->del_work);
585 } else
586 kfree(mddev);
588 spin_unlock(&all_mddevs_lock);
589 if (bs)
590 bioset_free(bs);
593 void mddev_init(struct mddev *mddev)
595 mutex_init(&mddev->open_mutex);
596 mutex_init(&mddev->reconfig_mutex);
597 mutex_init(&mddev->bitmap_info.mutex);
598 INIT_LIST_HEAD(&mddev->disks);
599 INIT_LIST_HEAD(&mddev->all_mddevs);
600 init_timer(&mddev->safemode_timer);
601 atomic_set(&mddev->active, 1);
602 atomic_set(&mddev->openers, 0);
603 atomic_set(&mddev->active_io, 0);
604 atomic_set(&mddev->plug_cnt, 0);
605 spin_lock_init(&mddev->write_lock);
606 atomic_set(&mddev->flush_pending, 0);
607 init_waitqueue_head(&mddev->sb_wait);
608 init_waitqueue_head(&mddev->recovery_wait);
609 mddev->reshape_position = MaxSector;
610 mddev->resync_min = 0;
611 mddev->resync_max = MaxSector;
612 mddev->level = LEVEL_NONE;
614 EXPORT_SYMBOL_GPL(mddev_init);
616 static struct mddev * mddev_find(dev_t unit)
618 struct mddev *mddev, *new = NULL;
620 if (unit && MAJOR(unit) != MD_MAJOR)
621 unit &= ~((1<<MdpMinorShift)-1);
623 retry:
624 spin_lock(&all_mddevs_lock);
626 if (unit) {
627 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
628 if (mddev->unit == unit) {
629 mddev_get(mddev);
630 spin_unlock(&all_mddevs_lock);
631 kfree(new);
632 return mddev;
635 if (new) {
636 list_add(&new->all_mddevs, &all_mddevs);
637 spin_unlock(&all_mddevs_lock);
638 new->hold_active = UNTIL_IOCTL;
639 return new;
641 } else if (new) {
642 /* find an unused unit number */
643 static int next_minor = 512;
644 int start = next_minor;
645 int is_free = 0;
646 int dev = 0;
647 while (!is_free) {
648 dev = MKDEV(MD_MAJOR, next_minor);
649 next_minor++;
650 if (next_minor > MINORMASK)
651 next_minor = 0;
652 if (next_minor == start) {
653 /* Oh dear, all in use. */
654 spin_unlock(&all_mddevs_lock);
655 kfree(new);
656 return NULL;
659 is_free = 1;
660 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
661 if (mddev->unit == dev) {
662 is_free = 0;
663 break;
666 new->unit = dev;
667 new->md_minor = MINOR(dev);
668 new->hold_active = UNTIL_STOP;
669 list_add(&new->all_mddevs, &all_mddevs);
670 spin_unlock(&all_mddevs_lock);
671 return new;
673 spin_unlock(&all_mddevs_lock);
675 new = kzalloc(sizeof(*new), GFP_KERNEL);
676 if (!new)
677 return NULL;
679 new->unit = unit;
680 if (MAJOR(unit) == MD_MAJOR)
681 new->md_minor = MINOR(unit);
682 else
683 new->md_minor = MINOR(unit) >> MdpMinorShift;
685 mddev_init(new);
687 goto retry;
690 static inline int mddev_lock(struct mddev * mddev)
692 return mutex_lock_interruptible(&mddev->reconfig_mutex);
695 static inline int mddev_is_locked(struct mddev *mddev)
697 return mutex_is_locked(&mddev->reconfig_mutex);
700 static inline int mddev_trylock(struct mddev * mddev)
702 return mutex_trylock(&mddev->reconfig_mutex);
705 static struct attribute_group md_redundancy_group;
707 static void mddev_unlock(struct mddev * mddev)
709 if (mddev->to_remove) {
710 /* These cannot be removed under reconfig_mutex as
711 * an access to the files will try to take reconfig_mutex
712 * while holding the file unremovable, which leads to
713 * a deadlock.
714 * So hold set sysfs_active while the remove in happeing,
715 * and anything else which might set ->to_remove or my
716 * otherwise change the sysfs namespace will fail with
717 * -EBUSY if sysfs_active is still set.
718 * We set sysfs_active under reconfig_mutex and elsewhere
719 * test it under the same mutex to ensure its correct value
720 * is seen.
722 struct attribute_group *to_remove = mddev->to_remove;
723 mddev->to_remove = NULL;
724 mddev->sysfs_active = 1;
725 mutex_unlock(&mddev->reconfig_mutex);
727 if (mddev->kobj.sd) {
728 if (to_remove != &md_redundancy_group)
729 sysfs_remove_group(&mddev->kobj, to_remove);
730 if (mddev->pers == NULL ||
731 mddev->pers->sync_request == NULL) {
732 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
733 if (mddev->sysfs_action)
734 sysfs_put(mddev->sysfs_action);
735 mddev->sysfs_action = NULL;
738 mddev->sysfs_active = 0;
739 } else
740 mutex_unlock(&mddev->reconfig_mutex);
742 /* As we've dropped the mutex we need a spinlock to
743 * make sure the thread doesn't disappear
745 spin_lock(&pers_lock);
746 md_wakeup_thread(mddev->thread);
747 spin_unlock(&pers_lock);
750 static struct md_rdev * find_rdev_nr(struct mddev *mddev, int nr)
752 struct md_rdev *rdev;
754 rdev_for_each(rdev, mddev)
755 if (rdev->desc_nr == nr)
756 return rdev;
758 return NULL;
761 static struct md_rdev * find_rdev(struct mddev * mddev, dev_t dev)
763 struct md_rdev *rdev;
765 rdev_for_each(rdev, mddev)
766 if (rdev->bdev->bd_dev == dev)
767 return rdev;
769 return NULL;
772 static struct md_personality *find_pers(int level, char *clevel)
774 struct md_personality *pers;
775 list_for_each_entry(pers, &pers_list, list) {
776 if (level != LEVEL_NONE && pers->level == level)
777 return pers;
778 if (strcmp(pers->name, clevel)==0)
779 return pers;
781 return NULL;
784 /* return the offset of the super block in 512byte sectors */
785 static inline sector_t calc_dev_sboffset(struct md_rdev *rdev)
787 sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
788 return MD_NEW_SIZE_SECTORS(num_sectors);
791 static int alloc_disk_sb(struct md_rdev * rdev)
793 if (rdev->sb_page)
794 MD_BUG();
796 rdev->sb_page = alloc_page(GFP_KERNEL);
797 if (!rdev->sb_page) {
798 printk(KERN_ALERT "md: out of memory.\n");
799 return -ENOMEM;
802 return 0;
805 static void free_disk_sb(struct md_rdev * rdev)
807 if (rdev->sb_page) {
808 put_page(rdev->sb_page);
809 rdev->sb_loaded = 0;
810 rdev->sb_page = NULL;
811 rdev->sb_start = 0;
812 rdev->sectors = 0;
814 if (rdev->bb_page) {
815 put_page(rdev->bb_page);
816 rdev->bb_page = NULL;
821 static void super_written(struct bio *bio, int error)
823 struct md_rdev *rdev = bio->bi_private;
824 struct mddev *mddev = rdev->mddev;
826 if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
827 printk("md: super_written gets error=%d, uptodate=%d\n",
828 error, test_bit(BIO_UPTODATE, &bio->bi_flags));
829 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
830 md_error(mddev, rdev);
833 if (atomic_dec_and_test(&mddev->pending_writes))
834 wake_up(&mddev->sb_wait);
835 bio_put(bio);
838 void md_super_write(struct mddev *mddev, struct md_rdev *rdev,
839 sector_t sector, int size, struct page *page)
841 /* write first size bytes of page to sector of rdev
842 * Increment mddev->pending_writes before returning
843 * and decrement it on completion, waking up sb_wait
844 * if zero is reached.
845 * If an error occurred, call md_error
847 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
849 bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
850 bio->bi_sector = sector;
851 bio_add_page(bio, page, size, 0);
852 bio->bi_private = rdev;
853 bio->bi_end_io = super_written;
855 atomic_inc(&mddev->pending_writes);
856 submit_bio(WRITE_FLUSH_FUA, bio);
859 void md_super_wait(struct mddev *mddev)
861 /* wait for all superblock writes that were scheduled to complete */
862 DEFINE_WAIT(wq);
863 for(;;) {
864 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
865 if (atomic_read(&mddev->pending_writes)==0)
866 break;
867 schedule();
869 finish_wait(&mddev->sb_wait, &wq);
872 static void bi_complete(struct bio *bio, int error)
874 complete((struct completion*)bio->bi_private);
877 int sync_page_io(struct md_rdev *rdev, sector_t sector, int size,
878 struct page *page, int rw, bool metadata_op)
880 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
881 struct completion event;
882 int ret;
884 rw |= REQ_SYNC;
886 bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
887 rdev->meta_bdev : rdev->bdev;
888 if (metadata_op)
889 bio->bi_sector = sector + rdev->sb_start;
890 else
891 bio->bi_sector = sector + rdev->data_offset;
892 bio_add_page(bio, page, size, 0);
893 init_completion(&event);
894 bio->bi_private = &event;
895 bio->bi_end_io = bi_complete;
896 submit_bio(rw, bio);
897 wait_for_completion(&event);
899 ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
900 bio_put(bio);
901 return ret;
903 EXPORT_SYMBOL_GPL(sync_page_io);
905 static int read_disk_sb(struct md_rdev * rdev, int size)
907 char b[BDEVNAME_SIZE];
908 if (!rdev->sb_page) {
909 MD_BUG();
910 return -EINVAL;
912 if (rdev->sb_loaded)
913 return 0;
916 if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
917 goto fail;
918 rdev->sb_loaded = 1;
919 return 0;
921 fail:
922 printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
923 bdevname(rdev->bdev,b));
924 return -EINVAL;
927 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
929 return sb1->set_uuid0 == sb2->set_uuid0 &&
930 sb1->set_uuid1 == sb2->set_uuid1 &&
931 sb1->set_uuid2 == sb2->set_uuid2 &&
932 sb1->set_uuid3 == sb2->set_uuid3;
935 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
937 int ret;
938 mdp_super_t *tmp1, *tmp2;
940 tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
941 tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
943 if (!tmp1 || !tmp2) {
944 ret = 0;
945 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
946 goto abort;
949 *tmp1 = *sb1;
950 *tmp2 = *sb2;
953 * nr_disks is not constant
955 tmp1->nr_disks = 0;
956 tmp2->nr_disks = 0;
958 ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
959 abort:
960 kfree(tmp1);
961 kfree(tmp2);
962 return ret;
966 static u32 md_csum_fold(u32 csum)
968 csum = (csum & 0xffff) + (csum >> 16);
969 return (csum & 0xffff) + (csum >> 16);
972 static unsigned int calc_sb_csum(mdp_super_t * sb)
974 u64 newcsum = 0;
975 u32 *sb32 = (u32*)sb;
976 int i;
977 unsigned int disk_csum, csum;
979 disk_csum = sb->sb_csum;
980 sb->sb_csum = 0;
982 for (i = 0; i < MD_SB_BYTES/4 ; i++)
983 newcsum += sb32[i];
984 csum = (newcsum & 0xffffffff) + (newcsum>>32);
987 #ifdef CONFIG_ALPHA
988 /* This used to use csum_partial, which was wrong for several
989 * reasons including that different results are returned on
990 * different architectures. It isn't critical that we get exactly
991 * the same return value as before (we always csum_fold before
992 * testing, and that removes any differences). However as we
993 * know that csum_partial always returned a 16bit value on
994 * alphas, do a fold to maximise conformity to previous behaviour.
996 sb->sb_csum = md_csum_fold(disk_csum);
997 #else
998 sb->sb_csum = disk_csum;
999 #endif
1000 return csum;
1005 * Handle superblock details.
1006 * We want to be able to handle multiple superblock formats
1007 * so we have a common interface to them all, and an array of
1008 * different handlers.
1009 * We rely on user-space to write the initial superblock, and support
1010 * reading and updating of superblocks.
1011 * Interface methods are:
1012 * int load_super(struct md_rdev *dev, struct md_rdev *refdev, int minor_version)
1013 * loads and validates a superblock on dev.
1014 * if refdev != NULL, compare superblocks on both devices
1015 * Return:
1016 * 0 - dev has a superblock that is compatible with refdev
1017 * 1 - dev has a superblock that is compatible and newer than refdev
1018 * so dev should be used as the refdev in future
1019 * -EINVAL superblock incompatible or invalid
1020 * -othererror e.g. -EIO
1022 * int validate_super(struct mddev *mddev, struct md_rdev *dev)
1023 * Verify that dev is acceptable into mddev.
1024 * The first time, mddev->raid_disks will be 0, and data from
1025 * dev should be merged in. Subsequent calls check that dev
1026 * is new enough. Return 0 or -EINVAL
1028 * void sync_super(struct mddev *mddev, struct md_rdev *dev)
1029 * Update the superblock for rdev with data in mddev
1030 * This does not write to disc.
1034 struct super_type {
1035 char *name;
1036 struct module *owner;
1037 int (*load_super)(struct md_rdev *rdev, struct md_rdev *refdev,
1038 int minor_version);
1039 int (*validate_super)(struct mddev *mddev, struct md_rdev *rdev);
1040 void (*sync_super)(struct mddev *mddev, struct md_rdev *rdev);
1041 unsigned long long (*rdev_size_change)(struct md_rdev *rdev,
1042 sector_t num_sectors);
1046 * Check that the given mddev has no bitmap.
1048 * This function is called from the run method of all personalities that do not
1049 * support bitmaps. It prints an error message and returns non-zero if mddev
1050 * has a bitmap. Otherwise, it returns 0.
1053 int md_check_no_bitmap(struct mddev *mddev)
1055 if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1056 return 0;
1057 printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
1058 mdname(mddev), mddev->pers->name);
1059 return 1;
1061 EXPORT_SYMBOL(md_check_no_bitmap);
1064 * load_super for 0.90.0
1066 static int super_90_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1068 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1069 mdp_super_t *sb;
1070 int ret;
1073 * Calculate the position of the superblock (512byte sectors),
1074 * it's at the end of the disk.
1076 * It also happens to be a multiple of 4Kb.
1078 rdev->sb_start = calc_dev_sboffset(rdev);
1080 ret = read_disk_sb(rdev, MD_SB_BYTES);
1081 if (ret) return ret;
1083 ret = -EINVAL;
1085 bdevname(rdev->bdev, b);
1086 sb = page_address(rdev->sb_page);
1088 if (sb->md_magic != MD_SB_MAGIC) {
1089 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
1091 goto abort;
1094 if (sb->major_version != 0 ||
1095 sb->minor_version < 90 ||
1096 sb->minor_version > 91) {
1097 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
1098 sb->major_version, sb->minor_version,
1100 goto abort;
1103 if (sb->raid_disks <= 0)
1104 goto abort;
1106 if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1107 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1109 goto abort;
1112 rdev->preferred_minor = sb->md_minor;
1113 rdev->data_offset = 0;
1114 rdev->sb_size = MD_SB_BYTES;
1115 rdev->badblocks.shift = -1;
1117 if (sb->level == LEVEL_MULTIPATH)
1118 rdev->desc_nr = -1;
1119 else
1120 rdev->desc_nr = sb->this_disk.number;
1122 if (!refdev) {
1123 ret = 1;
1124 } else {
1125 __u64 ev1, ev2;
1126 mdp_super_t *refsb = page_address(refdev->sb_page);
1127 if (!uuid_equal(refsb, sb)) {
1128 printk(KERN_WARNING "md: %s has different UUID to %s\n",
1129 b, bdevname(refdev->bdev,b2));
1130 goto abort;
1132 if (!sb_equal(refsb, sb)) {
1133 printk(KERN_WARNING "md: %s has same UUID"
1134 " but different superblock to %s\n",
1135 b, bdevname(refdev->bdev, b2));
1136 goto abort;
1138 ev1 = md_event(sb);
1139 ev2 = md_event(refsb);
1140 if (ev1 > ev2)
1141 ret = 1;
1142 else
1143 ret = 0;
1145 rdev->sectors = rdev->sb_start;
1146 /* Limit to 4TB as metadata cannot record more than that.
1147 * (not needed for Linear and RAID0 as metadata doesn't
1148 * record this size)
1150 if (rdev->sectors >= (2ULL << 32) && sb->level >= 1)
1151 rdev->sectors = (2ULL << 32) - 2;
1153 if (rdev->sectors < ((sector_t)sb->size) * 2 && sb->level >= 1)
1154 /* "this cannot possibly happen" ... */
1155 ret = -EINVAL;
1157 abort:
1158 return ret;
1162 * validate_super for 0.90.0
1164 static int super_90_validate(struct mddev *mddev, struct md_rdev *rdev)
1166 mdp_disk_t *desc;
1167 mdp_super_t *sb = page_address(rdev->sb_page);
1168 __u64 ev1 = md_event(sb);
1170 rdev->raid_disk = -1;
1171 clear_bit(Faulty, &rdev->flags);
1172 clear_bit(In_sync, &rdev->flags);
1173 clear_bit(WriteMostly, &rdev->flags);
1175 if (mddev->raid_disks == 0) {
1176 mddev->major_version = 0;
1177 mddev->minor_version = sb->minor_version;
1178 mddev->patch_version = sb->patch_version;
1179 mddev->external = 0;
1180 mddev->chunk_sectors = sb->chunk_size >> 9;
1181 mddev->ctime = sb->ctime;
1182 mddev->utime = sb->utime;
1183 mddev->level = sb->level;
1184 mddev->clevel[0] = 0;
1185 mddev->layout = sb->layout;
1186 mddev->raid_disks = sb->raid_disks;
1187 mddev->dev_sectors = ((sector_t)sb->size) * 2;
1188 mddev->events = ev1;
1189 mddev->bitmap_info.offset = 0;
1190 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1192 if (mddev->minor_version >= 91) {
1193 mddev->reshape_position = sb->reshape_position;
1194 mddev->delta_disks = sb->delta_disks;
1195 mddev->new_level = sb->new_level;
1196 mddev->new_layout = sb->new_layout;
1197 mddev->new_chunk_sectors = sb->new_chunk >> 9;
1198 } else {
1199 mddev->reshape_position = MaxSector;
1200 mddev->delta_disks = 0;
1201 mddev->new_level = mddev->level;
1202 mddev->new_layout = mddev->layout;
1203 mddev->new_chunk_sectors = mddev->chunk_sectors;
1206 if (sb->state & (1<<MD_SB_CLEAN))
1207 mddev->recovery_cp = MaxSector;
1208 else {
1209 if (sb->events_hi == sb->cp_events_hi &&
1210 sb->events_lo == sb->cp_events_lo) {
1211 mddev->recovery_cp = sb->recovery_cp;
1212 } else
1213 mddev->recovery_cp = 0;
1216 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1217 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1218 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1219 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1221 mddev->max_disks = MD_SB_DISKS;
1223 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1224 mddev->bitmap_info.file == NULL)
1225 mddev->bitmap_info.offset =
1226 mddev->bitmap_info.default_offset;
1228 } else if (mddev->pers == NULL) {
1229 /* Insist on good event counter while assembling, except
1230 * for spares (which don't need an event count) */
1231 ++ev1;
1232 if (sb->disks[rdev->desc_nr].state & (
1233 (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1234 if (ev1 < mddev->events)
1235 return -EINVAL;
1236 } else if (mddev->bitmap) {
1237 /* if adding to array with a bitmap, then we can accept an
1238 * older device ... but not too old.
1240 if (ev1 < mddev->bitmap->events_cleared)
1241 return 0;
1242 } else {
1243 if (ev1 < mddev->events)
1244 /* just a hot-add of a new device, leave raid_disk at -1 */
1245 return 0;
1248 if (mddev->level != LEVEL_MULTIPATH) {
1249 desc = sb->disks + rdev->desc_nr;
1251 if (desc->state & (1<<MD_DISK_FAULTY))
1252 set_bit(Faulty, &rdev->flags);
1253 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1254 desc->raid_disk < mddev->raid_disks */) {
1255 set_bit(In_sync, &rdev->flags);
1256 rdev->raid_disk = desc->raid_disk;
1257 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1258 /* active but not in sync implies recovery up to
1259 * reshape position. We don't know exactly where
1260 * that is, so set to zero for now */
1261 if (mddev->minor_version >= 91) {
1262 rdev->recovery_offset = 0;
1263 rdev->raid_disk = desc->raid_disk;
1266 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1267 set_bit(WriteMostly, &rdev->flags);
1268 } else /* MULTIPATH are always insync */
1269 set_bit(In_sync, &rdev->flags);
1270 return 0;
1274 * sync_super for 0.90.0
1276 static void super_90_sync(struct mddev *mddev, struct md_rdev *rdev)
1278 mdp_super_t *sb;
1279 struct md_rdev *rdev2;
1280 int next_spare = mddev->raid_disks;
1283 /* make rdev->sb match mddev data..
1285 * 1/ zero out disks
1286 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1287 * 3/ any empty disks < next_spare become removed
1289 * disks[0] gets initialised to REMOVED because
1290 * we cannot be sure from other fields if it has
1291 * been initialised or not.
1293 int i;
1294 int active=0, working=0,failed=0,spare=0,nr_disks=0;
1296 rdev->sb_size = MD_SB_BYTES;
1298 sb = page_address(rdev->sb_page);
1300 memset(sb, 0, sizeof(*sb));
1302 sb->md_magic = MD_SB_MAGIC;
1303 sb->major_version = mddev->major_version;
1304 sb->patch_version = mddev->patch_version;
1305 sb->gvalid_words = 0; /* ignored */
1306 memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1307 memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1308 memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1309 memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1311 sb->ctime = mddev->ctime;
1312 sb->level = mddev->level;
1313 sb->size = mddev->dev_sectors / 2;
1314 sb->raid_disks = mddev->raid_disks;
1315 sb->md_minor = mddev->md_minor;
1316 sb->not_persistent = 0;
1317 sb->utime = mddev->utime;
1318 sb->state = 0;
1319 sb->events_hi = (mddev->events>>32);
1320 sb->events_lo = (u32)mddev->events;
1322 if (mddev->reshape_position == MaxSector)
1323 sb->minor_version = 90;
1324 else {
1325 sb->minor_version = 91;
1326 sb->reshape_position = mddev->reshape_position;
1327 sb->new_level = mddev->new_level;
1328 sb->delta_disks = mddev->delta_disks;
1329 sb->new_layout = mddev->new_layout;
1330 sb->new_chunk = mddev->new_chunk_sectors << 9;
1332 mddev->minor_version = sb->minor_version;
1333 if (mddev->in_sync)
1335 sb->recovery_cp = mddev->recovery_cp;
1336 sb->cp_events_hi = (mddev->events>>32);
1337 sb->cp_events_lo = (u32)mddev->events;
1338 if (mddev->recovery_cp == MaxSector)
1339 sb->state = (1<< MD_SB_CLEAN);
1340 } else
1341 sb->recovery_cp = 0;
1343 sb->layout = mddev->layout;
1344 sb->chunk_size = mddev->chunk_sectors << 9;
1346 if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1347 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1349 sb->disks[0].state = (1<<MD_DISK_REMOVED);
1350 rdev_for_each(rdev2, mddev) {
1351 mdp_disk_t *d;
1352 int desc_nr;
1353 int is_active = test_bit(In_sync, &rdev2->flags);
1355 if (rdev2->raid_disk >= 0 &&
1356 sb->minor_version >= 91)
1357 /* we have nowhere to store the recovery_offset,
1358 * but if it is not below the reshape_position,
1359 * we can piggy-back on that.
1361 is_active = 1;
1362 if (rdev2->raid_disk < 0 ||
1363 test_bit(Faulty, &rdev2->flags))
1364 is_active = 0;
1365 if (is_active)
1366 desc_nr = rdev2->raid_disk;
1367 else
1368 desc_nr = next_spare++;
1369 rdev2->desc_nr = desc_nr;
1370 d = &sb->disks[rdev2->desc_nr];
1371 nr_disks++;
1372 d->number = rdev2->desc_nr;
1373 d->major = MAJOR(rdev2->bdev->bd_dev);
1374 d->minor = MINOR(rdev2->bdev->bd_dev);
1375 if (is_active)
1376 d->raid_disk = rdev2->raid_disk;
1377 else
1378 d->raid_disk = rdev2->desc_nr; /* compatibility */
1379 if (test_bit(Faulty, &rdev2->flags))
1380 d->state = (1<<MD_DISK_FAULTY);
1381 else if (is_active) {
1382 d->state = (1<<MD_DISK_ACTIVE);
1383 if (test_bit(In_sync, &rdev2->flags))
1384 d->state |= (1<<MD_DISK_SYNC);
1385 active++;
1386 working++;
1387 } else {
1388 d->state = 0;
1389 spare++;
1390 working++;
1392 if (test_bit(WriteMostly, &rdev2->flags))
1393 d->state |= (1<<MD_DISK_WRITEMOSTLY);
1395 /* now set the "removed" and "faulty" bits on any missing devices */
1396 for (i=0 ; i < mddev->raid_disks ; i++) {
1397 mdp_disk_t *d = &sb->disks[i];
1398 if (d->state == 0 && d->number == 0) {
1399 d->number = i;
1400 d->raid_disk = i;
1401 d->state = (1<<MD_DISK_REMOVED);
1402 d->state |= (1<<MD_DISK_FAULTY);
1403 failed++;
1406 sb->nr_disks = nr_disks;
1407 sb->active_disks = active;
1408 sb->working_disks = working;
1409 sb->failed_disks = failed;
1410 sb->spare_disks = spare;
1412 sb->this_disk = sb->disks[rdev->desc_nr];
1413 sb->sb_csum = calc_sb_csum(sb);
1417 * rdev_size_change for 0.90.0
1419 static unsigned long long
1420 super_90_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1422 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1423 return 0; /* component must fit device */
1424 if (rdev->mddev->bitmap_info.offset)
1425 return 0; /* can't move bitmap */
1426 rdev->sb_start = calc_dev_sboffset(rdev);
1427 if (!num_sectors || num_sectors > rdev->sb_start)
1428 num_sectors = rdev->sb_start;
1429 /* Limit to 4TB as metadata cannot record more than that.
1430 * 4TB == 2^32 KB, or 2*2^32 sectors.
1432 if (num_sectors >= (2ULL << 32) && rdev->mddev->level >= 1)
1433 num_sectors = (2ULL << 32) - 2;
1434 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1435 rdev->sb_page);
1436 md_super_wait(rdev->mddev);
1437 return num_sectors;
1442 * version 1 superblock
1445 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1447 __le32 disk_csum;
1448 u32 csum;
1449 unsigned long long newcsum;
1450 int size = 256 + le32_to_cpu(sb->max_dev)*2;
1451 __le32 *isuper = (__le32*)sb;
1452 int i;
1454 disk_csum = sb->sb_csum;
1455 sb->sb_csum = 0;
1456 newcsum = 0;
1457 for (i=0; size>=4; size -= 4 )
1458 newcsum += le32_to_cpu(*isuper++);
1460 if (size == 2)
1461 newcsum += le16_to_cpu(*(__le16*) isuper);
1463 csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1464 sb->sb_csum = disk_csum;
1465 return cpu_to_le32(csum);
1468 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
1469 int acknowledged);
1470 static int super_1_load(struct md_rdev *rdev, struct md_rdev *refdev, int minor_version)
1472 struct mdp_superblock_1 *sb;
1473 int ret;
1474 sector_t sb_start;
1475 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1476 int bmask;
1479 * Calculate the position of the superblock in 512byte sectors.
1480 * It is always aligned to a 4K boundary and
1481 * depeding on minor_version, it can be:
1482 * 0: At least 8K, but less than 12K, from end of device
1483 * 1: At start of device
1484 * 2: 4K from start of device.
1486 switch(minor_version) {
1487 case 0:
1488 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1489 sb_start -= 8*2;
1490 sb_start &= ~(sector_t)(4*2-1);
1491 break;
1492 case 1:
1493 sb_start = 0;
1494 break;
1495 case 2:
1496 sb_start = 8;
1497 break;
1498 default:
1499 return -EINVAL;
1501 rdev->sb_start = sb_start;
1503 /* superblock is rarely larger than 1K, but it can be larger,
1504 * and it is safe to read 4k, so we do that
1506 ret = read_disk_sb(rdev, 4096);
1507 if (ret) return ret;
1510 sb = page_address(rdev->sb_page);
1512 if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1513 sb->major_version != cpu_to_le32(1) ||
1514 le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1515 le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1516 (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1517 return -EINVAL;
1519 if (calc_sb_1_csum(sb) != sb->sb_csum) {
1520 printk("md: invalid superblock checksum on %s\n",
1521 bdevname(rdev->bdev,b));
1522 return -EINVAL;
1524 if (le64_to_cpu(sb->data_size) < 10) {
1525 printk("md: data_size too small on %s\n",
1526 bdevname(rdev->bdev,b));
1527 return -EINVAL;
1530 rdev->preferred_minor = 0xffff;
1531 rdev->data_offset = le64_to_cpu(sb->data_offset);
1532 atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1534 rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1535 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1536 if (rdev->sb_size & bmask)
1537 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1539 if (minor_version
1540 && rdev->data_offset < sb_start + (rdev->sb_size/512))
1541 return -EINVAL;
1543 if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1544 rdev->desc_nr = -1;
1545 else
1546 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1548 if (!rdev->bb_page) {
1549 rdev->bb_page = alloc_page(GFP_KERNEL);
1550 if (!rdev->bb_page)
1551 return -ENOMEM;
1553 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1554 rdev->badblocks.count == 0) {
1555 /* need to load the bad block list.
1556 * Currently we limit it to one page.
1558 s32 offset;
1559 sector_t bb_sector;
1560 u64 *bbp;
1561 int i;
1562 int sectors = le16_to_cpu(sb->bblog_size);
1563 if (sectors > (PAGE_SIZE / 512))
1564 return -EINVAL;
1565 offset = le32_to_cpu(sb->bblog_offset);
1566 if (offset == 0)
1567 return -EINVAL;
1568 bb_sector = (long long)offset;
1569 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1570 rdev->bb_page, READ, true))
1571 return -EIO;
1572 bbp = (u64 *)page_address(rdev->bb_page);
1573 rdev->badblocks.shift = sb->bblog_shift;
1574 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1575 u64 bb = le64_to_cpu(*bbp);
1576 int count = bb & (0x3ff);
1577 u64 sector = bb >> 10;
1578 sector <<= sb->bblog_shift;
1579 count <<= sb->bblog_shift;
1580 if (bb + 1 == 0)
1581 break;
1582 if (md_set_badblocks(&rdev->badblocks,
1583 sector, count, 1) == 0)
1584 return -EINVAL;
1586 } else if (sb->bblog_offset == 0)
1587 rdev->badblocks.shift = -1;
1589 if (!refdev) {
1590 ret = 1;
1591 } else {
1592 __u64 ev1, ev2;
1593 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1595 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1596 sb->level != refsb->level ||
1597 sb->layout != refsb->layout ||
1598 sb->chunksize != refsb->chunksize) {
1599 printk(KERN_WARNING "md: %s has strangely different"
1600 " superblock to %s\n",
1601 bdevname(rdev->bdev,b),
1602 bdevname(refdev->bdev,b2));
1603 return -EINVAL;
1605 ev1 = le64_to_cpu(sb->events);
1606 ev2 = le64_to_cpu(refsb->events);
1608 if (ev1 > ev2)
1609 ret = 1;
1610 else
1611 ret = 0;
1613 if (minor_version)
1614 rdev->sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
1615 le64_to_cpu(sb->data_offset);
1616 else
1617 rdev->sectors = rdev->sb_start;
1618 if (rdev->sectors < le64_to_cpu(sb->data_size))
1619 return -EINVAL;
1620 rdev->sectors = le64_to_cpu(sb->data_size);
1621 if (le64_to_cpu(sb->size) > rdev->sectors)
1622 return -EINVAL;
1623 return ret;
1626 static int super_1_validate(struct mddev *mddev, struct md_rdev *rdev)
1628 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1629 __u64 ev1 = le64_to_cpu(sb->events);
1631 rdev->raid_disk = -1;
1632 clear_bit(Faulty, &rdev->flags);
1633 clear_bit(In_sync, &rdev->flags);
1634 clear_bit(WriteMostly, &rdev->flags);
1636 if (mddev->raid_disks == 0) {
1637 mddev->major_version = 1;
1638 mddev->patch_version = 0;
1639 mddev->external = 0;
1640 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1641 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1642 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1643 mddev->level = le32_to_cpu(sb->level);
1644 mddev->clevel[0] = 0;
1645 mddev->layout = le32_to_cpu(sb->layout);
1646 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1647 mddev->dev_sectors = le64_to_cpu(sb->size);
1648 mddev->events = ev1;
1649 mddev->bitmap_info.offset = 0;
1650 mddev->bitmap_info.default_offset = 1024 >> 9;
1652 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1653 memcpy(mddev->uuid, sb->set_uuid, 16);
1655 mddev->max_disks = (4096-256)/2;
1657 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1658 mddev->bitmap_info.file == NULL )
1659 mddev->bitmap_info.offset =
1660 (__s32)le32_to_cpu(sb->bitmap_offset);
1662 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1663 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1664 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1665 mddev->new_level = le32_to_cpu(sb->new_level);
1666 mddev->new_layout = le32_to_cpu(sb->new_layout);
1667 mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1668 } else {
1669 mddev->reshape_position = MaxSector;
1670 mddev->delta_disks = 0;
1671 mddev->new_level = mddev->level;
1672 mddev->new_layout = mddev->layout;
1673 mddev->new_chunk_sectors = mddev->chunk_sectors;
1676 } else if (mddev->pers == NULL) {
1677 /* Insist of good event counter while assembling, except for
1678 * spares (which don't need an event count) */
1679 ++ev1;
1680 if (rdev->desc_nr >= 0 &&
1681 rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1682 le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1683 if (ev1 < mddev->events)
1684 return -EINVAL;
1685 } else if (mddev->bitmap) {
1686 /* If adding to array with a bitmap, then we can accept an
1687 * older device, but not too old.
1689 if (ev1 < mddev->bitmap->events_cleared)
1690 return 0;
1691 } else {
1692 if (ev1 < mddev->events)
1693 /* just a hot-add of a new device, leave raid_disk at -1 */
1694 return 0;
1696 if (mddev->level != LEVEL_MULTIPATH) {
1697 int role;
1698 if (rdev->desc_nr < 0 ||
1699 rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1700 role = 0xffff;
1701 rdev->desc_nr = -1;
1702 } else
1703 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1704 switch(role) {
1705 case 0xffff: /* spare */
1706 break;
1707 case 0xfffe: /* faulty */
1708 set_bit(Faulty, &rdev->flags);
1709 break;
1710 default:
1711 if ((le32_to_cpu(sb->feature_map) &
1712 MD_FEATURE_RECOVERY_OFFSET))
1713 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1714 else
1715 set_bit(In_sync, &rdev->flags);
1716 rdev->raid_disk = role;
1717 break;
1719 if (sb->devflags & WriteMostly1)
1720 set_bit(WriteMostly, &rdev->flags);
1721 if (le32_to_cpu(sb->feature_map) & MD_FEATURE_REPLACEMENT)
1722 set_bit(Replacement, &rdev->flags);
1723 } else /* MULTIPATH are always insync */
1724 set_bit(In_sync, &rdev->flags);
1726 return 0;
1729 static void super_1_sync(struct mddev *mddev, struct md_rdev *rdev)
1731 struct mdp_superblock_1 *sb;
1732 struct md_rdev *rdev2;
1733 int max_dev, i;
1734 /* make rdev->sb match mddev and rdev data. */
1736 sb = page_address(rdev->sb_page);
1738 sb->feature_map = 0;
1739 sb->pad0 = 0;
1740 sb->recovery_offset = cpu_to_le64(0);
1741 memset(sb->pad1, 0, sizeof(sb->pad1));
1742 memset(sb->pad3, 0, sizeof(sb->pad3));
1744 sb->utime = cpu_to_le64((__u64)mddev->utime);
1745 sb->events = cpu_to_le64(mddev->events);
1746 if (mddev->in_sync)
1747 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1748 else
1749 sb->resync_offset = cpu_to_le64(0);
1751 sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1753 sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1754 sb->size = cpu_to_le64(mddev->dev_sectors);
1755 sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1756 sb->level = cpu_to_le32(mddev->level);
1757 sb->layout = cpu_to_le32(mddev->layout);
1759 if (test_bit(WriteMostly, &rdev->flags))
1760 sb->devflags |= WriteMostly1;
1761 else
1762 sb->devflags &= ~WriteMostly1;
1764 if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1765 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1766 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1769 if (rdev->raid_disk >= 0 &&
1770 !test_bit(In_sync, &rdev->flags)) {
1771 sb->feature_map |=
1772 cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1773 sb->recovery_offset =
1774 cpu_to_le64(rdev->recovery_offset);
1776 if (test_bit(Replacement, &rdev->flags))
1777 sb->feature_map |=
1778 cpu_to_le32(MD_FEATURE_REPLACEMENT);
1780 if (mddev->reshape_position != MaxSector) {
1781 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1782 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1783 sb->new_layout = cpu_to_le32(mddev->new_layout);
1784 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1785 sb->new_level = cpu_to_le32(mddev->new_level);
1786 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1789 if (rdev->badblocks.count == 0)
1790 /* Nothing to do for bad blocks*/ ;
1791 else if (sb->bblog_offset == 0)
1792 /* Cannot record bad blocks on this device */
1793 md_error(mddev, rdev);
1794 else {
1795 struct badblocks *bb = &rdev->badblocks;
1796 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1797 u64 *p = bb->page;
1798 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1799 if (bb->changed) {
1800 unsigned seq;
1802 retry:
1803 seq = read_seqbegin(&bb->lock);
1805 memset(bbp, 0xff, PAGE_SIZE);
1807 for (i = 0 ; i < bb->count ; i++) {
1808 u64 internal_bb = p[i];
1809 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1810 | BB_LEN(internal_bb));
1811 bbp[i] = cpu_to_le64(store_bb);
1813 bb->changed = 0;
1814 if (read_seqretry(&bb->lock, seq))
1815 goto retry;
1817 bb->sector = (rdev->sb_start +
1818 (int)le32_to_cpu(sb->bblog_offset));
1819 bb->size = le16_to_cpu(sb->bblog_size);
1823 max_dev = 0;
1824 rdev_for_each(rdev2, mddev)
1825 if (rdev2->desc_nr+1 > max_dev)
1826 max_dev = rdev2->desc_nr+1;
1828 if (max_dev > le32_to_cpu(sb->max_dev)) {
1829 int bmask;
1830 sb->max_dev = cpu_to_le32(max_dev);
1831 rdev->sb_size = max_dev * 2 + 256;
1832 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1833 if (rdev->sb_size & bmask)
1834 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1835 } else
1836 max_dev = le32_to_cpu(sb->max_dev);
1838 for (i=0; i<max_dev;i++)
1839 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1841 rdev_for_each(rdev2, mddev) {
1842 i = rdev2->desc_nr;
1843 if (test_bit(Faulty, &rdev2->flags))
1844 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1845 else if (test_bit(In_sync, &rdev2->flags))
1846 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1847 else if (rdev2->raid_disk >= 0)
1848 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1849 else
1850 sb->dev_roles[i] = cpu_to_le16(0xffff);
1853 sb->sb_csum = calc_sb_1_csum(sb);
1856 static unsigned long long
1857 super_1_rdev_size_change(struct md_rdev *rdev, sector_t num_sectors)
1859 struct mdp_superblock_1 *sb;
1860 sector_t max_sectors;
1861 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1862 return 0; /* component must fit device */
1863 if (rdev->sb_start < rdev->data_offset) {
1864 /* minor versions 1 and 2; superblock before data */
1865 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1866 max_sectors -= rdev->data_offset;
1867 if (!num_sectors || num_sectors > max_sectors)
1868 num_sectors = max_sectors;
1869 } else if (rdev->mddev->bitmap_info.offset) {
1870 /* minor version 0 with bitmap we can't move */
1871 return 0;
1872 } else {
1873 /* minor version 0; superblock after data */
1874 sector_t sb_start;
1875 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1876 sb_start &= ~(sector_t)(4*2 - 1);
1877 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1878 if (!num_sectors || num_sectors > max_sectors)
1879 num_sectors = max_sectors;
1880 rdev->sb_start = sb_start;
1882 sb = page_address(rdev->sb_page);
1883 sb->data_size = cpu_to_le64(num_sectors);
1884 sb->super_offset = rdev->sb_start;
1885 sb->sb_csum = calc_sb_1_csum(sb);
1886 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1887 rdev->sb_page);
1888 md_super_wait(rdev->mddev);
1889 return num_sectors;
1892 static struct super_type super_types[] = {
1893 [0] = {
1894 .name = "0.90.0",
1895 .owner = THIS_MODULE,
1896 .load_super = super_90_load,
1897 .validate_super = super_90_validate,
1898 .sync_super = super_90_sync,
1899 .rdev_size_change = super_90_rdev_size_change,
1901 [1] = {
1902 .name = "md-1",
1903 .owner = THIS_MODULE,
1904 .load_super = super_1_load,
1905 .validate_super = super_1_validate,
1906 .sync_super = super_1_sync,
1907 .rdev_size_change = super_1_rdev_size_change,
1911 static void sync_super(struct mddev *mddev, struct md_rdev *rdev)
1913 if (mddev->sync_super) {
1914 mddev->sync_super(mddev, rdev);
1915 return;
1918 BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
1920 super_types[mddev->major_version].sync_super(mddev, rdev);
1923 static int match_mddev_units(struct mddev *mddev1, struct mddev *mddev2)
1925 struct md_rdev *rdev, *rdev2;
1927 rcu_read_lock();
1928 rdev_for_each_rcu(rdev, mddev1)
1929 rdev_for_each_rcu(rdev2, mddev2)
1930 if (rdev->bdev->bd_contains ==
1931 rdev2->bdev->bd_contains) {
1932 rcu_read_unlock();
1933 return 1;
1935 rcu_read_unlock();
1936 return 0;
1939 static LIST_HEAD(pending_raid_disks);
1942 * Try to register data integrity profile for an mddev
1944 * This is called when an array is started and after a disk has been kicked
1945 * from the array. It only succeeds if all working and active component devices
1946 * are integrity capable with matching profiles.
1948 int md_integrity_register(struct mddev *mddev)
1950 struct md_rdev *rdev, *reference = NULL;
1952 if (list_empty(&mddev->disks))
1953 return 0; /* nothing to do */
1954 if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
1955 return 0; /* shouldn't register, or already is */
1956 rdev_for_each(rdev, mddev) {
1957 /* skip spares and non-functional disks */
1958 if (test_bit(Faulty, &rdev->flags))
1959 continue;
1960 if (rdev->raid_disk < 0)
1961 continue;
1962 if (!reference) {
1963 /* Use the first rdev as the reference */
1964 reference = rdev;
1965 continue;
1967 /* does this rdev's profile match the reference profile? */
1968 if (blk_integrity_compare(reference->bdev->bd_disk,
1969 rdev->bdev->bd_disk) < 0)
1970 return -EINVAL;
1972 if (!reference || !bdev_get_integrity(reference->bdev))
1973 return 0;
1975 * All component devices are integrity capable and have matching
1976 * profiles, register the common profile for the md device.
1978 if (blk_integrity_register(mddev->gendisk,
1979 bdev_get_integrity(reference->bdev)) != 0) {
1980 printk(KERN_ERR "md: failed to register integrity for %s\n",
1981 mdname(mddev));
1982 return -EINVAL;
1984 printk(KERN_NOTICE "md: data integrity enabled on %s\n", mdname(mddev));
1985 if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
1986 printk(KERN_ERR "md: failed to create integrity pool for %s\n",
1987 mdname(mddev));
1988 return -EINVAL;
1990 return 0;
1992 EXPORT_SYMBOL(md_integrity_register);
1994 /* Disable data integrity if non-capable/non-matching disk is being added */
1995 void md_integrity_add_rdev(struct md_rdev *rdev, struct mddev *mddev)
1997 struct blk_integrity *bi_rdev = bdev_get_integrity(rdev->bdev);
1998 struct blk_integrity *bi_mddev = blk_get_integrity(mddev->gendisk);
2000 if (!bi_mddev) /* nothing to do */
2001 return;
2002 if (rdev->raid_disk < 0) /* skip spares */
2003 return;
2004 if (bi_rdev && blk_integrity_compare(mddev->gendisk,
2005 rdev->bdev->bd_disk) >= 0)
2006 return;
2007 printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
2008 blk_integrity_unregister(mddev->gendisk);
2010 EXPORT_SYMBOL(md_integrity_add_rdev);
2012 static int bind_rdev_to_array(struct md_rdev * rdev, struct mddev * mddev)
2014 char b[BDEVNAME_SIZE];
2015 struct kobject *ko;
2016 char *s;
2017 int err;
2019 if (rdev->mddev) {
2020 MD_BUG();
2021 return -EINVAL;
2024 /* prevent duplicates */
2025 if (find_rdev(mddev, rdev->bdev->bd_dev))
2026 return -EEXIST;
2028 /* make sure rdev->sectors exceeds mddev->dev_sectors */
2029 if (rdev->sectors && (mddev->dev_sectors == 0 ||
2030 rdev->sectors < mddev->dev_sectors)) {
2031 if (mddev->pers) {
2032 /* Cannot change size, so fail
2033 * If mddev->level <= 0, then we don't care
2034 * about aligning sizes (e.g. linear)
2036 if (mddev->level > 0)
2037 return -ENOSPC;
2038 } else
2039 mddev->dev_sectors = rdev->sectors;
2042 /* Verify rdev->desc_nr is unique.
2043 * If it is -1, assign a free number, else
2044 * check number is not in use
2046 if (rdev->desc_nr < 0) {
2047 int choice = 0;
2048 if (mddev->pers) choice = mddev->raid_disks;
2049 while (find_rdev_nr(mddev, choice))
2050 choice++;
2051 rdev->desc_nr = choice;
2052 } else {
2053 if (find_rdev_nr(mddev, rdev->desc_nr))
2054 return -EBUSY;
2056 if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2057 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
2058 mdname(mddev), mddev->max_disks);
2059 return -EBUSY;
2061 bdevname(rdev->bdev,b);
2062 while ( (s=strchr(b, '/')) != NULL)
2063 *s = '!';
2065 rdev->mddev = mddev;
2066 printk(KERN_INFO "md: bind<%s>\n", b);
2068 if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2069 goto fail;
2071 ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2072 if (sysfs_create_link(&rdev->kobj, ko, "block"))
2073 /* failure here is OK */;
2074 rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2076 list_add_rcu(&rdev->same_set, &mddev->disks);
2077 bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2079 /* May as well allow recovery to be retried once */
2080 mddev->recovery_disabled++;
2082 return 0;
2084 fail:
2085 printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
2086 b, mdname(mddev));
2087 return err;
2090 static void md_delayed_delete(struct work_struct *ws)
2092 struct md_rdev *rdev = container_of(ws, struct md_rdev, del_work);
2093 kobject_del(&rdev->kobj);
2094 kobject_put(&rdev->kobj);
2097 static void unbind_rdev_from_array(struct md_rdev * rdev)
2099 char b[BDEVNAME_SIZE];
2100 if (!rdev->mddev) {
2101 MD_BUG();
2102 return;
2104 bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2105 list_del_rcu(&rdev->same_set);
2106 printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
2107 rdev->mddev = NULL;
2108 sysfs_remove_link(&rdev->kobj, "block");
2109 sysfs_put(rdev->sysfs_state);
2110 rdev->sysfs_state = NULL;
2111 kfree(rdev->badblocks.page);
2112 rdev->badblocks.count = 0;
2113 rdev->badblocks.page = NULL;
2114 /* We need to delay this, otherwise we can deadlock when
2115 * writing to 'remove' to "dev/state". We also need
2116 * to delay it due to rcu usage.
2118 synchronize_rcu();
2119 INIT_WORK(&rdev->del_work, md_delayed_delete);
2120 kobject_get(&rdev->kobj);
2121 queue_work(md_misc_wq, &rdev->del_work);
2125 * prevent the device from being mounted, repartitioned or
2126 * otherwise reused by a RAID array (or any other kernel
2127 * subsystem), by bd_claiming the device.
2129 static int lock_rdev(struct md_rdev *rdev, dev_t dev, int shared)
2131 int err = 0;
2132 struct block_device *bdev;
2133 char b[BDEVNAME_SIZE];
2135 bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2136 shared ? (struct md_rdev *)lock_rdev : rdev);
2137 if (IS_ERR(bdev)) {
2138 printk(KERN_ERR "md: could not open %s.\n",
2139 __bdevname(dev, b));
2140 return PTR_ERR(bdev);
2142 rdev->bdev = bdev;
2143 return err;
2146 static void unlock_rdev(struct md_rdev *rdev)
2148 struct block_device *bdev = rdev->bdev;
2149 rdev->bdev = NULL;
2150 if (!bdev)
2151 MD_BUG();
2152 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2155 void md_autodetect_dev(dev_t dev);
2157 static void export_rdev(struct md_rdev * rdev)
2159 char b[BDEVNAME_SIZE];
2160 printk(KERN_INFO "md: export_rdev(%s)\n",
2161 bdevname(rdev->bdev,b));
2162 if (rdev->mddev)
2163 MD_BUG();
2164 free_disk_sb(rdev);
2165 #ifndef MODULE
2166 if (test_bit(AutoDetected, &rdev->flags))
2167 md_autodetect_dev(rdev->bdev->bd_dev);
2168 #endif
2169 unlock_rdev(rdev);
2170 kobject_put(&rdev->kobj);
2173 static void kick_rdev_from_array(struct md_rdev * rdev)
2175 unbind_rdev_from_array(rdev);
2176 export_rdev(rdev);
2179 static void export_array(struct mddev *mddev)
2181 struct md_rdev *rdev, *tmp;
2183 rdev_for_each_safe(rdev, tmp, mddev) {
2184 if (!rdev->mddev) {
2185 MD_BUG();
2186 continue;
2188 kick_rdev_from_array(rdev);
2190 if (!list_empty(&mddev->disks))
2191 MD_BUG();
2192 mddev->raid_disks = 0;
2193 mddev->major_version = 0;
2196 static void print_desc(mdp_disk_t *desc)
2198 printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
2199 desc->major,desc->minor,desc->raid_disk,desc->state);
2202 static void print_sb_90(mdp_super_t *sb)
2204 int i;
2206 printk(KERN_INFO
2207 "md: SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
2208 sb->major_version, sb->minor_version, sb->patch_version,
2209 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
2210 sb->ctime);
2211 printk(KERN_INFO "md: L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
2212 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
2213 sb->md_minor, sb->layout, sb->chunk_size);
2214 printk(KERN_INFO "md: UT:%08x ST:%d AD:%d WD:%d"
2215 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
2216 sb->utime, sb->state, sb->active_disks, sb->working_disks,
2217 sb->failed_disks, sb->spare_disks,
2218 sb->sb_csum, (unsigned long)sb->events_lo);
2220 printk(KERN_INFO);
2221 for (i = 0; i < MD_SB_DISKS; i++) {
2222 mdp_disk_t *desc;
2224 desc = sb->disks + i;
2225 if (desc->number || desc->major || desc->minor ||
2226 desc->raid_disk || (desc->state && (desc->state != 4))) {
2227 printk(" D %2d: ", i);
2228 print_desc(desc);
2231 printk(KERN_INFO "md: THIS: ");
2232 print_desc(&sb->this_disk);
2235 static void print_sb_1(struct mdp_superblock_1 *sb)
2237 __u8 *uuid;
2239 uuid = sb->set_uuid;
2240 printk(KERN_INFO
2241 "md: SB: (V:%u) (F:0x%08x) Array-ID:<%pU>\n"
2242 "md: Name: \"%s\" CT:%llu\n",
2243 le32_to_cpu(sb->major_version),
2244 le32_to_cpu(sb->feature_map),
2245 uuid,
2246 sb->set_name,
2247 (unsigned long long)le64_to_cpu(sb->ctime)
2248 & MD_SUPERBLOCK_1_TIME_SEC_MASK);
2250 uuid = sb->device_uuid;
2251 printk(KERN_INFO
2252 "md: L%u SZ%llu RD:%u LO:%u CS:%u DO:%llu DS:%llu SO:%llu"
2253 " RO:%llu\n"
2254 "md: Dev:%08x UUID: %pU\n"
2255 "md: (F:0x%08x) UT:%llu Events:%llu ResyncOffset:%llu CSUM:0x%08x\n"
2256 "md: (MaxDev:%u) \n",
2257 le32_to_cpu(sb->level),
2258 (unsigned long long)le64_to_cpu(sb->size),
2259 le32_to_cpu(sb->raid_disks),
2260 le32_to_cpu(sb->layout),
2261 le32_to_cpu(sb->chunksize),
2262 (unsigned long long)le64_to_cpu(sb->data_offset),
2263 (unsigned long long)le64_to_cpu(sb->data_size),
2264 (unsigned long long)le64_to_cpu(sb->super_offset),
2265 (unsigned long long)le64_to_cpu(sb->recovery_offset),
2266 le32_to_cpu(sb->dev_number),
2267 uuid,
2268 sb->devflags,
2269 (unsigned long long)le64_to_cpu(sb->utime) & MD_SUPERBLOCK_1_TIME_SEC_MASK,
2270 (unsigned long long)le64_to_cpu(sb->events),
2271 (unsigned long long)le64_to_cpu(sb->resync_offset),
2272 le32_to_cpu(sb->sb_csum),
2273 le32_to_cpu(sb->max_dev)
2277 static void print_rdev(struct md_rdev *rdev, int major_version)
2279 char b[BDEVNAME_SIZE];
2280 printk(KERN_INFO "md: rdev %s, Sect:%08llu F:%d S:%d DN:%u\n",
2281 bdevname(rdev->bdev, b), (unsigned long long)rdev->sectors,
2282 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
2283 rdev->desc_nr);
2284 if (rdev->sb_loaded) {
2285 printk(KERN_INFO "md: rdev superblock (MJ:%d):\n", major_version);
2286 switch (major_version) {
2287 case 0:
2288 print_sb_90(page_address(rdev->sb_page));
2289 break;
2290 case 1:
2291 print_sb_1(page_address(rdev->sb_page));
2292 break;
2294 } else
2295 printk(KERN_INFO "md: no rdev superblock!\n");
2298 static void md_print_devices(void)
2300 struct list_head *tmp;
2301 struct md_rdev *rdev;
2302 struct mddev *mddev;
2303 char b[BDEVNAME_SIZE];
2305 printk("\n");
2306 printk("md: **********************************\n");
2307 printk("md: * <COMPLETE RAID STATE PRINTOUT> *\n");
2308 printk("md: **********************************\n");
2309 for_each_mddev(mddev, tmp) {
2311 if (mddev->bitmap)
2312 bitmap_print_sb(mddev->bitmap);
2313 else
2314 printk("%s: ", mdname(mddev));
2315 rdev_for_each(rdev, mddev)
2316 printk("<%s>", bdevname(rdev->bdev,b));
2317 printk("\n");
2319 rdev_for_each(rdev, mddev)
2320 print_rdev(rdev, mddev->major_version);
2322 printk("md: **********************************\n");
2323 printk("\n");
2327 static void sync_sbs(struct mddev * mddev, int nospares)
2329 /* Update each superblock (in-memory image), but
2330 * if we are allowed to, skip spares which already
2331 * have the right event counter, or have one earlier
2332 * (which would mean they aren't being marked as dirty
2333 * with the rest of the array)
2335 struct md_rdev *rdev;
2336 rdev_for_each(rdev, mddev) {
2337 if (rdev->sb_events == mddev->events ||
2338 (nospares &&
2339 rdev->raid_disk < 0 &&
2340 rdev->sb_events+1 == mddev->events)) {
2341 /* Don't update this superblock */
2342 rdev->sb_loaded = 2;
2343 } else {
2344 sync_super(mddev, rdev);
2345 rdev->sb_loaded = 1;
2350 static void md_update_sb(struct mddev * mddev, int force_change)
2352 struct md_rdev *rdev;
2353 int sync_req;
2354 int nospares = 0;
2355 int any_badblocks_changed = 0;
2357 repeat:
2358 /* First make sure individual recovery_offsets are correct */
2359 rdev_for_each(rdev, mddev) {
2360 if (rdev->raid_disk >= 0 &&
2361 mddev->delta_disks >= 0 &&
2362 !test_bit(In_sync, &rdev->flags) &&
2363 mddev->curr_resync_completed > rdev->recovery_offset)
2364 rdev->recovery_offset = mddev->curr_resync_completed;
2367 if (!mddev->persistent) {
2368 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2369 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2370 if (!mddev->external) {
2371 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2372 rdev_for_each(rdev, mddev) {
2373 if (rdev->badblocks.changed) {
2374 rdev->badblocks.changed = 0;
2375 md_ack_all_badblocks(&rdev->badblocks);
2376 md_error(mddev, rdev);
2378 clear_bit(Blocked, &rdev->flags);
2379 clear_bit(BlockedBadBlocks, &rdev->flags);
2380 wake_up(&rdev->blocked_wait);
2383 wake_up(&mddev->sb_wait);
2384 return;
2387 spin_lock_irq(&mddev->write_lock);
2389 mddev->utime = get_seconds();
2391 if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2392 force_change = 1;
2393 if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2394 /* just a clean<-> dirty transition, possibly leave spares alone,
2395 * though if events isn't the right even/odd, we will have to do
2396 * spares after all
2398 nospares = 1;
2399 if (force_change)
2400 nospares = 0;
2401 if (mddev->degraded)
2402 /* If the array is degraded, then skipping spares is both
2403 * dangerous and fairly pointless.
2404 * Dangerous because a device that was removed from the array
2405 * might have a event_count that still looks up-to-date,
2406 * so it can be re-added without a resync.
2407 * Pointless because if there are any spares to skip,
2408 * then a recovery will happen and soon that array won't
2409 * be degraded any more and the spare can go back to sleep then.
2411 nospares = 0;
2413 sync_req = mddev->in_sync;
2415 /* If this is just a dirty<->clean transition, and the array is clean
2416 * and 'events' is odd, we can roll back to the previous clean state */
2417 if (nospares
2418 && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2419 && mddev->can_decrease_events
2420 && mddev->events != 1) {
2421 mddev->events--;
2422 mddev->can_decrease_events = 0;
2423 } else {
2424 /* otherwise we have to go forward and ... */
2425 mddev->events ++;
2426 mddev->can_decrease_events = nospares;
2429 if (!mddev->events) {
2431 * oops, this 64-bit counter should never wrap.
2432 * Either we are in around ~1 trillion A.C., assuming
2433 * 1 reboot per second, or we have a bug:
2435 MD_BUG();
2436 mddev->events --;
2439 rdev_for_each(rdev, mddev) {
2440 if (rdev->badblocks.changed)
2441 any_badblocks_changed++;
2442 if (test_bit(Faulty, &rdev->flags))
2443 set_bit(FaultRecorded, &rdev->flags);
2446 sync_sbs(mddev, nospares);
2447 spin_unlock_irq(&mddev->write_lock);
2449 pr_debug("md: updating %s RAID superblock on device (in sync %d)\n",
2450 mdname(mddev), mddev->in_sync);
2452 bitmap_update_sb(mddev->bitmap);
2453 rdev_for_each(rdev, mddev) {
2454 char b[BDEVNAME_SIZE];
2456 if (rdev->sb_loaded != 1)
2457 continue; /* no noise on spare devices */
2459 if (!test_bit(Faulty, &rdev->flags) &&
2460 rdev->saved_raid_disk == -1) {
2461 md_super_write(mddev,rdev,
2462 rdev->sb_start, rdev->sb_size,
2463 rdev->sb_page);
2464 pr_debug("md: (write) %s's sb offset: %llu\n",
2465 bdevname(rdev->bdev, b),
2466 (unsigned long long)rdev->sb_start);
2467 rdev->sb_events = mddev->events;
2468 if (rdev->badblocks.size) {
2469 md_super_write(mddev, rdev,
2470 rdev->badblocks.sector,
2471 rdev->badblocks.size << 9,
2472 rdev->bb_page);
2473 rdev->badblocks.size = 0;
2476 } else if (test_bit(Faulty, &rdev->flags))
2477 pr_debug("md: %s (skipping faulty)\n",
2478 bdevname(rdev->bdev, b));
2479 else
2480 pr_debug("(skipping incremental s/r ");
2482 if (mddev->level == LEVEL_MULTIPATH)
2483 /* only need to write one superblock... */
2484 break;
2486 md_super_wait(mddev);
2487 /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2489 spin_lock_irq(&mddev->write_lock);
2490 if (mddev->in_sync != sync_req ||
2491 test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2492 /* have to write it out again */
2493 spin_unlock_irq(&mddev->write_lock);
2494 goto repeat;
2496 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2497 spin_unlock_irq(&mddev->write_lock);
2498 wake_up(&mddev->sb_wait);
2499 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2500 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2502 rdev_for_each(rdev, mddev) {
2503 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2504 clear_bit(Blocked, &rdev->flags);
2506 if (any_badblocks_changed)
2507 md_ack_all_badblocks(&rdev->badblocks);
2508 clear_bit(BlockedBadBlocks, &rdev->flags);
2509 wake_up(&rdev->blocked_wait);
2513 /* words written to sysfs files may, or may not, be \n terminated.
2514 * We want to accept with case. For this we use cmd_match.
2516 static int cmd_match(const char *cmd, const char *str)
2518 /* See if cmd, written into a sysfs file, matches
2519 * str. They must either be the same, or cmd can
2520 * have a trailing newline
2522 while (*cmd && *str && *cmd == *str) {
2523 cmd++;
2524 str++;
2526 if (*cmd == '\n')
2527 cmd++;
2528 if (*str || *cmd)
2529 return 0;
2530 return 1;
2533 struct rdev_sysfs_entry {
2534 struct attribute attr;
2535 ssize_t (*show)(struct md_rdev *, char *);
2536 ssize_t (*store)(struct md_rdev *, const char *, size_t);
2539 static ssize_t
2540 state_show(struct md_rdev *rdev, char *page)
2542 char *sep = "";
2543 size_t len = 0;
2545 if (test_bit(Faulty, &rdev->flags) ||
2546 rdev->badblocks.unacked_exist) {
2547 len+= sprintf(page+len, "%sfaulty",sep);
2548 sep = ",";
2550 if (test_bit(In_sync, &rdev->flags)) {
2551 len += sprintf(page+len, "%sin_sync",sep);
2552 sep = ",";
2554 if (test_bit(WriteMostly, &rdev->flags)) {
2555 len += sprintf(page+len, "%swrite_mostly",sep);
2556 sep = ",";
2558 if (test_bit(Blocked, &rdev->flags) ||
2559 (rdev->badblocks.unacked_exist
2560 && !test_bit(Faulty, &rdev->flags))) {
2561 len += sprintf(page+len, "%sblocked", sep);
2562 sep = ",";
2564 if (!test_bit(Faulty, &rdev->flags) &&
2565 !test_bit(In_sync, &rdev->flags)) {
2566 len += sprintf(page+len, "%sspare", sep);
2567 sep = ",";
2569 if (test_bit(WriteErrorSeen, &rdev->flags)) {
2570 len += sprintf(page+len, "%swrite_error", sep);
2571 sep = ",";
2573 if (test_bit(WantReplacement, &rdev->flags)) {
2574 len += sprintf(page+len, "%swant_replacement", sep);
2575 sep = ",";
2577 if (test_bit(Replacement, &rdev->flags)) {
2578 len += sprintf(page+len, "%sreplacement", sep);
2579 sep = ",";
2582 return len+sprintf(page+len, "\n");
2585 static ssize_t
2586 state_store(struct md_rdev *rdev, const char *buf, size_t len)
2588 /* can write
2589 * faulty - simulates an error
2590 * remove - disconnects the device
2591 * writemostly - sets write_mostly
2592 * -writemostly - clears write_mostly
2593 * blocked - sets the Blocked flags
2594 * -blocked - clears the Blocked and possibly simulates an error
2595 * insync - sets Insync providing device isn't active
2596 * write_error - sets WriteErrorSeen
2597 * -write_error - clears WriteErrorSeen
2599 int err = -EINVAL;
2600 if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2601 md_error(rdev->mddev, rdev);
2602 if (test_bit(Faulty, &rdev->flags))
2603 err = 0;
2604 else
2605 err = -EBUSY;
2606 } else if (cmd_match(buf, "remove")) {
2607 if (rdev->raid_disk >= 0)
2608 err = -EBUSY;
2609 else {
2610 struct mddev *mddev = rdev->mddev;
2611 kick_rdev_from_array(rdev);
2612 if (mddev->pers)
2613 md_update_sb(mddev, 1);
2614 md_new_event(mddev);
2615 err = 0;
2617 } else if (cmd_match(buf, "writemostly")) {
2618 set_bit(WriteMostly, &rdev->flags);
2619 err = 0;
2620 } else if (cmd_match(buf, "-writemostly")) {
2621 clear_bit(WriteMostly, &rdev->flags);
2622 err = 0;
2623 } else if (cmd_match(buf, "blocked")) {
2624 set_bit(Blocked, &rdev->flags);
2625 err = 0;
2626 } else if (cmd_match(buf, "-blocked")) {
2627 if (!test_bit(Faulty, &rdev->flags) &&
2628 rdev->badblocks.unacked_exist) {
2629 /* metadata handler doesn't understand badblocks,
2630 * so we need to fail the device
2632 md_error(rdev->mddev, rdev);
2634 clear_bit(Blocked, &rdev->flags);
2635 clear_bit(BlockedBadBlocks, &rdev->flags);
2636 wake_up(&rdev->blocked_wait);
2637 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2638 md_wakeup_thread(rdev->mddev->thread);
2640 err = 0;
2641 } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2642 set_bit(In_sync, &rdev->flags);
2643 err = 0;
2644 } else if (cmd_match(buf, "write_error")) {
2645 set_bit(WriteErrorSeen, &rdev->flags);
2646 err = 0;
2647 } else if (cmd_match(buf, "-write_error")) {
2648 clear_bit(WriteErrorSeen, &rdev->flags);
2649 err = 0;
2650 } else if (cmd_match(buf, "want_replacement")) {
2651 /* Any non-spare device that is not a replacement can
2652 * become want_replacement at any time, but we then need to
2653 * check if recovery is needed.
2655 if (rdev->raid_disk >= 0 &&
2656 !test_bit(Replacement, &rdev->flags))
2657 set_bit(WantReplacement, &rdev->flags);
2658 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2659 md_wakeup_thread(rdev->mddev->thread);
2660 err = 0;
2661 } else if (cmd_match(buf, "-want_replacement")) {
2662 /* Clearing 'want_replacement' is always allowed.
2663 * Once replacements starts it is too late though.
2665 err = 0;
2666 clear_bit(WantReplacement, &rdev->flags);
2667 } else if (cmd_match(buf, "replacement")) {
2668 /* Can only set a device as a replacement when array has not
2669 * yet been started. Once running, replacement is automatic
2670 * from spares, or by assigning 'slot'.
2672 if (rdev->mddev->pers)
2673 err = -EBUSY;
2674 else {
2675 set_bit(Replacement, &rdev->flags);
2676 err = 0;
2678 } else if (cmd_match(buf, "-replacement")) {
2679 /* Similarly, can only clear Replacement before start */
2680 if (rdev->mddev->pers)
2681 err = -EBUSY;
2682 else {
2683 clear_bit(Replacement, &rdev->flags);
2684 err = 0;
2687 if (!err)
2688 sysfs_notify_dirent_safe(rdev->sysfs_state);
2689 return err ? err : len;
2691 static struct rdev_sysfs_entry rdev_state =
2692 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
2694 static ssize_t
2695 errors_show(struct md_rdev *rdev, char *page)
2697 return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2700 static ssize_t
2701 errors_store(struct md_rdev *rdev, const char *buf, size_t len)
2703 char *e;
2704 unsigned long n = simple_strtoul(buf, &e, 10);
2705 if (*buf && (*e == 0 || *e == '\n')) {
2706 atomic_set(&rdev->corrected_errors, n);
2707 return len;
2709 return -EINVAL;
2711 static struct rdev_sysfs_entry rdev_errors =
2712 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2714 static ssize_t
2715 slot_show(struct md_rdev *rdev, char *page)
2717 if (rdev->raid_disk < 0)
2718 return sprintf(page, "none\n");
2719 else
2720 return sprintf(page, "%d\n", rdev->raid_disk);
2723 static ssize_t
2724 slot_store(struct md_rdev *rdev, const char *buf, size_t len)
2726 char *e;
2727 int err;
2728 int slot = simple_strtoul(buf, &e, 10);
2729 if (strncmp(buf, "none", 4)==0)
2730 slot = -1;
2731 else if (e==buf || (*e && *e!= '\n'))
2732 return -EINVAL;
2733 if (rdev->mddev->pers && slot == -1) {
2734 /* Setting 'slot' on an active array requires also
2735 * updating the 'rd%d' link, and communicating
2736 * with the personality with ->hot_*_disk.
2737 * For now we only support removing
2738 * failed/spare devices. This normally happens automatically,
2739 * but not when the metadata is externally managed.
2741 if (rdev->raid_disk == -1)
2742 return -EEXIST;
2743 /* personality does all needed checks */
2744 if (rdev->mddev->pers->hot_remove_disk == NULL)
2745 return -EINVAL;
2746 err = rdev->mddev->pers->
2747 hot_remove_disk(rdev->mddev, rdev);
2748 if (err)
2749 return err;
2750 sysfs_unlink_rdev(rdev->mddev, rdev);
2751 rdev->raid_disk = -1;
2752 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2753 md_wakeup_thread(rdev->mddev->thread);
2754 } else if (rdev->mddev->pers) {
2755 /* Activating a spare .. or possibly reactivating
2756 * if we ever get bitmaps working here.
2759 if (rdev->raid_disk != -1)
2760 return -EBUSY;
2762 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2763 return -EBUSY;
2765 if (rdev->mddev->pers->hot_add_disk == NULL)
2766 return -EINVAL;
2768 if (slot >= rdev->mddev->raid_disks &&
2769 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2770 return -ENOSPC;
2772 rdev->raid_disk = slot;
2773 if (test_bit(In_sync, &rdev->flags))
2774 rdev->saved_raid_disk = slot;
2775 else
2776 rdev->saved_raid_disk = -1;
2777 clear_bit(In_sync, &rdev->flags);
2778 err = rdev->mddev->pers->
2779 hot_add_disk(rdev->mddev, rdev);
2780 if (err) {
2781 rdev->raid_disk = -1;
2782 return err;
2783 } else
2784 sysfs_notify_dirent_safe(rdev->sysfs_state);
2785 if (sysfs_link_rdev(rdev->mddev, rdev))
2786 /* failure here is OK */;
2787 /* don't wakeup anyone, leave that to userspace. */
2788 } else {
2789 if (slot >= rdev->mddev->raid_disks &&
2790 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2791 return -ENOSPC;
2792 rdev->raid_disk = slot;
2793 /* assume it is working */
2794 clear_bit(Faulty, &rdev->flags);
2795 clear_bit(WriteMostly, &rdev->flags);
2796 set_bit(In_sync, &rdev->flags);
2797 sysfs_notify_dirent_safe(rdev->sysfs_state);
2799 return len;
2803 static struct rdev_sysfs_entry rdev_slot =
2804 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2806 static ssize_t
2807 offset_show(struct md_rdev *rdev, char *page)
2809 return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2812 static ssize_t
2813 offset_store(struct md_rdev *rdev, const char *buf, size_t len)
2815 char *e;
2816 unsigned long long offset = simple_strtoull(buf, &e, 10);
2817 if (e==buf || (*e && *e != '\n'))
2818 return -EINVAL;
2819 if (rdev->mddev->pers && rdev->raid_disk >= 0)
2820 return -EBUSY;
2821 if (rdev->sectors && rdev->mddev->external)
2822 /* Must set offset before size, so overlap checks
2823 * can be sane */
2824 return -EBUSY;
2825 rdev->data_offset = offset;
2826 return len;
2829 static struct rdev_sysfs_entry rdev_offset =
2830 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2832 static ssize_t
2833 rdev_size_show(struct md_rdev *rdev, char *page)
2835 return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2838 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2840 /* check if two start/length pairs overlap */
2841 if (s1+l1 <= s2)
2842 return 0;
2843 if (s2+l2 <= s1)
2844 return 0;
2845 return 1;
2848 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2850 unsigned long long blocks;
2851 sector_t new;
2853 if (strict_strtoull(buf, 10, &blocks) < 0)
2854 return -EINVAL;
2856 if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2857 return -EINVAL; /* sector conversion overflow */
2859 new = blocks * 2;
2860 if (new != blocks * 2)
2861 return -EINVAL; /* unsigned long long to sector_t overflow */
2863 *sectors = new;
2864 return 0;
2867 static ssize_t
2868 rdev_size_store(struct md_rdev *rdev, const char *buf, size_t len)
2870 struct mddev *my_mddev = rdev->mddev;
2871 sector_t oldsectors = rdev->sectors;
2872 sector_t sectors;
2874 if (strict_blocks_to_sectors(buf, &sectors) < 0)
2875 return -EINVAL;
2876 if (my_mddev->pers && rdev->raid_disk >= 0) {
2877 if (my_mddev->persistent) {
2878 sectors = super_types[my_mddev->major_version].
2879 rdev_size_change(rdev, sectors);
2880 if (!sectors)
2881 return -EBUSY;
2882 } else if (!sectors)
2883 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
2884 rdev->data_offset;
2886 if (sectors < my_mddev->dev_sectors)
2887 return -EINVAL; /* component must fit device */
2889 rdev->sectors = sectors;
2890 if (sectors > oldsectors && my_mddev->external) {
2891 /* need to check that all other rdevs with the same ->bdev
2892 * do not overlap. We need to unlock the mddev to avoid
2893 * a deadlock. We have already changed rdev->sectors, and if
2894 * we have to change it back, we will have the lock again.
2896 struct mddev *mddev;
2897 int overlap = 0;
2898 struct list_head *tmp;
2900 mddev_unlock(my_mddev);
2901 for_each_mddev(mddev, tmp) {
2902 struct md_rdev *rdev2;
2904 mddev_lock(mddev);
2905 rdev_for_each(rdev2, mddev)
2906 if (rdev->bdev == rdev2->bdev &&
2907 rdev != rdev2 &&
2908 overlaps(rdev->data_offset, rdev->sectors,
2909 rdev2->data_offset,
2910 rdev2->sectors)) {
2911 overlap = 1;
2912 break;
2914 mddev_unlock(mddev);
2915 if (overlap) {
2916 mddev_put(mddev);
2917 break;
2920 mddev_lock(my_mddev);
2921 if (overlap) {
2922 /* Someone else could have slipped in a size
2923 * change here, but doing so is just silly.
2924 * We put oldsectors back because we *know* it is
2925 * safe, and trust userspace not to race with
2926 * itself
2928 rdev->sectors = oldsectors;
2929 return -EBUSY;
2932 return len;
2935 static struct rdev_sysfs_entry rdev_size =
2936 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2939 static ssize_t recovery_start_show(struct md_rdev *rdev, char *page)
2941 unsigned long long recovery_start = rdev->recovery_offset;
2943 if (test_bit(In_sync, &rdev->flags) ||
2944 recovery_start == MaxSector)
2945 return sprintf(page, "none\n");
2947 return sprintf(page, "%llu\n", recovery_start);
2950 static ssize_t recovery_start_store(struct md_rdev *rdev, const char *buf, size_t len)
2952 unsigned long long recovery_start;
2954 if (cmd_match(buf, "none"))
2955 recovery_start = MaxSector;
2956 else if (strict_strtoull(buf, 10, &recovery_start))
2957 return -EINVAL;
2959 if (rdev->mddev->pers &&
2960 rdev->raid_disk >= 0)
2961 return -EBUSY;
2963 rdev->recovery_offset = recovery_start;
2964 if (recovery_start == MaxSector)
2965 set_bit(In_sync, &rdev->flags);
2966 else
2967 clear_bit(In_sync, &rdev->flags);
2968 return len;
2971 static struct rdev_sysfs_entry rdev_recovery_start =
2972 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
2975 static ssize_t
2976 badblocks_show(struct badblocks *bb, char *page, int unack);
2977 static ssize_t
2978 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack);
2980 static ssize_t bb_show(struct md_rdev *rdev, char *page)
2982 return badblocks_show(&rdev->badblocks, page, 0);
2984 static ssize_t bb_store(struct md_rdev *rdev, const char *page, size_t len)
2986 int rv = badblocks_store(&rdev->badblocks, page, len, 0);
2987 /* Maybe that ack was all we needed */
2988 if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
2989 wake_up(&rdev->blocked_wait);
2990 return rv;
2992 static struct rdev_sysfs_entry rdev_bad_blocks =
2993 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
2996 static ssize_t ubb_show(struct md_rdev *rdev, char *page)
2998 return badblocks_show(&rdev->badblocks, page, 1);
3000 static ssize_t ubb_store(struct md_rdev *rdev, const char *page, size_t len)
3002 return badblocks_store(&rdev->badblocks, page, len, 1);
3004 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
3005 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
3007 static struct attribute *rdev_default_attrs[] = {
3008 &rdev_state.attr,
3009 &rdev_errors.attr,
3010 &rdev_slot.attr,
3011 &rdev_offset.attr,
3012 &rdev_size.attr,
3013 &rdev_recovery_start.attr,
3014 &rdev_bad_blocks.attr,
3015 &rdev_unack_bad_blocks.attr,
3016 NULL,
3018 static ssize_t
3019 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
3021 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3022 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3023 struct mddev *mddev = rdev->mddev;
3024 ssize_t rv;
3026 if (!entry->show)
3027 return -EIO;
3029 rv = mddev ? mddev_lock(mddev) : -EBUSY;
3030 if (!rv) {
3031 if (rdev->mddev == NULL)
3032 rv = -EBUSY;
3033 else
3034 rv = entry->show(rdev, page);
3035 mddev_unlock(mddev);
3037 return rv;
3040 static ssize_t
3041 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
3042 const char *page, size_t length)
3044 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
3045 struct md_rdev *rdev = container_of(kobj, struct md_rdev, kobj);
3046 ssize_t rv;
3047 struct mddev *mddev = rdev->mddev;
3049 if (!entry->store)
3050 return -EIO;
3051 if (!capable(CAP_SYS_ADMIN))
3052 return -EACCES;
3053 rv = mddev ? mddev_lock(mddev): -EBUSY;
3054 if (!rv) {
3055 if (rdev->mddev == NULL)
3056 rv = -EBUSY;
3057 else
3058 rv = entry->store(rdev, page, length);
3059 mddev_unlock(mddev);
3061 return rv;
3064 static void rdev_free(struct kobject *ko)
3066 struct md_rdev *rdev = container_of(ko, struct md_rdev, kobj);
3067 kfree(rdev);
3069 static const struct sysfs_ops rdev_sysfs_ops = {
3070 .show = rdev_attr_show,
3071 .store = rdev_attr_store,
3073 static struct kobj_type rdev_ktype = {
3074 .release = rdev_free,
3075 .sysfs_ops = &rdev_sysfs_ops,
3076 .default_attrs = rdev_default_attrs,
3079 int md_rdev_init(struct md_rdev *rdev)
3081 rdev->desc_nr = -1;
3082 rdev->saved_raid_disk = -1;
3083 rdev->raid_disk = -1;
3084 rdev->flags = 0;
3085 rdev->data_offset = 0;
3086 rdev->sb_events = 0;
3087 rdev->last_read_error.tv_sec = 0;
3088 rdev->last_read_error.tv_nsec = 0;
3089 rdev->sb_loaded = 0;
3090 rdev->bb_page = NULL;
3091 atomic_set(&rdev->nr_pending, 0);
3092 atomic_set(&rdev->read_errors, 0);
3093 atomic_set(&rdev->corrected_errors, 0);
3095 INIT_LIST_HEAD(&rdev->same_set);
3096 init_waitqueue_head(&rdev->blocked_wait);
3098 /* Add space to store bad block list.
3099 * This reserves the space even on arrays where it cannot
3100 * be used - I wonder if that matters
3102 rdev->badblocks.count = 0;
3103 rdev->badblocks.shift = 0;
3104 rdev->badblocks.page = kmalloc(PAGE_SIZE, GFP_KERNEL);
3105 seqlock_init(&rdev->badblocks.lock);
3106 if (rdev->badblocks.page == NULL)
3107 return -ENOMEM;
3109 return 0;
3111 EXPORT_SYMBOL_GPL(md_rdev_init);
3113 * Import a device. If 'super_format' >= 0, then sanity check the superblock
3115 * mark the device faulty if:
3117 * - the device is nonexistent (zero size)
3118 * - the device has no valid superblock
3120 * a faulty rdev _never_ has rdev->sb set.
3122 static struct md_rdev *md_import_device(dev_t newdev, int super_format, int super_minor)
3124 char b[BDEVNAME_SIZE];
3125 int err;
3126 struct md_rdev *rdev;
3127 sector_t size;
3129 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3130 if (!rdev) {
3131 printk(KERN_ERR "md: could not alloc mem for new device!\n");
3132 return ERR_PTR(-ENOMEM);
3135 err = md_rdev_init(rdev);
3136 if (err)
3137 goto abort_free;
3138 err = alloc_disk_sb(rdev);
3139 if (err)
3140 goto abort_free;
3142 err = lock_rdev(rdev, newdev, super_format == -2);
3143 if (err)
3144 goto abort_free;
3146 kobject_init(&rdev->kobj, &rdev_ktype);
3148 size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3149 if (!size) {
3150 printk(KERN_WARNING
3151 "md: %s has zero or unknown size, marking faulty!\n",
3152 bdevname(rdev->bdev,b));
3153 err = -EINVAL;
3154 goto abort_free;
3157 if (super_format >= 0) {
3158 err = super_types[super_format].
3159 load_super(rdev, NULL, super_minor);
3160 if (err == -EINVAL) {
3161 printk(KERN_WARNING
3162 "md: %s does not have a valid v%d.%d "
3163 "superblock, not importing!\n",
3164 bdevname(rdev->bdev,b),
3165 super_format, super_minor);
3166 goto abort_free;
3168 if (err < 0) {
3169 printk(KERN_WARNING
3170 "md: could not read %s's sb, not importing!\n",
3171 bdevname(rdev->bdev,b));
3172 goto abort_free;
3175 if (super_format == -1)
3176 /* hot-add for 0.90, or non-persistent: so no badblocks */
3177 rdev->badblocks.shift = -1;
3179 return rdev;
3181 abort_free:
3182 if (rdev->bdev)
3183 unlock_rdev(rdev);
3184 free_disk_sb(rdev);
3185 kfree(rdev->badblocks.page);
3186 kfree(rdev);
3187 return ERR_PTR(err);
3191 * Check a full RAID array for plausibility
3195 static void analyze_sbs(struct mddev * mddev)
3197 int i;
3198 struct md_rdev *rdev, *freshest, *tmp;
3199 char b[BDEVNAME_SIZE];
3201 freshest = NULL;
3202 rdev_for_each_safe(rdev, tmp, mddev)
3203 switch (super_types[mddev->major_version].
3204 load_super(rdev, freshest, mddev->minor_version)) {
3205 case 1:
3206 freshest = rdev;
3207 break;
3208 case 0:
3209 break;
3210 default:
3211 printk( KERN_ERR \
3212 "md: fatal superblock inconsistency in %s"
3213 " -- removing from array\n",
3214 bdevname(rdev->bdev,b));
3215 kick_rdev_from_array(rdev);
3219 super_types[mddev->major_version].
3220 validate_super(mddev, freshest);
3222 i = 0;
3223 rdev_for_each_safe(rdev, tmp, mddev) {
3224 if (mddev->max_disks &&
3225 (rdev->desc_nr >= mddev->max_disks ||
3226 i > mddev->max_disks)) {
3227 printk(KERN_WARNING
3228 "md: %s: %s: only %d devices permitted\n",
3229 mdname(mddev), bdevname(rdev->bdev, b),
3230 mddev->max_disks);
3231 kick_rdev_from_array(rdev);
3232 continue;
3234 if (rdev != freshest)
3235 if (super_types[mddev->major_version].
3236 validate_super(mddev, rdev)) {
3237 printk(KERN_WARNING "md: kicking non-fresh %s"
3238 " from array!\n",
3239 bdevname(rdev->bdev,b));
3240 kick_rdev_from_array(rdev);
3241 continue;
3243 if (mddev->level == LEVEL_MULTIPATH) {
3244 rdev->desc_nr = i++;
3245 rdev->raid_disk = rdev->desc_nr;
3246 set_bit(In_sync, &rdev->flags);
3247 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
3248 rdev->raid_disk = -1;
3249 clear_bit(In_sync, &rdev->flags);
3254 /* Read a fixed-point number.
3255 * Numbers in sysfs attributes should be in "standard" units where
3256 * possible, so time should be in seconds.
3257 * However we internally use a a much smaller unit such as
3258 * milliseconds or jiffies.
3259 * This function takes a decimal number with a possible fractional
3260 * component, and produces an integer which is the result of
3261 * multiplying that number by 10^'scale'.
3262 * all without any floating-point arithmetic.
3264 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3266 unsigned long result = 0;
3267 long decimals = -1;
3268 while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3269 if (*cp == '.')
3270 decimals = 0;
3271 else if (decimals < scale) {
3272 unsigned int value;
3273 value = *cp - '0';
3274 result = result * 10 + value;
3275 if (decimals >= 0)
3276 decimals++;
3278 cp++;
3280 if (*cp == '\n')
3281 cp++;
3282 if (*cp)
3283 return -EINVAL;
3284 if (decimals < 0)
3285 decimals = 0;
3286 while (decimals < scale) {
3287 result *= 10;
3288 decimals ++;
3290 *res = result;
3291 return 0;
3295 static void md_safemode_timeout(unsigned long data);
3297 static ssize_t
3298 safe_delay_show(struct mddev *mddev, char *page)
3300 int msec = (mddev->safemode_delay*1000)/HZ;
3301 return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3303 static ssize_t
3304 safe_delay_store(struct mddev *mddev, const char *cbuf, size_t len)
3306 unsigned long msec;
3308 if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3309 return -EINVAL;
3310 if (msec == 0)
3311 mddev->safemode_delay = 0;
3312 else {
3313 unsigned long old_delay = mddev->safemode_delay;
3314 mddev->safemode_delay = (msec*HZ)/1000;
3315 if (mddev->safemode_delay == 0)
3316 mddev->safemode_delay = 1;
3317 if (mddev->safemode_delay < old_delay)
3318 md_safemode_timeout((unsigned long)mddev);
3320 return len;
3322 static struct md_sysfs_entry md_safe_delay =
3323 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3325 static ssize_t
3326 level_show(struct mddev *mddev, char *page)
3328 struct md_personality *p = mddev->pers;
3329 if (p)
3330 return sprintf(page, "%s\n", p->name);
3331 else if (mddev->clevel[0])
3332 return sprintf(page, "%s\n", mddev->clevel);
3333 else if (mddev->level != LEVEL_NONE)
3334 return sprintf(page, "%d\n", mddev->level);
3335 else
3336 return 0;
3339 static ssize_t
3340 level_store(struct mddev *mddev, const char *buf, size_t len)
3342 char clevel[16];
3343 ssize_t rv = len;
3344 struct md_personality *pers;
3345 long level;
3346 void *priv;
3347 struct md_rdev *rdev;
3349 if (mddev->pers == NULL) {
3350 if (len == 0)
3351 return 0;
3352 if (len >= sizeof(mddev->clevel))
3353 return -ENOSPC;
3354 strncpy(mddev->clevel, buf, len);
3355 if (mddev->clevel[len-1] == '\n')
3356 len--;
3357 mddev->clevel[len] = 0;
3358 mddev->level = LEVEL_NONE;
3359 return rv;
3362 /* request to change the personality. Need to ensure:
3363 * - array is not engaged in resync/recovery/reshape
3364 * - old personality can be suspended
3365 * - new personality will access other array.
3368 if (mddev->sync_thread ||
3369 mddev->reshape_position != MaxSector ||
3370 mddev->sysfs_active)
3371 return -EBUSY;
3373 if (!mddev->pers->quiesce) {
3374 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3375 mdname(mddev), mddev->pers->name);
3376 return -EINVAL;
3379 /* Now find the new personality */
3380 if (len == 0 || len >= sizeof(clevel))
3381 return -EINVAL;
3382 strncpy(clevel, buf, len);
3383 if (clevel[len-1] == '\n')
3384 len--;
3385 clevel[len] = 0;
3386 if (strict_strtol(clevel, 10, &level))
3387 level = LEVEL_NONE;
3389 if (request_module("md-%s", clevel) != 0)
3390 request_module("md-level-%s", clevel);
3391 spin_lock(&pers_lock);
3392 pers = find_pers(level, clevel);
3393 if (!pers || !try_module_get(pers->owner)) {
3394 spin_unlock(&pers_lock);
3395 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3396 return -EINVAL;
3398 spin_unlock(&pers_lock);
3400 if (pers == mddev->pers) {
3401 /* Nothing to do! */
3402 module_put(pers->owner);
3403 return rv;
3405 if (!pers->takeover) {
3406 module_put(pers->owner);
3407 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3408 mdname(mddev), clevel);
3409 return -EINVAL;
3412 rdev_for_each(rdev, mddev)
3413 rdev->new_raid_disk = rdev->raid_disk;
3415 /* ->takeover must set new_* and/or delta_disks
3416 * if it succeeds, and may set them when it fails.
3418 priv = pers->takeover(mddev);
3419 if (IS_ERR(priv)) {
3420 mddev->new_level = mddev->level;
3421 mddev->new_layout = mddev->layout;
3422 mddev->new_chunk_sectors = mddev->chunk_sectors;
3423 mddev->raid_disks -= mddev->delta_disks;
3424 mddev->delta_disks = 0;
3425 module_put(pers->owner);
3426 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3427 mdname(mddev), clevel);
3428 return PTR_ERR(priv);
3431 /* Looks like we have a winner */
3432 mddev_suspend(mddev);
3433 mddev->pers->stop(mddev);
3435 if (mddev->pers->sync_request == NULL &&
3436 pers->sync_request != NULL) {
3437 /* need to add the md_redundancy_group */
3438 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3439 printk(KERN_WARNING
3440 "md: cannot register extra attributes for %s\n",
3441 mdname(mddev));
3442 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, NULL, "sync_action");
3444 if (mddev->pers->sync_request != NULL &&
3445 pers->sync_request == NULL) {
3446 /* need to remove the md_redundancy_group */
3447 if (mddev->to_remove == NULL)
3448 mddev->to_remove = &md_redundancy_group;
3451 if (mddev->pers->sync_request == NULL &&
3452 mddev->external) {
3453 /* We are converting from a no-redundancy array
3454 * to a redundancy array and metadata is managed
3455 * externally so we need to be sure that writes
3456 * won't block due to a need to transition
3457 * clean->dirty
3458 * until external management is started.
3460 mddev->in_sync = 0;
3461 mddev->safemode_delay = 0;
3462 mddev->safemode = 0;
3465 rdev_for_each(rdev, mddev) {
3466 if (rdev->raid_disk < 0)
3467 continue;
3468 if (rdev->new_raid_disk >= mddev->raid_disks)
3469 rdev->new_raid_disk = -1;
3470 if (rdev->new_raid_disk == rdev->raid_disk)
3471 continue;
3472 sysfs_unlink_rdev(mddev, rdev);
3474 rdev_for_each(rdev, mddev) {
3475 if (rdev->raid_disk < 0)
3476 continue;
3477 if (rdev->new_raid_disk == rdev->raid_disk)
3478 continue;
3479 rdev->raid_disk = rdev->new_raid_disk;
3480 if (rdev->raid_disk < 0)
3481 clear_bit(In_sync, &rdev->flags);
3482 else {
3483 if (sysfs_link_rdev(mddev, rdev))
3484 printk(KERN_WARNING "md: cannot register rd%d"
3485 " for %s after level change\n",
3486 rdev->raid_disk, mdname(mddev));
3490 module_put(mddev->pers->owner);
3491 mddev->pers = pers;
3492 mddev->private = priv;
3493 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3494 mddev->level = mddev->new_level;
3495 mddev->layout = mddev->new_layout;
3496 mddev->chunk_sectors = mddev->new_chunk_sectors;
3497 mddev->delta_disks = 0;
3498 mddev->degraded = 0;
3499 if (mddev->pers->sync_request == NULL) {
3500 /* this is now an array without redundancy, so
3501 * it must always be in_sync
3503 mddev->in_sync = 1;
3504 del_timer_sync(&mddev->safemode_timer);
3506 pers->run(mddev);
3507 mddev_resume(mddev);
3508 set_bit(MD_CHANGE_DEVS, &mddev->flags);
3509 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3510 md_wakeup_thread(mddev->thread);
3511 sysfs_notify(&mddev->kobj, NULL, "level");
3512 md_new_event(mddev);
3513 return rv;
3516 static struct md_sysfs_entry md_level =
3517 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3520 static ssize_t
3521 layout_show(struct mddev *mddev, char *page)
3523 /* just a number, not meaningful for all levels */
3524 if (mddev->reshape_position != MaxSector &&
3525 mddev->layout != mddev->new_layout)
3526 return sprintf(page, "%d (%d)\n",
3527 mddev->new_layout, mddev->layout);
3528 return sprintf(page, "%d\n", mddev->layout);
3531 static ssize_t
3532 layout_store(struct mddev *mddev, const char *buf, size_t len)
3534 char *e;
3535 unsigned long n = simple_strtoul(buf, &e, 10);
3537 if (!*buf || (*e && *e != '\n'))
3538 return -EINVAL;
3540 if (mddev->pers) {
3541 int err;
3542 if (mddev->pers->check_reshape == NULL)
3543 return -EBUSY;
3544 mddev->new_layout = n;
3545 err = mddev->pers->check_reshape(mddev);
3546 if (err) {
3547 mddev->new_layout = mddev->layout;
3548 return err;
3550 } else {
3551 mddev->new_layout = n;
3552 if (mddev->reshape_position == MaxSector)
3553 mddev->layout = n;
3555 return len;
3557 static struct md_sysfs_entry md_layout =
3558 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3561 static ssize_t
3562 raid_disks_show(struct mddev *mddev, char *page)
3564 if (mddev->raid_disks == 0)
3565 return 0;
3566 if (mddev->reshape_position != MaxSector &&
3567 mddev->delta_disks != 0)
3568 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3569 mddev->raid_disks - mddev->delta_disks);
3570 return sprintf(page, "%d\n", mddev->raid_disks);
3573 static int update_raid_disks(struct mddev *mddev, int raid_disks);
3575 static ssize_t
3576 raid_disks_store(struct mddev *mddev, const char *buf, size_t len)
3578 char *e;
3579 int rv = 0;
3580 unsigned long n = simple_strtoul(buf, &e, 10);
3582 if (!*buf || (*e && *e != '\n'))
3583 return -EINVAL;
3585 if (mddev->pers)
3586 rv = update_raid_disks(mddev, n);
3587 else if (mddev->reshape_position != MaxSector) {
3588 int olddisks = mddev->raid_disks - mddev->delta_disks;
3589 mddev->delta_disks = n - olddisks;
3590 mddev->raid_disks = n;
3591 } else
3592 mddev->raid_disks = n;
3593 return rv ? rv : len;
3595 static struct md_sysfs_entry md_raid_disks =
3596 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3598 static ssize_t
3599 chunk_size_show(struct mddev *mddev, char *page)
3601 if (mddev->reshape_position != MaxSector &&
3602 mddev->chunk_sectors != mddev->new_chunk_sectors)
3603 return sprintf(page, "%d (%d)\n",
3604 mddev->new_chunk_sectors << 9,
3605 mddev->chunk_sectors << 9);
3606 return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3609 static ssize_t
3610 chunk_size_store(struct mddev *mddev, const char *buf, size_t len)
3612 char *e;
3613 unsigned long n = simple_strtoul(buf, &e, 10);
3615 if (!*buf || (*e && *e != '\n'))
3616 return -EINVAL;
3618 if (mddev->pers) {
3619 int err;
3620 if (mddev->pers->check_reshape == NULL)
3621 return -EBUSY;
3622 mddev->new_chunk_sectors = n >> 9;
3623 err = mddev->pers->check_reshape(mddev);
3624 if (err) {
3625 mddev->new_chunk_sectors = mddev->chunk_sectors;
3626 return err;
3628 } else {
3629 mddev->new_chunk_sectors = n >> 9;
3630 if (mddev->reshape_position == MaxSector)
3631 mddev->chunk_sectors = n >> 9;
3633 return len;
3635 static struct md_sysfs_entry md_chunk_size =
3636 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3638 static ssize_t
3639 resync_start_show(struct mddev *mddev, char *page)
3641 if (mddev->recovery_cp == MaxSector)
3642 return sprintf(page, "none\n");
3643 return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3646 static ssize_t
3647 resync_start_store(struct mddev *mddev, const char *buf, size_t len)
3649 char *e;
3650 unsigned long long n = simple_strtoull(buf, &e, 10);
3652 if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3653 return -EBUSY;
3654 if (cmd_match(buf, "none"))
3655 n = MaxSector;
3656 else if (!*buf || (*e && *e != '\n'))
3657 return -EINVAL;
3659 mddev->recovery_cp = n;
3660 return len;
3662 static struct md_sysfs_entry md_resync_start =
3663 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
3666 * The array state can be:
3668 * clear
3669 * No devices, no size, no level
3670 * Equivalent to STOP_ARRAY ioctl
3671 * inactive
3672 * May have some settings, but array is not active
3673 * all IO results in error
3674 * When written, doesn't tear down array, but just stops it
3675 * suspended (not supported yet)
3676 * All IO requests will block. The array can be reconfigured.
3677 * Writing this, if accepted, will block until array is quiescent
3678 * readonly
3679 * no resync can happen. no superblocks get written.
3680 * write requests fail
3681 * read-auto
3682 * like readonly, but behaves like 'clean' on a write request.
3684 * clean - no pending writes, but otherwise active.
3685 * When written to inactive array, starts without resync
3686 * If a write request arrives then
3687 * if metadata is known, mark 'dirty' and switch to 'active'.
3688 * if not known, block and switch to write-pending
3689 * If written to an active array that has pending writes, then fails.
3690 * active
3691 * fully active: IO and resync can be happening.
3692 * When written to inactive array, starts with resync
3694 * write-pending
3695 * clean, but writes are blocked waiting for 'active' to be written.
3697 * active-idle
3698 * like active, but no writes have been seen for a while (100msec).
3701 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3702 write_pending, active_idle, bad_word};
3703 static char *array_states[] = {
3704 "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3705 "write-pending", "active-idle", NULL };
3707 static int match_word(const char *word, char **list)
3709 int n;
3710 for (n=0; list[n]; n++)
3711 if (cmd_match(word, list[n]))
3712 break;
3713 return n;
3716 static ssize_t
3717 array_state_show(struct mddev *mddev, char *page)
3719 enum array_state st = inactive;
3721 if (mddev->pers)
3722 switch(mddev->ro) {
3723 case 1:
3724 st = readonly;
3725 break;
3726 case 2:
3727 st = read_auto;
3728 break;
3729 case 0:
3730 if (mddev->in_sync)
3731 st = clean;
3732 else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3733 st = write_pending;
3734 else if (mddev->safemode)
3735 st = active_idle;
3736 else
3737 st = active;
3739 else {
3740 if (list_empty(&mddev->disks) &&
3741 mddev->raid_disks == 0 &&
3742 mddev->dev_sectors == 0)
3743 st = clear;
3744 else
3745 st = inactive;
3747 return sprintf(page, "%s\n", array_states[st]);
3750 static int do_md_stop(struct mddev * mddev, int ro, struct block_device *bdev);
3751 static int md_set_readonly(struct mddev * mddev, struct block_device *bdev);
3752 static int do_md_run(struct mddev * mddev);
3753 static int restart_array(struct mddev *mddev);
3755 static ssize_t
3756 array_state_store(struct mddev *mddev, const char *buf, size_t len)
3758 int err = -EINVAL;
3759 enum array_state st = match_word(buf, array_states);
3760 switch(st) {
3761 case bad_word:
3762 break;
3763 case clear:
3764 /* stopping an active array */
3765 if (atomic_read(&mddev->openers) > 0)
3766 return -EBUSY;
3767 err = do_md_stop(mddev, 0, NULL);
3768 break;
3769 case inactive:
3770 /* stopping an active array */
3771 if (mddev->pers) {
3772 if (atomic_read(&mddev->openers) > 0)
3773 return -EBUSY;
3774 err = do_md_stop(mddev, 2, NULL);
3775 } else
3776 err = 0; /* already inactive */
3777 break;
3778 case suspended:
3779 break; /* not supported yet */
3780 case readonly:
3781 if (mddev->pers)
3782 err = md_set_readonly(mddev, NULL);
3783 else {
3784 mddev->ro = 1;
3785 set_disk_ro(mddev->gendisk, 1);
3786 err = do_md_run(mddev);
3788 break;
3789 case read_auto:
3790 if (mddev->pers) {
3791 if (mddev->ro == 0)
3792 err = md_set_readonly(mddev, NULL);
3793 else if (mddev->ro == 1)
3794 err = restart_array(mddev);
3795 if (err == 0) {
3796 mddev->ro = 2;
3797 set_disk_ro(mddev->gendisk, 0);
3799 } else {
3800 mddev->ro = 2;
3801 err = do_md_run(mddev);
3803 break;
3804 case clean:
3805 if (mddev->pers) {
3806 restart_array(mddev);
3807 spin_lock_irq(&mddev->write_lock);
3808 if (atomic_read(&mddev->writes_pending) == 0) {
3809 if (mddev->in_sync == 0) {
3810 mddev->in_sync = 1;
3811 if (mddev->safemode == 1)
3812 mddev->safemode = 0;
3813 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3815 err = 0;
3816 } else
3817 err = -EBUSY;
3818 spin_unlock_irq(&mddev->write_lock);
3819 } else
3820 err = -EINVAL;
3821 break;
3822 case active:
3823 if (mddev->pers) {
3824 restart_array(mddev);
3825 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3826 wake_up(&mddev->sb_wait);
3827 err = 0;
3828 } else {
3829 mddev->ro = 0;
3830 set_disk_ro(mddev->gendisk, 0);
3831 err = do_md_run(mddev);
3833 break;
3834 case write_pending:
3835 case active_idle:
3836 /* these cannot be set */
3837 break;
3839 if (err)
3840 return err;
3841 else {
3842 if (mddev->hold_active == UNTIL_IOCTL)
3843 mddev->hold_active = 0;
3844 sysfs_notify_dirent_safe(mddev->sysfs_state);
3845 return len;
3848 static struct md_sysfs_entry md_array_state =
3849 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3851 static ssize_t
3852 max_corrected_read_errors_show(struct mddev *mddev, char *page) {
3853 return sprintf(page, "%d\n",
3854 atomic_read(&mddev->max_corr_read_errors));
3857 static ssize_t
3858 max_corrected_read_errors_store(struct mddev *mddev, const char *buf, size_t len)
3860 char *e;
3861 unsigned long n = simple_strtoul(buf, &e, 10);
3863 if (*buf && (*e == 0 || *e == '\n')) {
3864 atomic_set(&mddev->max_corr_read_errors, n);
3865 return len;
3867 return -EINVAL;
3870 static struct md_sysfs_entry max_corr_read_errors =
3871 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
3872 max_corrected_read_errors_store);
3874 static ssize_t
3875 null_show(struct mddev *mddev, char *page)
3877 return -EINVAL;
3880 static ssize_t
3881 new_dev_store(struct mddev *mddev, const char *buf, size_t len)
3883 /* buf must be %d:%d\n? giving major and minor numbers */
3884 /* The new device is added to the array.
3885 * If the array has a persistent superblock, we read the
3886 * superblock to initialise info and check validity.
3887 * Otherwise, only checking done is that in bind_rdev_to_array,
3888 * which mainly checks size.
3890 char *e;
3891 int major = simple_strtoul(buf, &e, 10);
3892 int minor;
3893 dev_t dev;
3894 struct md_rdev *rdev;
3895 int err;
3897 if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
3898 return -EINVAL;
3899 minor = simple_strtoul(e+1, &e, 10);
3900 if (*e && *e != '\n')
3901 return -EINVAL;
3902 dev = MKDEV(major, minor);
3903 if (major != MAJOR(dev) ||
3904 minor != MINOR(dev))
3905 return -EOVERFLOW;
3908 if (mddev->persistent) {
3909 rdev = md_import_device(dev, mddev->major_version,
3910 mddev->minor_version);
3911 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
3912 struct md_rdev *rdev0
3913 = list_entry(mddev->disks.next,
3914 struct md_rdev, same_set);
3915 err = super_types[mddev->major_version]
3916 .load_super(rdev, rdev0, mddev->minor_version);
3917 if (err < 0)
3918 goto out;
3920 } else if (mddev->external)
3921 rdev = md_import_device(dev, -2, -1);
3922 else
3923 rdev = md_import_device(dev, -1, -1);
3925 if (IS_ERR(rdev))
3926 return PTR_ERR(rdev);
3927 err = bind_rdev_to_array(rdev, mddev);
3928 out:
3929 if (err)
3930 export_rdev(rdev);
3931 return err ? err : len;
3934 static struct md_sysfs_entry md_new_device =
3935 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
3937 static ssize_t
3938 bitmap_store(struct mddev *mddev, const char *buf, size_t len)
3940 char *end;
3941 unsigned long chunk, end_chunk;
3943 if (!mddev->bitmap)
3944 goto out;
3945 /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
3946 while (*buf) {
3947 chunk = end_chunk = simple_strtoul(buf, &end, 0);
3948 if (buf == end) break;
3949 if (*end == '-') { /* range */
3950 buf = end + 1;
3951 end_chunk = simple_strtoul(buf, &end, 0);
3952 if (buf == end) break;
3954 if (*end && !isspace(*end)) break;
3955 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
3956 buf = skip_spaces(end);
3958 bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
3959 out:
3960 return len;
3963 static struct md_sysfs_entry md_bitmap =
3964 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
3966 static ssize_t
3967 size_show(struct mddev *mddev, char *page)
3969 return sprintf(page, "%llu\n",
3970 (unsigned long long)mddev->dev_sectors / 2);
3973 static int update_size(struct mddev *mddev, sector_t num_sectors);
3975 static ssize_t
3976 size_store(struct mddev *mddev, const char *buf, size_t len)
3978 /* If array is inactive, we can reduce the component size, but
3979 * not increase it (except from 0).
3980 * If array is active, we can try an on-line resize
3982 sector_t sectors;
3983 int err = strict_blocks_to_sectors(buf, &sectors);
3985 if (err < 0)
3986 return err;
3987 if (mddev->pers) {
3988 err = update_size(mddev, sectors);
3989 md_update_sb(mddev, 1);
3990 } else {
3991 if (mddev->dev_sectors == 0 ||
3992 mddev->dev_sectors > sectors)
3993 mddev->dev_sectors = sectors;
3994 else
3995 err = -ENOSPC;
3997 return err ? err : len;
4000 static struct md_sysfs_entry md_size =
4001 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
4004 /* Metdata version.
4005 * This is one of
4006 * 'none' for arrays with no metadata (good luck...)
4007 * 'external' for arrays with externally managed metadata,
4008 * or N.M for internally known formats
4010 static ssize_t
4011 metadata_show(struct mddev *mddev, char *page)
4013 if (mddev->persistent)
4014 return sprintf(page, "%d.%d\n",
4015 mddev->major_version, mddev->minor_version);
4016 else if (mddev->external)
4017 return sprintf(page, "external:%s\n", mddev->metadata_type);
4018 else
4019 return sprintf(page, "none\n");
4022 static ssize_t
4023 metadata_store(struct mddev *mddev, const char *buf, size_t len)
4025 int major, minor;
4026 char *e;
4027 /* Changing the details of 'external' metadata is
4028 * always permitted. Otherwise there must be
4029 * no devices attached to the array.
4031 if (mddev->external && strncmp(buf, "external:", 9) == 0)
4033 else if (!list_empty(&mddev->disks))
4034 return -EBUSY;
4036 if (cmd_match(buf, "none")) {
4037 mddev->persistent = 0;
4038 mddev->external = 0;
4039 mddev->major_version = 0;
4040 mddev->minor_version = 90;
4041 return len;
4043 if (strncmp(buf, "external:", 9) == 0) {
4044 size_t namelen = len-9;
4045 if (namelen >= sizeof(mddev->metadata_type))
4046 namelen = sizeof(mddev->metadata_type)-1;
4047 strncpy(mddev->metadata_type, buf+9, namelen);
4048 mddev->metadata_type[namelen] = 0;
4049 if (namelen && mddev->metadata_type[namelen-1] == '\n')
4050 mddev->metadata_type[--namelen] = 0;
4051 mddev->persistent = 0;
4052 mddev->external = 1;
4053 mddev->major_version = 0;
4054 mddev->minor_version = 90;
4055 return len;
4057 major = simple_strtoul(buf, &e, 10);
4058 if (e==buf || *e != '.')
4059 return -EINVAL;
4060 buf = e+1;
4061 minor = simple_strtoul(buf, &e, 10);
4062 if (e==buf || (*e && *e != '\n') )
4063 return -EINVAL;
4064 if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
4065 return -ENOENT;
4066 mddev->major_version = major;
4067 mddev->minor_version = minor;
4068 mddev->persistent = 1;
4069 mddev->external = 0;
4070 return len;
4073 static struct md_sysfs_entry md_metadata =
4074 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4076 static ssize_t
4077 action_show(struct mddev *mddev, char *page)
4079 char *type = "idle";
4080 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4081 type = "frozen";
4082 else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4083 (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
4084 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4085 type = "reshape";
4086 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4087 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
4088 type = "resync";
4089 else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
4090 type = "check";
4091 else
4092 type = "repair";
4093 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
4094 type = "recover";
4096 return sprintf(page, "%s\n", type);
4099 static void reap_sync_thread(struct mddev *mddev);
4101 static ssize_t
4102 action_store(struct mddev *mddev, const char *page, size_t len)
4104 if (!mddev->pers || !mddev->pers->sync_request)
4105 return -EINVAL;
4107 if (cmd_match(page, "frozen"))
4108 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4109 else
4110 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4112 if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4113 if (mddev->sync_thread) {
4114 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4115 reap_sync_thread(mddev);
4117 } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4118 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
4119 return -EBUSY;
4120 else if (cmd_match(page, "resync"))
4121 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4122 else if (cmd_match(page, "recover")) {
4123 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4124 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4125 } else if (cmd_match(page, "reshape")) {
4126 int err;
4127 if (mddev->pers->start_reshape == NULL)
4128 return -EINVAL;
4129 err = mddev->pers->start_reshape(mddev);
4130 if (err)
4131 return err;
4132 sysfs_notify(&mddev->kobj, NULL, "degraded");
4133 } else {
4134 if (cmd_match(page, "check"))
4135 set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4136 else if (!cmd_match(page, "repair"))
4137 return -EINVAL;
4138 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4139 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4141 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4142 md_wakeup_thread(mddev->thread);
4143 sysfs_notify_dirent_safe(mddev->sysfs_action);
4144 return len;
4147 static ssize_t
4148 mismatch_cnt_show(struct mddev *mddev, char *page)
4150 return sprintf(page, "%llu\n",
4151 (unsigned long long) mddev->resync_mismatches);
4154 static struct md_sysfs_entry md_scan_mode =
4155 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4158 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4160 static ssize_t
4161 sync_min_show(struct mddev *mddev, char *page)
4163 return sprintf(page, "%d (%s)\n", speed_min(mddev),
4164 mddev->sync_speed_min ? "local": "system");
4167 static ssize_t
4168 sync_min_store(struct mddev *mddev, const char *buf, size_t len)
4170 int min;
4171 char *e;
4172 if (strncmp(buf, "system", 6)==0) {
4173 mddev->sync_speed_min = 0;
4174 return len;
4176 min = simple_strtoul(buf, &e, 10);
4177 if (buf == e || (*e && *e != '\n') || min <= 0)
4178 return -EINVAL;
4179 mddev->sync_speed_min = min;
4180 return len;
4183 static struct md_sysfs_entry md_sync_min =
4184 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4186 static ssize_t
4187 sync_max_show(struct mddev *mddev, char *page)
4189 return sprintf(page, "%d (%s)\n", speed_max(mddev),
4190 mddev->sync_speed_max ? "local": "system");
4193 static ssize_t
4194 sync_max_store(struct mddev *mddev, const char *buf, size_t len)
4196 int max;
4197 char *e;
4198 if (strncmp(buf, "system", 6)==0) {
4199 mddev->sync_speed_max = 0;
4200 return len;
4202 max = simple_strtoul(buf, &e, 10);
4203 if (buf == e || (*e && *e != '\n') || max <= 0)
4204 return -EINVAL;
4205 mddev->sync_speed_max = max;
4206 return len;
4209 static struct md_sysfs_entry md_sync_max =
4210 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4212 static ssize_t
4213 degraded_show(struct mddev *mddev, char *page)
4215 return sprintf(page, "%d\n", mddev->degraded);
4217 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4219 static ssize_t
4220 sync_force_parallel_show(struct mddev *mddev, char *page)
4222 return sprintf(page, "%d\n", mddev->parallel_resync);
4225 static ssize_t
4226 sync_force_parallel_store(struct mddev *mddev, const char *buf, size_t len)
4228 long n;
4230 if (strict_strtol(buf, 10, &n))
4231 return -EINVAL;
4233 if (n != 0 && n != 1)
4234 return -EINVAL;
4236 mddev->parallel_resync = n;
4238 if (mddev->sync_thread)
4239 wake_up(&resync_wait);
4241 return len;
4244 /* force parallel resync, even with shared block devices */
4245 static struct md_sysfs_entry md_sync_force_parallel =
4246 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4247 sync_force_parallel_show, sync_force_parallel_store);
4249 static ssize_t
4250 sync_speed_show(struct mddev *mddev, char *page)
4252 unsigned long resync, dt, db;
4253 if (mddev->curr_resync == 0)
4254 return sprintf(page, "none\n");
4255 resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4256 dt = (jiffies - mddev->resync_mark) / HZ;
4257 if (!dt) dt++;
4258 db = resync - mddev->resync_mark_cnt;
4259 return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4262 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4264 static ssize_t
4265 sync_completed_show(struct mddev *mddev, char *page)
4267 unsigned long long max_sectors, resync;
4269 if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4270 return sprintf(page, "none\n");
4272 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4273 max_sectors = mddev->resync_max_sectors;
4274 else
4275 max_sectors = mddev->dev_sectors;
4277 resync = mddev->curr_resync_completed;
4278 return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4281 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
4283 static ssize_t
4284 min_sync_show(struct mddev *mddev, char *page)
4286 return sprintf(page, "%llu\n",
4287 (unsigned long long)mddev->resync_min);
4289 static ssize_t
4290 min_sync_store(struct mddev *mddev, const char *buf, size_t len)
4292 unsigned long long min;
4293 if (strict_strtoull(buf, 10, &min))
4294 return -EINVAL;
4295 if (min > mddev->resync_max)
4296 return -EINVAL;
4297 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4298 return -EBUSY;
4300 /* Must be a multiple of chunk_size */
4301 if (mddev->chunk_sectors) {
4302 sector_t temp = min;
4303 if (sector_div(temp, mddev->chunk_sectors))
4304 return -EINVAL;
4306 mddev->resync_min = min;
4308 return len;
4311 static struct md_sysfs_entry md_min_sync =
4312 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4314 static ssize_t
4315 max_sync_show(struct mddev *mddev, char *page)
4317 if (mddev->resync_max == MaxSector)
4318 return sprintf(page, "max\n");
4319 else
4320 return sprintf(page, "%llu\n",
4321 (unsigned long long)mddev->resync_max);
4323 static ssize_t
4324 max_sync_store(struct mddev *mddev, const char *buf, size_t len)
4326 if (strncmp(buf, "max", 3) == 0)
4327 mddev->resync_max = MaxSector;
4328 else {
4329 unsigned long long max;
4330 if (strict_strtoull(buf, 10, &max))
4331 return -EINVAL;
4332 if (max < mddev->resync_min)
4333 return -EINVAL;
4334 if (max < mddev->resync_max &&
4335 mddev->ro == 0 &&
4336 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4337 return -EBUSY;
4339 /* Must be a multiple of chunk_size */
4340 if (mddev->chunk_sectors) {
4341 sector_t temp = max;
4342 if (sector_div(temp, mddev->chunk_sectors))
4343 return -EINVAL;
4345 mddev->resync_max = max;
4347 wake_up(&mddev->recovery_wait);
4348 return len;
4351 static struct md_sysfs_entry md_max_sync =
4352 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4354 static ssize_t
4355 suspend_lo_show(struct mddev *mddev, char *page)
4357 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4360 static ssize_t
4361 suspend_lo_store(struct mddev *mddev, const char *buf, size_t len)
4363 char *e;
4364 unsigned long long new = simple_strtoull(buf, &e, 10);
4365 unsigned long long old = mddev->suspend_lo;
4367 if (mddev->pers == NULL ||
4368 mddev->pers->quiesce == NULL)
4369 return -EINVAL;
4370 if (buf == e || (*e && *e != '\n'))
4371 return -EINVAL;
4373 mddev->suspend_lo = new;
4374 if (new >= old)
4375 /* Shrinking suspended region */
4376 mddev->pers->quiesce(mddev, 2);
4377 else {
4378 /* Expanding suspended region - need to wait */
4379 mddev->pers->quiesce(mddev, 1);
4380 mddev->pers->quiesce(mddev, 0);
4382 return len;
4384 static struct md_sysfs_entry md_suspend_lo =
4385 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4388 static ssize_t
4389 suspend_hi_show(struct mddev *mddev, char *page)
4391 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4394 static ssize_t
4395 suspend_hi_store(struct mddev *mddev, const char *buf, size_t len)
4397 char *e;
4398 unsigned long long new = simple_strtoull(buf, &e, 10);
4399 unsigned long long old = mddev->suspend_hi;
4401 if (mddev->pers == NULL ||
4402 mddev->pers->quiesce == NULL)
4403 return -EINVAL;
4404 if (buf == e || (*e && *e != '\n'))
4405 return -EINVAL;
4407 mddev->suspend_hi = new;
4408 if (new <= old)
4409 /* Shrinking suspended region */
4410 mddev->pers->quiesce(mddev, 2);
4411 else {
4412 /* Expanding suspended region - need to wait */
4413 mddev->pers->quiesce(mddev, 1);
4414 mddev->pers->quiesce(mddev, 0);
4416 return len;
4418 static struct md_sysfs_entry md_suspend_hi =
4419 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4421 static ssize_t
4422 reshape_position_show(struct mddev *mddev, char *page)
4424 if (mddev->reshape_position != MaxSector)
4425 return sprintf(page, "%llu\n",
4426 (unsigned long long)mddev->reshape_position);
4427 strcpy(page, "none\n");
4428 return 5;
4431 static ssize_t
4432 reshape_position_store(struct mddev *mddev, const char *buf, size_t len)
4434 char *e;
4435 unsigned long long new = simple_strtoull(buf, &e, 10);
4436 if (mddev->pers)
4437 return -EBUSY;
4438 if (buf == e || (*e && *e != '\n'))
4439 return -EINVAL;
4440 mddev->reshape_position = new;
4441 mddev->delta_disks = 0;
4442 mddev->new_level = mddev->level;
4443 mddev->new_layout = mddev->layout;
4444 mddev->new_chunk_sectors = mddev->chunk_sectors;
4445 return len;
4448 static struct md_sysfs_entry md_reshape_position =
4449 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4450 reshape_position_store);
4452 static ssize_t
4453 array_size_show(struct mddev *mddev, char *page)
4455 if (mddev->external_size)
4456 return sprintf(page, "%llu\n",
4457 (unsigned long long)mddev->array_sectors/2);
4458 else
4459 return sprintf(page, "default\n");
4462 static ssize_t
4463 array_size_store(struct mddev *mddev, const char *buf, size_t len)
4465 sector_t sectors;
4467 if (strncmp(buf, "default", 7) == 0) {
4468 if (mddev->pers)
4469 sectors = mddev->pers->size(mddev, 0, 0);
4470 else
4471 sectors = mddev->array_sectors;
4473 mddev->external_size = 0;
4474 } else {
4475 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4476 return -EINVAL;
4477 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4478 return -E2BIG;
4480 mddev->external_size = 1;
4483 mddev->array_sectors = sectors;
4484 if (mddev->pers) {
4485 set_capacity(mddev->gendisk, mddev->array_sectors);
4486 revalidate_disk(mddev->gendisk);
4488 return len;
4491 static struct md_sysfs_entry md_array_size =
4492 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4493 array_size_store);
4495 static struct attribute *md_default_attrs[] = {
4496 &md_level.attr,
4497 &md_layout.attr,
4498 &md_raid_disks.attr,
4499 &md_chunk_size.attr,
4500 &md_size.attr,
4501 &md_resync_start.attr,
4502 &md_metadata.attr,
4503 &md_new_device.attr,
4504 &md_safe_delay.attr,
4505 &md_array_state.attr,
4506 &md_reshape_position.attr,
4507 &md_array_size.attr,
4508 &max_corr_read_errors.attr,
4509 NULL,
4512 static struct attribute *md_redundancy_attrs[] = {
4513 &md_scan_mode.attr,
4514 &md_mismatches.attr,
4515 &md_sync_min.attr,
4516 &md_sync_max.attr,
4517 &md_sync_speed.attr,
4518 &md_sync_force_parallel.attr,
4519 &md_sync_completed.attr,
4520 &md_min_sync.attr,
4521 &md_max_sync.attr,
4522 &md_suspend_lo.attr,
4523 &md_suspend_hi.attr,
4524 &md_bitmap.attr,
4525 &md_degraded.attr,
4526 NULL,
4528 static struct attribute_group md_redundancy_group = {
4529 .name = NULL,
4530 .attrs = md_redundancy_attrs,
4534 static ssize_t
4535 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4537 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4538 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4539 ssize_t rv;
4541 if (!entry->show)
4542 return -EIO;
4543 spin_lock(&all_mddevs_lock);
4544 if (list_empty(&mddev->all_mddevs)) {
4545 spin_unlock(&all_mddevs_lock);
4546 return -EBUSY;
4548 mddev_get(mddev);
4549 spin_unlock(&all_mddevs_lock);
4551 rv = mddev_lock(mddev);
4552 if (!rv) {
4553 rv = entry->show(mddev, page);
4554 mddev_unlock(mddev);
4556 mddev_put(mddev);
4557 return rv;
4560 static ssize_t
4561 md_attr_store(struct kobject *kobj, struct attribute *attr,
4562 const char *page, size_t length)
4564 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4565 struct mddev *mddev = container_of(kobj, struct mddev, kobj);
4566 ssize_t rv;
4568 if (!entry->store)
4569 return -EIO;
4570 if (!capable(CAP_SYS_ADMIN))
4571 return -EACCES;
4572 spin_lock(&all_mddevs_lock);
4573 if (list_empty(&mddev->all_mddevs)) {
4574 spin_unlock(&all_mddevs_lock);
4575 return -EBUSY;
4577 mddev_get(mddev);
4578 spin_unlock(&all_mddevs_lock);
4579 rv = mddev_lock(mddev);
4580 if (!rv) {
4581 rv = entry->store(mddev, page, length);
4582 mddev_unlock(mddev);
4584 mddev_put(mddev);
4585 return rv;
4588 static void md_free(struct kobject *ko)
4590 struct mddev *mddev = container_of(ko, struct mddev, kobj);
4592 if (mddev->sysfs_state)
4593 sysfs_put(mddev->sysfs_state);
4595 if (mddev->gendisk) {
4596 del_gendisk(mddev->gendisk);
4597 put_disk(mddev->gendisk);
4599 if (mddev->queue)
4600 blk_cleanup_queue(mddev->queue);
4602 kfree(mddev);
4605 static const struct sysfs_ops md_sysfs_ops = {
4606 .show = md_attr_show,
4607 .store = md_attr_store,
4609 static struct kobj_type md_ktype = {
4610 .release = md_free,
4611 .sysfs_ops = &md_sysfs_ops,
4612 .default_attrs = md_default_attrs,
4615 int mdp_major = 0;
4617 static void mddev_delayed_delete(struct work_struct *ws)
4619 struct mddev *mddev = container_of(ws, struct mddev, del_work);
4621 sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4622 kobject_del(&mddev->kobj);
4623 kobject_put(&mddev->kobj);
4626 static int md_alloc(dev_t dev, char *name)
4628 static DEFINE_MUTEX(disks_mutex);
4629 struct mddev *mddev = mddev_find(dev);
4630 struct gendisk *disk;
4631 int partitioned;
4632 int shift;
4633 int unit;
4634 int error;
4636 if (!mddev)
4637 return -ENODEV;
4639 partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4640 shift = partitioned ? MdpMinorShift : 0;
4641 unit = MINOR(mddev->unit) >> shift;
4643 /* wait for any previous instance of this device to be
4644 * completely removed (mddev_delayed_delete).
4646 flush_workqueue(md_misc_wq);
4648 mutex_lock(&disks_mutex);
4649 error = -EEXIST;
4650 if (mddev->gendisk)
4651 goto abort;
4653 if (name) {
4654 /* Need to ensure that 'name' is not a duplicate.
4656 struct mddev *mddev2;
4657 spin_lock(&all_mddevs_lock);
4659 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4660 if (mddev2->gendisk &&
4661 strcmp(mddev2->gendisk->disk_name, name) == 0) {
4662 spin_unlock(&all_mddevs_lock);
4663 goto abort;
4665 spin_unlock(&all_mddevs_lock);
4668 error = -ENOMEM;
4669 mddev->queue = blk_alloc_queue(GFP_KERNEL);
4670 if (!mddev->queue)
4671 goto abort;
4672 mddev->queue->queuedata = mddev;
4674 blk_queue_make_request(mddev->queue, md_make_request);
4675 blk_set_stacking_limits(&mddev->queue->limits);
4677 disk = alloc_disk(1 << shift);
4678 if (!disk) {
4679 blk_cleanup_queue(mddev->queue);
4680 mddev->queue = NULL;
4681 goto abort;
4683 disk->major = MAJOR(mddev->unit);
4684 disk->first_minor = unit << shift;
4685 if (name)
4686 strcpy(disk->disk_name, name);
4687 else if (partitioned)
4688 sprintf(disk->disk_name, "md_d%d", unit);
4689 else
4690 sprintf(disk->disk_name, "md%d", unit);
4691 disk->fops = &md_fops;
4692 disk->private_data = mddev;
4693 disk->queue = mddev->queue;
4694 blk_queue_flush(mddev->queue, REQ_FLUSH | REQ_FUA);
4695 /* Allow extended partitions. This makes the
4696 * 'mdp' device redundant, but we can't really
4697 * remove it now.
4699 disk->flags |= GENHD_FL_EXT_DEVT;
4700 mddev->gendisk = disk;
4701 /* As soon as we call add_disk(), another thread could get
4702 * through to md_open, so make sure it doesn't get too far
4704 mutex_lock(&mddev->open_mutex);
4705 add_disk(disk);
4707 error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4708 &disk_to_dev(disk)->kobj, "%s", "md");
4709 if (error) {
4710 /* This isn't possible, but as kobject_init_and_add is marked
4711 * __must_check, we must do something with the result
4713 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4714 disk->disk_name);
4715 error = 0;
4717 if (mddev->kobj.sd &&
4718 sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4719 printk(KERN_DEBUG "pointless warning\n");
4720 mutex_unlock(&mddev->open_mutex);
4721 abort:
4722 mutex_unlock(&disks_mutex);
4723 if (!error && mddev->kobj.sd) {
4724 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4725 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4727 mddev_put(mddev);
4728 return error;
4731 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4733 md_alloc(dev, NULL);
4734 return NULL;
4737 static int add_named_array(const char *val, struct kernel_param *kp)
4739 /* val must be "md_*" where * is not all digits.
4740 * We allocate an array with a large free minor number, and
4741 * set the name to val. val must not already be an active name.
4743 int len = strlen(val);
4744 char buf[DISK_NAME_LEN];
4746 while (len && val[len-1] == '\n')
4747 len--;
4748 if (len >= DISK_NAME_LEN)
4749 return -E2BIG;
4750 strlcpy(buf, val, len+1);
4751 if (strncmp(buf, "md_", 3) != 0)
4752 return -EINVAL;
4753 return md_alloc(0, buf);
4756 static void md_safemode_timeout(unsigned long data)
4758 struct mddev *mddev = (struct mddev *) data;
4760 if (!atomic_read(&mddev->writes_pending)) {
4761 mddev->safemode = 1;
4762 if (mddev->external)
4763 sysfs_notify_dirent_safe(mddev->sysfs_state);
4765 md_wakeup_thread(mddev->thread);
4768 static int start_dirty_degraded;
4770 int md_run(struct mddev *mddev)
4772 int err;
4773 struct md_rdev *rdev;
4774 struct md_personality *pers;
4776 if (list_empty(&mddev->disks))
4777 /* cannot run an array with no devices.. */
4778 return -EINVAL;
4780 if (mddev->pers)
4781 return -EBUSY;
4782 /* Cannot run until previous stop completes properly */
4783 if (mddev->sysfs_active)
4784 return -EBUSY;
4787 * Analyze all RAID superblock(s)
4789 if (!mddev->raid_disks) {
4790 if (!mddev->persistent)
4791 return -EINVAL;
4792 analyze_sbs(mddev);
4795 if (mddev->level != LEVEL_NONE)
4796 request_module("md-level-%d", mddev->level);
4797 else if (mddev->clevel[0])
4798 request_module("md-%s", mddev->clevel);
4801 * Drop all container device buffers, from now on
4802 * the only valid external interface is through the md
4803 * device.
4805 rdev_for_each(rdev, mddev) {
4806 if (test_bit(Faulty, &rdev->flags))
4807 continue;
4808 sync_blockdev(rdev->bdev);
4809 invalidate_bdev(rdev->bdev);
4811 /* perform some consistency tests on the device.
4812 * We don't want the data to overlap the metadata,
4813 * Internal Bitmap issues have been handled elsewhere.
4815 if (rdev->meta_bdev) {
4816 /* Nothing to check */;
4817 } else if (rdev->data_offset < rdev->sb_start) {
4818 if (mddev->dev_sectors &&
4819 rdev->data_offset + mddev->dev_sectors
4820 > rdev->sb_start) {
4821 printk("md: %s: data overlaps metadata\n",
4822 mdname(mddev));
4823 return -EINVAL;
4825 } else {
4826 if (rdev->sb_start + rdev->sb_size/512
4827 > rdev->data_offset) {
4828 printk("md: %s: metadata overlaps data\n",
4829 mdname(mddev));
4830 return -EINVAL;
4833 sysfs_notify_dirent_safe(rdev->sysfs_state);
4836 if (mddev->bio_set == NULL)
4837 mddev->bio_set = bioset_create(BIO_POOL_SIZE,
4838 sizeof(struct mddev *));
4840 spin_lock(&pers_lock);
4841 pers = find_pers(mddev->level, mddev->clevel);
4842 if (!pers || !try_module_get(pers->owner)) {
4843 spin_unlock(&pers_lock);
4844 if (mddev->level != LEVEL_NONE)
4845 printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
4846 mddev->level);
4847 else
4848 printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
4849 mddev->clevel);
4850 return -EINVAL;
4852 mddev->pers = pers;
4853 spin_unlock(&pers_lock);
4854 if (mddev->level != pers->level) {
4855 mddev->level = pers->level;
4856 mddev->new_level = pers->level;
4858 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
4860 if (mddev->reshape_position != MaxSector &&
4861 pers->start_reshape == NULL) {
4862 /* This personality cannot handle reshaping... */
4863 mddev->pers = NULL;
4864 module_put(pers->owner);
4865 return -EINVAL;
4868 if (pers->sync_request) {
4869 /* Warn if this is a potentially silly
4870 * configuration.
4872 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4873 struct md_rdev *rdev2;
4874 int warned = 0;
4876 rdev_for_each(rdev, mddev)
4877 rdev_for_each(rdev2, mddev) {
4878 if (rdev < rdev2 &&
4879 rdev->bdev->bd_contains ==
4880 rdev2->bdev->bd_contains) {
4881 printk(KERN_WARNING
4882 "%s: WARNING: %s appears to be"
4883 " on the same physical disk as"
4884 " %s.\n",
4885 mdname(mddev),
4886 bdevname(rdev->bdev,b),
4887 bdevname(rdev2->bdev,b2));
4888 warned = 1;
4892 if (warned)
4893 printk(KERN_WARNING
4894 "True protection against single-disk"
4895 " failure might be compromised.\n");
4898 mddev->recovery = 0;
4899 /* may be over-ridden by personality */
4900 mddev->resync_max_sectors = mddev->dev_sectors;
4902 mddev->ok_start_degraded = start_dirty_degraded;
4904 if (start_readonly && mddev->ro == 0)
4905 mddev->ro = 2; /* read-only, but switch on first write */
4907 err = mddev->pers->run(mddev);
4908 if (err)
4909 printk(KERN_ERR "md: pers->run() failed ...\n");
4910 else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
4911 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
4912 " but 'external_size' not in effect?\n", __func__);
4913 printk(KERN_ERR
4914 "md: invalid array_size %llu > default size %llu\n",
4915 (unsigned long long)mddev->array_sectors / 2,
4916 (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
4917 err = -EINVAL;
4918 mddev->pers->stop(mddev);
4920 if (err == 0 && mddev->pers->sync_request) {
4921 err = bitmap_create(mddev);
4922 if (err) {
4923 printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
4924 mdname(mddev), err);
4925 mddev->pers->stop(mddev);
4928 if (err) {
4929 module_put(mddev->pers->owner);
4930 mddev->pers = NULL;
4931 bitmap_destroy(mddev);
4932 return err;
4934 if (mddev->pers->sync_request) {
4935 if (mddev->kobj.sd &&
4936 sysfs_create_group(&mddev->kobj, &md_redundancy_group))
4937 printk(KERN_WARNING
4938 "md: cannot register extra attributes for %s\n",
4939 mdname(mddev));
4940 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
4941 } else if (mddev->ro == 2) /* auto-readonly not meaningful */
4942 mddev->ro = 0;
4944 atomic_set(&mddev->writes_pending,0);
4945 atomic_set(&mddev->max_corr_read_errors,
4946 MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
4947 mddev->safemode = 0;
4948 mddev->safemode_timer.function = md_safemode_timeout;
4949 mddev->safemode_timer.data = (unsigned long) mddev;
4950 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
4951 mddev->in_sync = 1;
4952 smp_wmb();
4953 mddev->ready = 1;
4954 rdev_for_each(rdev, mddev)
4955 if (rdev->raid_disk >= 0)
4956 if (sysfs_link_rdev(mddev, rdev))
4957 /* failure here is OK */;
4959 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4961 if (mddev->flags)
4962 md_update_sb(mddev, 0);
4964 md_new_event(mddev);
4965 sysfs_notify_dirent_safe(mddev->sysfs_state);
4966 sysfs_notify_dirent_safe(mddev->sysfs_action);
4967 sysfs_notify(&mddev->kobj, NULL, "degraded");
4968 return 0;
4970 EXPORT_SYMBOL_GPL(md_run);
4972 static int do_md_run(struct mddev *mddev)
4974 int err;
4976 err = md_run(mddev);
4977 if (err)
4978 goto out;
4979 err = bitmap_load(mddev);
4980 if (err) {
4981 bitmap_destroy(mddev);
4982 goto out;
4985 md_wakeup_thread(mddev->thread);
4986 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
4988 set_capacity(mddev->gendisk, mddev->array_sectors);
4989 revalidate_disk(mddev->gendisk);
4990 mddev->changed = 1;
4991 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4992 out:
4993 return err;
4996 static int restart_array(struct mddev *mddev)
4998 struct gendisk *disk = mddev->gendisk;
5000 /* Complain if it has no devices */
5001 if (list_empty(&mddev->disks))
5002 return -ENXIO;
5003 if (!mddev->pers)
5004 return -EINVAL;
5005 if (!mddev->ro)
5006 return -EBUSY;
5007 mddev->safemode = 0;
5008 mddev->ro = 0;
5009 set_disk_ro(disk, 0);
5010 printk(KERN_INFO "md: %s switched to read-write mode.\n",
5011 mdname(mddev));
5012 /* Kick recovery or resync if necessary */
5013 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5014 md_wakeup_thread(mddev->thread);
5015 md_wakeup_thread(mddev->sync_thread);
5016 sysfs_notify_dirent_safe(mddev->sysfs_state);
5017 return 0;
5020 /* similar to deny_write_access, but accounts for our holding a reference
5021 * to the file ourselves */
5022 static int deny_bitmap_write_access(struct file * file)
5024 struct inode *inode = file->f_mapping->host;
5026 spin_lock(&inode->i_lock);
5027 if (atomic_read(&inode->i_writecount) > 1) {
5028 spin_unlock(&inode->i_lock);
5029 return -ETXTBSY;
5031 atomic_set(&inode->i_writecount, -1);
5032 spin_unlock(&inode->i_lock);
5034 return 0;
5037 void restore_bitmap_write_access(struct file *file)
5039 struct inode *inode = file->f_mapping->host;
5041 spin_lock(&inode->i_lock);
5042 atomic_set(&inode->i_writecount, 1);
5043 spin_unlock(&inode->i_lock);
5046 static void md_clean(struct mddev *mddev)
5048 mddev->array_sectors = 0;
5049 mddev->external_size = 0;
5050 mddev->dev_sectors = 0;
5051 mddev->raid_disks = 0;
5052 mddev->recovery_cp = 0;
5053 mddev->resync_min = 0;
5054 mddev->resync_max = MaxSector;
5055 mddev->reshape_position = MaxSector;
5056 mddev->external = 0;
5057 mddev->persistent = 0;
5058 mddev->level = LEVEL_NONE;
5059 mddev->clevel[0] = 0;
5060 mddev->flags = 0;
5061 mddev->ro = 0;
5062 mddev->metadata_type[0] = 0;
5063 mddev->chunk_sectors = 0;
5064 mddev->ctime = mddev->utime = 0;
5065 mddev->layout = 0;
5066 mddev->max_disks = 0;
5067 mddev->events = 0;
5068 mddev->can_decrease_events = 0;
5069 mddev->delta_disks = 0;
5070 mddev->new_level = LEVEL_NONE;
5071 mddev->new_layout = 0;
5072 mddev->new_chunk_sectors = 0;
5073 mddev->curr_resync = 0;
5074 mddev->resync_mismatches = 0;
5075 mddev->suspend_lo = mddev->suspend_hi = 0;
5076 mddev->sync_speed_min = mddev->sync_speed_max = 0;
5077 mddev->recovery = 0;
5078 mddev->in_sync = 0;
5079 mddev->changed = 0;
5080 mddev->degraded = 0;
5081 mddev->safemode = 0;
5082 mddev->merge_check_needed = 0;
5083 mddev->bitmap_info.offset = 0;
5084 mddev->bitmap_info.default_offset = 0;
5085 mddev->bitmap_info.chunksize = 0;
5086 mddev->bitmap_info.daemon_sleep = 0;
5087 mddev->bitmap_info.max_write_behind = 0;
5090 static void __md_stop_writes(struct mddev *mddev)
5092 if (mddev->sync_thread) {
5093 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5094 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5095 reap_sync_thread(mddev);
5098 del_timer_sync(&mddev->safemode_timer);
5100 bitmap_flush(mddev);
5101 md_super_wait(mddev);
5103 if (!mddev->in_sync || mddev->flags) {
5104 /* mark array as shutdown cleanly */
5105 mddev->in_sync = 1;
5106 md_update_sb(mddev, 1);
5110 void md_stop_writes(struct mddev *mddev)
5112 mddev_lock(mddev);
5113 __md_stop_writes(mddev);
5114 mddev_unlock(mddev);
5116 EXPORT_SYMBOL_GPL(md_stop_writes);
5118 void md_stop(struct mddev *mddev)
5120 mddev->ready = 0;
5121 mddev->pers->stop(mddev);
5122 if (mddev->pers->sync_request && mddev->to_remove == NULL)
5123 mddev->to_remove = &md_redundancy_group;
5124 module_put(mddev->pers->owner);
5125 mddev->pers = NULL;
5126 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5128 EXPORT_SYMBOL_GPL(md_stop);
5130 static int md_set_readonly(struct mddev *mddev, struct block_device *bdev)
5132 int err = 0;
5133 mutex_lock(&mddev->open_mutex);
5134 if (atomic_read(&mddev->openers) > !!bdev) {
5135 printk("md: %s still in use.\n",mdname(mddev));
5136 err = -EBUSY;
5137 goto out;
5139 if (bdev)
5140 sync_blockdev(bdev);
5141 if (mddev->pers) {
5142 __md_stop_writes(mddev);
5144 err = -ENXIO;
5145 if (mddev->ro==1)
5146 goto out;
5147 mddev->ro = 1;
5148 set_disk_ro(mddev->gendisk, 1);
5149 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5150 sysfs_notify_dirent_safe(mddev->sysfs_state);
5151 err = 0;
5153 out:
5154 mutex_unlock(&mddev->open_mutex);
5155 return err;
5158 /* mode:
5159 * 0 - completely stop and dis-assemble array
5160 * 2 - stop but do not disassemble array
5162 static int do_md_stop(struct mddev * mddev, int mode,
5163 struct block_device *bdev)
5165 struct gendisk *disk = mddev->gendisk;
5166 struct md_rdev *rdev;
5168 mutex_lock(&mddev->open_mutex);
5169 if (atomic_read(&mddev->openers) > !!bdev ||
5170 mddev->sysfs_active) {
5171 printk("md: %s still in use.\n",mdname(mddev));
5172 mutex_unlock(&mddev->open_mutex);
5173 return -EBUSY;
5175 if (bdev)
5176 /* It is possible IO was issued on some other
5177 * open file which was closed before we took ->open_mutex.
5178 * As that was not the last close __blkdev_put will not
5179 * have called sync_blockdev, so we must.
5181 sync_blockdev(bdev);
5183 if (mddev->pers) {
5184 if (mddev->ro)
5185 set_disk_ro(disk, 0);
5187 __md_stop_writes(mddev);
5188 md_stop(mddev);
5189 mddev->queue->merge_bvec_fn = NULL;
5190 mddev->queue->backing_dev_info.congested_fn = NULL;
5192 /* tell userspace to handle 'inactive' */
5193 sysfs_notify_dirent_safe(mddev->sysfs_state);
5195 rdev_for_each(rdev, mddev)
5196 if (rdev->raid_disk >= 0)
5197 sysfs_unlink_rdev(mddev, rdev);
5199 set_capacity(disk, 0);
5200 mutex_unlock(&mddev->open_mutex);
5201 mddev->changed = 1;
5202 revalidate_disk(disk);
5204 if (mddev->ro)
5205 mddev->ro = 0;
5206 } else
5207 mutex_unlock(&mddev->open_mutex);
5209 * Free resources if final stop
5211 if (mode == 0) {
5212 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
5214 bitmap_destroy(mddev);
5215 if (mddev->bitmap_info.file) {
5216 restore_bitmap_write_access(mddev->bitmap_info.file);
5217 fput(mddev->bitmap_info.file);
5218 mddev->bitmap_info.file = NULL;
5220 mddev->bitmap_info.offset = 0;
5222 export_array(mddev);
5224 md_clean(mddev);
5225 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5226 if (mddev->hold_active == UNTIL_STOP)
5227 mddev->hold_active = 0;
5229 blk_integrity_unregister(disk);
5230 md_new_event(mddev);
5231 sysfs_notify_dirent_safe(mddev->sysfs_state);
5232 return 0;
5235 #ifndef MODULE
5236 static void autorun_array(struct mddev *mddev)
5238 struct md_rdev *rdev;
5239 int err;
5241 if (list_empty(&mddev->disks))
5242 return;
5244 printk(KERN_INFO "md: running: ");
5246 rdev_for_each(rdev, mddev) {
5247 char b[BDEVNAME_SIZE];
5248 printk("<%s>", bdevname(rdev->bdev,b));
5250 printk("\n");
5252 err = do_md_run(mddev);
5253 if (err) {
5254 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
5255 do_md_stop(mddev, 0, NULL);
5260 * lets try to run arrays based on all disks that have arrived
5261 * until now. (those are in pending_raid_disks)
5263 * the method: pick the first pending disk, collect all disks with
5264 * the same UUID, remove all from the pending list and put them into
5265 * the 'same_array' list. Then order this list based on superblock
5266 * update time (freshest comes first), kick out 'old' disks and
5267 * compare superblocks. If everything's fine then run it.
5269 * If "unit" is allocated, then bump its reference count
5271 static void autorun_devices(int part)
5273 struct md_rdev *rdev0, *rdev, *tmp;
5274 struct mddev *mddev;
5275 char b[BDEVNAME_SIZE];
5277 printk(KERN_INFO "md: autorun ...\n");
5278 while (!list_empty(&pending_raid_disks)) {
5279 int unit;
5280 dev_t dev;
5281 LIST_HEAD(candidates);
5282 rdev0 = list_entry(pending_raid_disks.next,
5283 struct md_rdev, same_set);
5285 printk(KERN_INFO "md: considering %s ...\n",
5286 bdevname(rdev0->bdev,b));
5287 INIT_LIST_HEAD(&candidates);
5288 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
5289 if (super_90_load(rdev, rdev0, 0) >= 0) {
5290 printk(KERN_INFO "md: adding %s ...\n",
5291 bdevname(rdev->bdev,b));
5292 list_move(&rdev->same_set, &candidates);
5295 * now we have a set of devices, with all of them having
5296 * mostly sane superblocks. It's time to allocate the
5297 * mddev.
5299 if (part) {
5300 dev = MKDEV(mdp_major,
5301 rdev0->preferred_minor << MdpMinorShift);
5302 unit = MINOR(dev) >> MdpMinorShift;
5303 } else {
5304 dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
5305 unit = MINOR(dev);
5307 if (rdev0->preferred_minor != unit) {
5308 printk(KERN_INFO "md: unit number in %s is bad: %d\n",
5309 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
5310 break;
5313 md_probe(dev, NULL, NULL);
5314 mddev = mddev_find(dev);
5315 if (!mddev || !mddev->gendisk) {
5316 if (mddev)
5317 mddev_put(mddev);
5318 printk(KERN_ERR
5319 "md: cannot allocate memory for md drive.\n");
5320 break;
5322 if (mddev_lock(mddev))
5323 printk(KERN_WARNING "md: %s locked, cannot run\n",
5324 mdname(mddev));
5325 else if (mddev->raid_disks || mddev->major_version
5326 || !list_empty(&mddev->disks)) {
5327 printk(KERN_WARNING
5328 "md: %s already running, cannot run %s\n",
5329 mdname(mddev), bdevname(rdev0->bdev,b));
5330 mddev_unlock(mddev);
5331 } else {
5332 printk(KERN_INFO "md: created %s\n", mdname(mddev));
5333 mddev->persistent = 1;
5334 rdev_for_each_list(rdev, tmp, &candidates) {
5335 list_del_init(&rdev->same_set);
5336 if (bind_rdev_to_array(rdev, mddev))
5337 export_rdev(rdev);
5339 autorun_array(mddev);
5340 mddev_unlock(mddev);
5342 /* on success, candidates will be empty, on error
5343 * it won't...
5345 rdev_for_each_list(rdev, tmp, &candidates) {
5346 list_del_init(&rdev->same_set);
5347 export_rdev(rdev);
5349 mddev_put(mddev);
5351 printk(KERN_INFO "md: ... autorun DONE.\n");
5353 #endif /* !MODULE */
5355 static int get_version(void __user * arg)
5357 mdu_version_t ver;
5359 ver.major = MD_MAJOR_VERSION;
5360 ver.minor = MD_MINOR_VERSION;
5361 ver.patchlevel = MD_PATCHLEVEL_VERSION;
5363 if (copy_to_user(arg, &ver, sizeof(ver)))
5364 return -EFAULT;
5366 return 0;
5369 static int get_array_info(struct mddev * mddev, void __user * arg)
5371 mdu_array_info_t info;
5372 int nr,working,insync,failed,spare;
5373 struct md_rdev *rdev;
5375 nr=working=insync=failed=spare=0;
5376 rdev_for_each(rdev, mddev) {
5377 nr++;
5378 if (test_bit(Faulty, &rdev->flags))
5379 failed++;
5380 else {
5381 working++;
5382 if (test_bit(In_sync, &rdev->flags))
5383 insync++;
5384 else
5385 spare++;
5389 info.major_version = mddev->major_version;
5390 info.minor_version = mddev->minor_version;
5391 info.patch_version = MD_PATCHLEVEL_VERSION;
5392 info.ctime = mddev->ctime;
5393 info.level = mddev->level;
5394 info.size = mddev->dev_sectors / 2;
5395 if (info.size != mddev->dev_sectors / 2) /* overflow */
5396 info.size = -1;
5397 info.nr_disks = nr;
5398 info.raid_disks = mddev->raid_disks;
5399 info.md_minor = mddev->md_minor;
5400 info.not_persistent= !mddev->persistent;
5402 info.utime = mddev->utime;
5403 info.state = 0;
5404 if (mddev->in_sync)
5405 info.state = (1<<MD_SB_CLEAN);
5406 if (mddev->bitmap && mddev->bitmap_info.offset)
5407 info.state = (1<<MD_SB_BITMAP_PRESENT);
5408 info.active_disks = insync;
5409 info.working_disks = working;
5410 info.failed_disks = failed;
5411 info.spare_disks = spare;
5413 info.layout = mddev->layout;
5414 info.chunk_size = mddev->chunk_sectors << 9;
5416 if (copy_to_user(arg, &info, sizeof(info)))
5417 return -EFAULT;
5419 return 0;
5422 static int get_bitmap_file(struct mddev * mddev, void __user * arg)
5424 mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5425 char *ptr, *buf = NULL;
5426 int err = -ENOMEM;
5428 if (md_allow_write(mddev))
5429 file = kmalloc(sizeof(*file), GFP_NOIO);
5430 else
5431 file = kmalloc(sizeof(*file), GFP_KERNEL);
5433 if (!file)
5434 goto out;
5436 /* bitmap disabled, zero the first byte and copy out */
5437 if (!mddev->bitmap || !mddev->bitmap->file) {
5438 file->pathname[0] = '\0';
5439 goto copy_out;
5442 buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
5443 if (!buf)
5444 goto out;
5446 ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
5447 if (IS_ERR(ptr))
5448 goto out;
5450 strcpy(file->pathname, ptr);
5452 copy_out:
5453 err = 0;
5454 if (copy_to_user(arg, file, sizeof(*file)))
5455 err = -EFAULT;
5456 out:
5457 kfree(buf);
5458 kfree(file);
5459 return err;
5462 static int get_disk_info(struct mddev * mddev, void __user * arg)
5464 mdu_disk_info_t info;
5465 struct md_rdev *rdev;
5467 if (copy_from_user(&info, arg, sizeof(info)))
5468 return -EFAULT;
5470 rdev = find_rdev_nr(mddev, info.number);
5471 if (rdev) {
5472 info.major = MAJOR(rdev->bdev->bd_dev);
5473 info.minor = MINOR(rdev->bdev->bd_dev);
5474 info.raid_disk = rdev->raid_disk;
5475 info.state = 0;
5476 if (test_bit(Faulty, &rdev->flags))
5477 info.state |= (1<<MD_DISK_FAULTY);
5478 else if (test_bit(In_sync, &rdev->flags)) {
5479 info.state |= (1<<MD_DISK_ACTIVE);
5480 info.state |= (1<<MD_DISK_SYNC);
5482 if (test_bit(WriteMostly, &rdev->flags))
5483 info.state |= (1<<MD_DISK_WRITEMOSTLY);
5484 } else {
5485 info.major = info.minor = 0;
5486 info.raid_disk = -1;
5487 info.state = (1<<MD_DISK_REMOVED);
5490 if (copy_to_user(arg, &info, sizeof(info)))
5491 return -EFAULT;
5493 return 0;
5496 static int add_new_disk(struct mddev * mddev, mdu_disk_info_t *info)
5498 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5499 struct md_rdev *rdev;
5500 dev_t dev = MKDEV(info->major,info->minor);
5502 if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5503 return -EOVERFLOW;
5505 if (!mddev->raid_disks) {
5506 int err;
5507 /* expecting a device which has a superblock */
5508 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5509 if (IS_ERR(rdev)) {
5510 printk(KERN_WARNING
5511 "md: md_import_device returned %ld\n",
5512 PTR_ERR(rdev));
5513 return PTR_ERR(rdev);
5515 if (!list_empty(&mddev->disks)) {
5516 struct md_rdev *rdev0
5517 = list_entry(mddev->disks.next,
5518 struct md_rdev, same_set);
5519 err = super_types[mddev->major_version]
5520 .load_super(rdev, rdev0, mddev->minor_version);
5521 if (err < 0) {
5522 printk(KERN_WARNING
5523 "md: %s has different UUID to %s\n",
5524 bdevname(rdev->bdev,b),
5525 bdevname(rdev0->bdev,b2));
5526 export_rdev(rdev);
5527 return -EINVAL;
5530 err = bind_rdev_to_array(rdev, mddev);
5531 if (err)
5532 export_rdev(rdev);
5533 return err;
5537 * add_new_disk can be used once the array is assembled
5538 * to add "hot spares". They must already have a superblock
5539 * written
5541 if (mddev->pers) {
5542 int err;
5543 if (!mddev->pers->hot_add_disk) {
5544 printk(KERN_WARNING
5545 "%s: personality does not support diskops!\n",
5546 mdname(mddev));
5547 return -EINVAL;
5549 if (mddev->persistent)
5550 rdev = md_import_device(dev, mddev->major_version,
5551 mddev->minor_version);
5552 else
5553 rdev = md_import_device(dev, -1, -1);
5554 if (IS_ERR(rdev)) {
5555 printk(KERN_WARNING
5556 "md: md_import_device returned %ld\n",
5557 PTR_ERR(rdev));
5558 return PTR_ERR(rdev);
5560 /* set saved_raid_disk if appropriate */
5561 if (!mddev->persistent) {
5562 if (info->state & (1<<MD_DISK_SYNC) &&
5563 info->raid_disk < mddev->raid_disks) {
5564 rdev->raid_disk = info->raid_disk;
5565 set_bit(In_sync, &rdev->flags);
5566 } else
5567 rdev->raid_disk = -1;
5568 } else
5569 super_types[mddev->major_version].
5570 validate_super(mddev, rdev);
5571 if ((info->state & (1<<MD_DISK_SYNC)) &&
5572 (!test_bit(In_sync, &rdev->flags) ||
5573 rdev->raid_disk != info->raid_disk)) {
5574 /* This was a hot-add request, but events doesn't
5575 * match, so reject it.
5577 export_rdev(rdev);
5578 return -EINVAL;
5581 if (test_bit(In_sync, &rdev->flags))
5582 rdev->saved_raid_disk = rdev->raid_disk;
5583 else
5584 rdev->saved_raid_disk = -1;
5586 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5587 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5588 set_bit(WriteMostly, &rdev->flags);
5589 else
5590 clear_bit(WriteMostly, &rdev->flags);
5592 rdev->raid_disk = -1;
5593 err = bind_rdev_to_array(rdev, mddev);
5594 if (!err && !mddev->pers->hot_remove_disk) {
5595 /* If there is hot_add_disk but no hot_remove_disk
5596 * then added disks for geometry changes,
5597 * and should be added immediately.
5599 super_types[mddev->major_version].
5600 validate_super(mddev, rdev);
5601 err = mddev->pers->hot_add_disk(mddev, rdev);
5602 if (err)
5603 unbind_rdev_from_array(rdev);
5605 if (err)
5606 export_rdev(rdev);
5607 else
5608 sysfs_notify_dirent_safe(rdev->sysfs_state);
5610 md_update_sb(mddev, 1);
5611 if (mddev->degraded)
5612 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5613 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5614 if (!err)
5615 md_new_event(mddev);
5616 md_wakeup_thread(mddev->thread);
5617 return err;
5620 /* otherwise, add_new_disk is only allowed
5621 * for major_version==0 superblocks
5623 if (mddev->major_version != 0) {
5624 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5625 mdname(mddev));
5626 return -EINVAL;
5629 if (!(info->state & (1<<MD_DISK_FAULTY))) {
5630 int err;
5631 rdev = md_import_device(dev, -1, 0);
5632 if (IS_ERR(rdev)) {
5633 printk(KERN_WARNING
5634 "md: error, md_import_device() returned %ld\n",
5635 PTR_ERR(rdev));
5636 return PTR_ERR(rdev);
5638 rdev->desc_nr = info->number;
5639 if (info->raid_disk < mddev->raid_disks)
5640 rdev->raid_disk = info->raid_disk;
5641 else
5642 rdev->raid_disk = -1;
5644 if (rdev->raid_disk < mddev->raid_disks)
5645 if (info->state & (1<<MD_DISK_SYNC))
5646 set_bit(In_sync, &rdev->flags);
5648 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5649 set_bit(WriteMostly, &rdev->flags);
5651 if (!mddev->persistent) {
5652 printk(KERN_INFO "md: nonpersistent superblock ...\n");
5653 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5654 } else
5655 rdev->sb_start = calc_dev_sboffset(rdev);
5656 rdev->sectors = rdev->sb_start;
5658 err = bind_rdev_to_array(rdev, mddev);
5659 if (err) {
5660 export_rdev(rdev);
5661 return err;
5665 return 0;
5668 static int hot_remove_disk(struct mddev * mddev, dev_t dev)
5670 char b[BDEVNAME_SIZE];
5671 struct md_rdev *rdev;
5673 rdev = find_rdev(mddev, dev);
5674 if (!rdev)
5675 return -ENXIO;
5677 if (rdev->raid_disk >= 0)
5678 goto busy;
5680 kick_rdev_from_array(rdev);
5681 md_update_sb(mddev, 1);
5682 md_new_event(mddev);
5684 return 0;
5685 busy:
5686 printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
5687 bdevname(rdev->bdev,b), mdname(mddev));
5688 return -EBUSY;
5691 static int hot_add_disk(struct mddev * mddev, dev_t dev)
5693 char b[BDEVNAME_SIZE];
5694 int err;
5695 struct md_rdev *rdev;
5697 if (!mddev->pers)
5698 return -ENODEV;
5700 if (mddev->major_version != 0) {
5701 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
5702 " version-0 superblocks.\n",
5703 mdname(mddev));
5704 return -EINVAL;
5706 if (!mddev->pers->hot_add_disk) {
5707 printk(KERN_WARNING
5708 "%s: personality does not support diskops!\n",
5709 mdname(mddev));
5710 return -EINVAL;
5713 rdev = md_import_device(dev, -1, 0);
5714 if (IS_ERR(rdev)) {
5715 printk(KERN_WARNING
5716 "md: error, md_import_device() returned %ld\n",
5717 PTR_ERR(rdev));
5718 return -EINVAL;
5721 if (mddev->persistent)
5722 rdev->sb_start = calc_dev_sboffset(rdev);
5723 else
5724 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5726 rdev->sectors = rdev->sb_start;
5728 if (test_bit(Faulty, &rdev->flags)) {
5729 printk(KERN_WARNING
5730 "md: can not hot-add faulty %s disk to %s!\n",
5731 bdevname(rdev->bdev,b), mdname(mddev));
5732 err = -EINVAL;
5733 goto abort_export;
5735 clear_bit(In_sync, &rdev->flags);
5736 rdev->desc_nr = -1;
5737 rdev->saved_raid_disk = -1;
5738 err = bind_rdev_to_array(rdev, mddev);
5739 if (err)
5740 goto abort_export;
5743 * The rest should better be atomic, we can have disk failures
5744 * noticed in interrupt contexts ...
5747 rdev->raid_disk = -1;
5749 md_update_sb(mddev, 1);
5752 * Kick recovery, maybe this spare has to be added to the
5753 * array immediately.
5755 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5756 md_wakeup_thread(mddev->thread);
5757 md_new_event(mddev);
5758 return 0;
5760 abort_export:
5761 export_rdev(rdev);
5762 return err;
5765 static int set_bitmap_file(struct mddev *mddev, int fd)
5767 int err;
5769 if (mddev->pers) {
5770 if (!mddev->pers->quiesce)
5771 return -EBUSY;
5772 if (mddev->recovery || mddev->sync_thread)
5773 return -EBUSY;
5774 /* we should be able to change the bitmap.. */
5778 if (fd >= 0) {
5779 if (mddev->bitmap)
5780 return -EEXIST; /* cannot add when bitmap is present */
5781 mddev->bitmap_info.file = fget(fd);
5783 if (mddev->bitmap_info.file == NULL) {
5784 printk(KERN_ERR "%s: error: failed to get bitmap file\n",
5785 mdname(mddev));
5786 return -EBADF;
5789 err = deny_bitmap_write_access(mddev->bitmap_info.file);
5790 if (err) {
5791 printk(KERN_ERR "%s: error: bitmap file is already in use\n",
5792 mdname(mddev));
5793 fput(mddev->bitmap_info.file);
5794 mddev->bitmap_info.file = NULL;
5795 return err;
5797 mddev->bitmap_info.offset = 0; /* file overrides offset */
5798 } else if (mddev->bitmap == NULL)
5799 return -ENOENT; /* cannot remove what isn't there */
5800 err = 0;
5801 if (mddev->pers) {
5802 mddev->pers->quiesce(mddev, 1);
5803 if (fd >= 0) {
5804 err = bitmap_create(mddev);
5805 if (!err)
5806 err = bitmap_load(mddev);
5808 if (fd < 0 || err) {
5809 bitmap_destroy(mddev);
5810 fd = -1; /* make sure to put the file */
5812 mddev->pers->quiesce(mddev, 0);
5814 if (fd < 0) {
5815 if (mddev->bitmap_info.file) {
5816 restore_bitmap_write_access(mddev->bitmap_info.file);
5817 fput(mddev->bitmap_info.file);
5819 mddev->bitmap_info.file = NULL;
5822 return err;
5826 * set_array_info is used two different ways
5827 * The original usage is when creating a new array.
5828 * In this usage, raid_disks is > 0 and it together with
5829 * level, size, not_persistent,layout,chunksize determine the
5830 * shape of the array.
5831 * This will always create an array with a type-0.90.0 superblock.
5832 * The newer usage is when assembling an array.
5833 * In this case raid_disks will be 0, and the major_version field is
5834 * use to determine which style super-blocks are to be found on the devices.
5835 * The minor and patch _version numbers are also kept incase the
5836 * super_block handler wishes to interpret them.
5838 static int set_array_info(struct mddev * mddev, mdu_array_info_t *info)
5841 if (info->raid_disks == 0) {
5842 /* just setting version number for superblock loading */
5843 if (info->major_version < 0 ||
5844 info->major_version >= ARRAY_SIZE(super_types) ||
5845 super_types[info->major_version].name == NULL) {
5846 /* maybe try to auto-load a module? */
5847 printk(KERN_INFO
5848 "md: superblock version %d not known\n",
5849 info->major_version);
5850 return -EINVAL;
5852 mddev->major_version = info->major_version;
5853 mddev->minor_version = info->minor_version;
5854 mddev->patch_version = info->patch_version;
5855 mddev->persistent = !info->not_persistent;
5856 /* ensure mddev_put doesn't delete this now that there
5857 * is some minimal configuration.
5859 mddev->ctime = get_seconds();
5860 return 0;
5862 mddev->major_version = MD_MAJOR_VERSION;
5863 mddev->minor_version = MD_MINOR_VERSION;
5864 mddev->patch_version = MD_PATCHLEVEL_VERSION;
5865 mddev->ctime = get_seconds();
5867 mddev->level = info->level;
5868 mddev->clevel[0] = 0;
5869 mddev->dev_sectors = 2 * (sector_t)info->size;
5870 mddev->raid_disks = info->raid_disks;
5871 /* don't set md_minor, it is determined by which /dev/md* was
5872 * openned
5874 if (info->state & (1<<MD_SB_CLEAN))
5875 mddev->recovery_cp = MaxSector;
5876 else
5877 mddev->recovery_cp = 0;
5878 mddev->persistent = ! info->not_persistent;
5879 mddev->external = 0;
5881 mddev->layout = info->layout;
5882 mddev->chunk_sectors = info->chunk_size >> 9;
5884 mddev->max_disks = MD_SB_DISKS;
5886 if (mddev->persistent)
5887 mddev->flags = 0;
5888 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5890 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
5891 mddev->bitmap_info.offset = 0;
5893 mddev->reshape_position = MaxSector;
5896 * Generate a 128 bit UUID
5898 get_random_bytes(mddev->uuid, 16);
5900 mddev->new_level = mddev->level;
5901 mddev->new_chunk_sectors = mddev->chunk_sectors;
5902 mddev->new_layout = mddev->layout;
5903 mddev->delta_disks = 0;
5905 return 0;
5908 void md_set_array_sectors(struct mddev *mddev, sector_t array_sectors)
5910 WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
5912 if (mddev->external_size)
5913 return;
5915 mddev->array_sectors = array_sectors;
5917 EXPORT_SYMBOL(md_set_array_sectors);
5919 static int update_size(struct mddev *mddev, sector_t num_sectors)
5921 struct md_rdev *rdev;
5922 int rv;
5923 int fit = (num_sectors == 0);
5925 if (mddev->pers->resize == NULL)
5926 return -EINVAL;
5927 /* The "num_sectors" is the number of sectors of each device that
5928 * is used. This can only make sense for arrays with redundancy.
5929 * linear and raid0 always use whatever space is available. We can only
5930 * consider changing this number if no resync or reconstruction is
5931 * happening, and if the new size is acceptable. It must fit before the
5932 * sb_start or, if that is <data_offset, it must fit before the size
5933 * of each device. If num_sectors is zero, we find the largest size
5934 * that fits.
5936 if (mddev->sync_thread)
5937 return -EBUSY;
5938 if (mddev->bitmap)
5939 /* Sorry, cannot grow a bitmap yet, just remove it,
5940 * grow, and re-add.
5942 return -EBUSY;
5943 rdev_for_each(rdev, mddev) {
5944 sector_t avail = rdev->sectors;
5946 if (fit && (num_sectors == 0 || num_sectors > avail))
5947 num_sectors = avail;
5948 if (avail < num_sectors)
5949 return -ENOSPC;
5951 rv = mddev->pers->resize(mddev, num_sectors);
5952 if (!rv)
5953 revalidate_disk(mddev->gendisk);
5954 return rv;
5957 static int update_raid_disks(struct mddev *mddev, int raid_disks)
5959 int rv;
5960 /* change the number of raid disks */
5961 if (mddev->pers->check_reshape == NULL)
5962 return -EINVAL;
5963 if (raid_disks <= 0 ||
5964 (mddev->max_disks && raid_disks >= mddev->max_disks))
5965 return -EINVAL;
5966 if (mddev->sync_thread || mddev->reshape_position != MaxSector)
5967 return -EBUSY;
5968 mddev->delta_disks = raid_disks - mddev->raid_disks;
5970 rv = mddev->pers->check_reshape(mddev);
5971 if (rv < 0)
5972 mddev->delta_disks = 0;
5973 return rv;
5978 * update_array_info is used to change the configuration of an
5979 * on-line array.
5980 * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
5981 * fields in the info are checked against the array.
5982 * Any differences that cannot be handled will cause an error.
5983 * Normally, only one change can be managed at a time.
5985 static int update_array_info(struct mddev *mddev, mdu_array_info_t *info)
5987 int rv = 0;
5988 int cnt = 0;
5989 int state = 0;
5991 /* calculate expected state,ignoring low bits */
5992 if (mddev->bitmap && mddev->bitmap_info.offset)
5993 state |= (1 << MD_SB_BITMAP_PRESENT);
5995 if (mddev->major_version != info->major_version ||
5996 mddev->minor_version != info->minor_version ||
5997 /* mddev->patch_version != info->patch_version || */
5998 mddev->ctime != info->ctime ||
5999 mddev->level != info->level ||
6000 /* mddev->layout != info->layout || */
6001 !mddev->persistent != info->not_persistent||
6002 mddev->chunk_sectors != info->chunk_size >> 9 ||
6003 /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
6004 ((state^info->state) & 0xfffffe00)
6006 return -EINVAL;
6007 /* Check there is only one change */
6008 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6009 cnt++;
6010 if (mddev->raid_disks != info->raid_disks)
6011 cnt++;
6012 if (mddev->layout != info->layout)
6013 cnt++;
6014 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
6015 cnt++;
6016 if (cnt == 0)
6017 return 0;
6018 if (cnt > 1)
6019 return -EINVAL;
6021 if (mddev->layout != info->layout) {
6022 /* Change layout
6023 * we don't need to do anything at the md level, the
6024 * personality will take care of it all.
6026 if (mddev->pers->check_reshape == NULL)
6027 return -EINVAL;
6028 else {
6029 mddev->new_layout = info->layout;
6030 rv = mddev->pers->check_reshape(mddev);
6031 if (rv)
6032 mddev->new_layout = mddev->layout;
6033 return rv;
6036 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
6037 rv = update_size(mddev, (sector_t)info->size * 2);
6039 if (mddev->raid_disks != info->raid_disks)
6040 rv = update_raid_disks(mddev, info->raid_disks);
6042 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
6043 if (mddev->pers->quiesce == NULL)
6044 return -EINVAL;
6045 if (mddev->recovery || mddev->sync_thread)
6046 return -EBUSY;
6047 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
6048 /* add the bitmap */
6049 if (mddev->bitmap)
6050 return -EEXIST;
6051 if (mddev->bitmap_info.default_offset == 0)
6052 return -EINVAL;
6053 mddev->bitmap_info.offset =
6054 mddev->bitmap_info.default_offset;
6055 mddev->pers->quiesce(mddev, 1);
6056 rv = bitmap_create(mddev);
6057 if (!rv)
6058 rv = bitmap_load(mddev);
6059 if (rv)
6060 bitmap_destroy(mddev);
6061 mddev->pers->quiesce(mddev, 0);
6062 } else {
6063 /* remove the bitmap */
6064 if (!mddev->bitmap)
6065 return -ENOENT;
6066 if (mddev->bitmap->file)
6067 return -EINVAL;
6068 mddev->pers->quiesce(mddev, 1);
6069 bitmap_destroy(mddev);
6070 mddev->pers->quiesce(mddev, 0);
6071 mddev->bitmap_info.offset = 0;
6074 md_update_sb(mddev, 1);
6075 return rv;
6078 static int set_disk_faulty(struct mddev *mddev, dev_t dev)
6080 struct md_rdev *rdev;
6082 if (mddev->pers == NULL)
6083 return -ENODEV;
6085 rdev = find_rdev(mddev, dev);
6086 if (!rdev)
6087 return -ENODEV;
6089 md_error(mddev, rdev);
6090 if (!test_bit(Faulty, &rdev->flags))
6091 return -EBUSY;
6092 return 0;
6096 * We have a problem here : there is no easy way to give a CHS
6097 * virtual geometry. We currently pretend that we have a 2 heads
6098 * 4 sectors (with a BIG number of cylinders...). This drives
6099 * dosfs just mad... ;-)
6101 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
6103 struct mddev *mddev = bdev->bd_disk->private_data;
6105 geo->heads = 2;
6106 geo->sectors = 4;
6107 geo->cylinders = mddev->array_sectors / 8;
6108 return 0;
6111 static int md_ioctl(struct block_device *bdev, fmode_t mode,
6112 unsigned int cmd, unsigned long arg)
6114 int err = 0;
6115 void __user *argp = (void __user *)arg;
6116 struct mddev *mddev = NULL;
6117 int ro;
6119 switch (cmd) {
6120 case RAID_VERSION:
6121 case GET_ARRAY_INFO:
6122 case GET_DISK_INFO:
6123 break;
6124 default:
6125 if (!capable(CAP_SYS_ADMIN))
6126 return -EACCES;
6130 * Commands dealing with the RAID driver but not any
6131 * particular array:
6133 switch (cmd)
6135 case RAID_VERSION:
6136 err = get_version(argp);
6137 goto done;
6139 case PRINT_RAID_DEBUG:
6140 err = 0;
6141 md_print_devices();
6142 goto done;
6144 #ifndef MODULE
6145 case RAID_AUTORUN:
6146 err = 0;
6147 autostart_arrays(arg);
6148 goto done;
6149 #endif
6150 default:;
6154 * Commands creating/starting a new array:
6157 mddev = bdev->bd_disk->private_data;
6159 if (!mddev) {
6160 BUG();
6161 goto abort;
6164 err = mddev_lock(mddev);
6165 if (err) {
6166 printk(KERN_INFO
6167 "md: ioctl lock interrupted, reason %d, cmd %d\n",
6168 err, cmd);
6169 goto abort;
6172 switch (cmd)
6174 case SET_ARRAY_INFO:
6176 mdu_array_info_t info;
6177 if (!arg)
6178 memset(&info, 0, sizeof(info));
6179 else if (copy_from_user(&info, argp, sizeof(info))) {
6180 err = -EFAULT;
6181 goto abort_unlock;
6183 if (mddev->pers) {
6184 err = update_array_info(mddev, &info);
6185 if (err) {
6186 printk(KERN_WARNING "md: couldn't update"
6187 " array info. %d\n", err);
6188 goto abort_unlock;
6190 goto done_unlock;
6192 if (!list_empty(&mddev->disks)) {
6193 printk(KERN_WARNING
6194 "md: array %s already has disks!\n",
6195 mdname(mddev));
6196 err = -EBUSY;
6197 goto abort_unlock;
6199 if (mddev->raid_disks) {
6200 printk(KERN_WARNING
6201 "md: array %s already initialised!\n",
6202 mdname(mddev));
6203 err = -EBUSY;
6204 goto abort_unlock;
6206 err = set_array_info(mddev, &info);
6207 if (err) {
6208 printk(KERN_WARNING "md: couldn't set"
6209 " array info. %d\n", err);
6210 goto abort_unlock;
6213 goto done_unlock;
6215 default:;
6219 * Commands querying/configuring an existing array:
6221 /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
6222 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
6223 if ((!mddev->raid_disks && !mddev->external)
6224 && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
6225 && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
6226 && cmd != GET_BITMAP_FILE) {
6227 err = -ENODEV;
6228 goto abort_unlock;
6232 * Commands even a read-only array can execute:
6234 switch (cmd)
6236 case GET_ARRAY_INFO:
6237 err = get_array_info(mddev, argp);
6238 goto done_unlock;
6240 case GET_BITMAP_FILE:
6241 err = get_bitmap_file(mddev, argp);
6242 goto done_unlock;
6244 case GET_DISK_INFO:
6245 err = get_disk_info(mddev, argp);
6246 goto done_unlock;
6248 case RESTART_ARRAY_RW:
6249 err = restart_array(mddev);
6250 goto done_unlock;
6252 case STOP_ARRAY:
6253 err = do_md_stop(mddev, 0, bdev);
6254 goto done_unlock;
6256 case STOP_ARRAY_RO:
6257 err = md_set_readonly(mddev, bdev);
6258 goto done_unlock;
6260 case BLKROSET:
6261 if (get_user(ro, (int __user *)(arg))) {
6262 err = -EFAULT;
6263 goto done_unlock;
6265 err = -EINVAL;
6267 /* if the bdev is going readonly the value of mddev->ro
6268 * does not matter, no writes are coming
6270 if (ro)
6271 goto done_unlock;
6273 /* are we are already prepared for writes? */
6274 if (mddev->ro != 1)
6275 goto done_unlock;
6277 /* transitioning to readauto need only happen for
6278 * arrays that call md_write_start
6280 if (mddev->pers) {
6281 err = restart_array(mddev);
6282 if (err == 0) {
6283 mddev->ro = 2;
6284 set_disk_ro(mddev->gendisk, 0);
6287 goto done_unlock;
6291 * The remaining ioctls are changing the state of the
6292 * superblock, so we do not allow them on read-only arrays.
6293 * However non-MD ioctls (e.g. get-size) will still come through
6294 * here and hit the 'default' below, so only disallow
6295 * 'md' ioctls, and switch to rw mode if started auto-readonly.
6297 if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
6298 if (mddev->ro == 2) {
6299 mddev->ro = 0;
6300 sysfs_notify_dirent_safe(mddev->sysfs_state);
6301 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6302 md_wakeup_thread(mddev->thread);
6303 } else {
6304 err = -EROFS;
6305 goto abort_unlock;
6309 switch (cmd)
6311 case ADD_NEW_DISK:
6313 mdu_disk_info_t info;
6314 if (copy_from_user(&info, argp, sizeof(info)))
6315 err = -EFAULT;
6316 else
6317 err = add_new_disk(mddev, &info);
6318 goto done_unlock;
6321 case HOT_REMOVE_DISK:
6322 err = hot_remove_disk(mddev, new_decode_dev(arg));
6323 goto done_unlock;
6325 case HOT_ADD_DISK:
6326 err = hot_add_disk(mddev, new_decode_dev(arg));
6327 goto done_unlock;
6329 case SET_DISK_FAULTY:
6330 err = set_disk_faulty(mddev, new_decode_dev(arg));
6331 goto done_unlock;
6333 case RUN_ARRAY:
6334 err = do_md_run(mddev);
6335 goto done_unlock;
6337 case SET_BITMAP_FILE:
6338 err = set_bitmap_file(mddev, (int)arg);
6339 goto done_unlock;
6341 default:
6342 err = -EINVAL;
6343 goto abort_unlock;
6346 done_unlock:
6347 abort_unlock:
6348 if (mddev->hold_active == UNTIL_IOCTL &&
6349 err != -EINVAL)
6350 mddev->hold_active = 0;
6351 mddev_unlock(mddev);
6353 return err;
6354 done:
6355 if (err)
6356 MD_BUG();
6357 abort:
6358 return err;
6360 #ifdef CONFIG_COMPAT
6361 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
6362 unsigned int cmd, unsigned long arg)
6364 switch (cmd) {
6365 case HOT_REMOVE_DISK:
6366 case HOT_ADD_DISK:
6367 case SET_DISK_FAULTY:
6368 case SET_BITMAP_FILE:
6369 /* These take in integer arg, do not convert */
6370 break;
6371 default:
6372 arg = (unsigned long)compat_ptr(arg);
6373 break;
6376 return md_ioctl(bdev, mode, cmd, arg);
6378 #endif /* CONFIG_COMPAT */
6380 static int md_open(struct block_device *bdev, fmode_t mode)
6383 * Succeed if we can lock the mddev, which confirms that
6384 * it isn't being stopped right now.
6386 struct mddev *mddev = mddev_find(bdev->bd_dev);
6387 int err;
6389 if (mddev->gendisk != bdev->bd_disk) {
6390 /* we are racing with mddev_put which is discarding this
6391 * bd_disk.
6393 mddev_put(mddev);
6394 /* Wait until bdev->bd_disk is definitely gone */
6395 flush_workqueue(md_misc_wq);
6396 /* Then retry the open from the top */
6397 return -ERESTARTSYS;
6399 BUG_ON(mddev != bdev->bd_disk->private_data);
6401 if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
6402 goto out;
6404 err = 0;
6405 atomic_inc(&mddev->openers);
6406 mutex_unlock(&mddev->open_mutex);
6408 check_disk_change(bdev);
6409 out:
6410 return err;
6413 static int md_release(struct gendisk *disk, fmode_t mode)
6415 struct mddev *mddev = disk->private_data;
6417 BUG_ON(!mddev);
6418 atomic_dec(&mddev->openers);
6419 mddev_put(mddev);
6421 return 0;
6424 static int md_media_changed(struct gendisk *disk)
6426 struct mddev *mddev = disk->private_data;
6428 return mddev->changed;
6431 static int md_revalidate(struct gendisk *disk)
6433 struct mddev *mddev = disk->private_data;
6435 mddev->changed = 0;
6436 return 0;
6438 static const struct block_device_operations md_fops =
6440 .owner = THIS_MODULE,
6441 .open = md_open,
6442 .release = md_release,
6443 .ioctl = md_ioctl,
6444 #ifdef CONFIG_COMPAT
6445 .compat_ioctl = md_compat_ioctl,
6446 #endif
6447 .getgeo = md_getgeo,
6448 .media_changed = md_media_changed,
6449 .revalidate_disk= md_revalidate,
6452 static int md_thread(void * arg)
6454 struct md_thread *thread = arg;
6457 * md_thread is a 'system-thread', it's priority should be very
6458 * high. We avoid resource deadlocks individually in each
6459 * raid personality. (RAID5 does preallocation) We also use RR and
6460 * the very same RT priority as kswapd, thus we will never get
6461 * into a priority inversion deadlock.
6463 * we definitely have to have equal or higher priority than
6464 * bdflush, otherwise bdflush will deadlock if there are too
6465 * many dirty RAID5 blocks.
6468 allow_signal(SIGKILL);
6469 while (!kthread_should_stop()) {
6471 /* We need to wait INTERRUPTIBLE so that
6472 * we don't add to the load-average.
6473 * That means we need to be sure no signals are
6474 * pending
6476 if (signal_pending(current))
6477 flush_signals(current);
6479 wait_event_interruptible_timeout
6480 (thread->wqueue,
6481 test_bit(THREAD_WAKEUP, &thread->flags)
6482 || kthread_should_stop(),
6483 thread->timeout);
6485 clear_bit(THREAD_WAKEUP, &thread->flags);
6486 if (!kthread_should_stop())
6487 thread->run(thread->mddev);
6490 return 0;
6493 void md_wakeup_thread(struct md_thread *thread)
6495 if (thread) {
6496 pr_debug("md: waking up MD thread %s.\n", thread->tsk->comm);
6497 set_bit(THREAD_WAKEUP, &thread->flags);
6498 wake_up(&thread->wqueue);
6502 struct md_thread *md_register_thread(void (*run) (struct mddev *), struct mddev *mddev,
6503 const char *name)
6505 struct md_thread *thread;
6507 thread = kzalloc(sizeof(struct md_thread), GFP_KERNEL);
6508 if (!thread)
6509 return NULL;
6511 init_waitqueue_head(&thread->wqueue);
6513 thread->run = run;
6514 thread->mddev = mddev;
6515 thread->timeout = MAX_SCHEDULE_TIMEOUT;
6516 thread->tsk = kthread_run(md_thread, thread,
6517 "%s_%s",
6518 mdname(thread->mddev),
6519 name ?: mddev->pers->name);
6520 if (IS_ERR(thread->tsk)) {
6521 kfree(thread);
6522 return NULL;
6524 return thread;
6527 void md_unregister_thread(struct md_thread **threadp)
6529 struct md_thread *thread = *threadp;
6530 if (!thread)
6531 return;
6532 pr_debug("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
6533 /* Locking ensures that mddev_unlock does not wake_up a
6534 * non-existent thread
6536 spin_lock(&pers_lock);
6537 *threadp = NULL;
6538 spin_unlock(&pers_lock);
6540 kthread_stop(thread->tsk);
6541 kfree(thread);
6544 void md_error(struct mddev *mddev, struct md_rdev *rdev)
6546 if (!mddev) {
6547 MD_BUG();
6548 return;
6551 if (!rdev || test_bit(Faulty, &rdev->flags))
6552 return;
6554 if (!mddev->pers || !mddev->pers->error_handler)
6555 return;
6556 mddev->pers->error_handler(mddev,rdev);
6557 if (mddev->degraded)
6558 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6559 sysfs_notify_dirent_safe(rdev->sysfs_state);
6560 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6561 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6562 md_wakeup_thread(mddev->thread);
6563 if (mddev->event_work.func)
6564 queue_work(md_misc_wq, &mddev->event_work);
6565 md_new_event_inintr(mddev);
6568 /* seq_file implementation /proc/mdstat */
6570 static void status_unused(struct seq_file *seq)
6572 int i = 0;
6573 struct md_rdev *rdev;
6575 seq_printf(seq, "unused devices: ");
6577 list_for_each_entry(rdev, &pending_raid_disks, same_set) {
6578 char b[BDEVNAME_SIZE];
6579 i++;
6580 seq_printf(seq, "%s ",
6581 bdevname(rdev->bdev,b));
6583 if (!i)
6584 seq_printf(seq, "<none>");
6586 seq_printf(seq, "\n");
6590 static void status_resync(struct seq_file *seq, struct mddev * mddev)
6592 sector_t max_sectors, resync, res;
6593 unsigned long dt, db;
6594 sector_t rt;
6595 int scale;
6596 unsigned int per_milli;
6598 resync = mddev->curr_resync - atomic_read(&mddev->recovery_active);
6600 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
6601 max_sectors = mddev->resync_max_sectors;
6602 else
6603 max_sectors = mddev->dev_sectors;
6606 * Should not happen.
6608 if (!max_sectors) {
6609 MD_BUG();
6610 return;
6612 /* Pick 'scale' such that (resync>>scale)*1000 will fit
6613 * in a sector_t, and (max_sectors>>scale) will fit in a
6614 * u32, as those are the requirements for sector_div.
6615 * Thus 'scale' must be at least 10
6617 scale = 10;
6618 if (sizeof(sector_t) > sizeof(unsigned long)) {
6619 while ( max_sectors/2 > (1ULL<<(scale+32)))
6620 scale++;
6622 res = (resync>>scale)*1000;
6623 sector_div(res, (u32)((max_sectors>>scale)+1));
6625 per_milli = res;
6627 int i, x = per_milli/50, y = 20-x;
6628 seq_printf(seq, "[");
6629 for (i = 0; i < x; i++)
6630 seq_printf(seq, "=");
6631 seq_printf(seq, ">");
6632 for (i = 0; i < y; i++)
6633 seq_printf(seq, ".");
6634 seq_printf(seq, "] ");
6636 seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
6637 (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
6638 "reshape" :
6639 (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
6640 "check" :
6641 (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
6642 "resync" : "recovery"))),
6643 per_milli/10, per_milli % 10,
6644 (unsigned long long) resync/2,
6645 (unsigned long long) max_sectors/2);
6648 * dt: time from mark until now
6649 * db: blocks written from mark until now
6650 * rt: remaining time
6652 * rt is a sector_t, so could be 32bit or 64bit.
6653 * So we divide before multiply in case it is 32bit and close
6654 * to the limit.
6655 * We scale the divisor (db) by 32 to avoid losing precision
6656 * near the end of resync when the number of remaining sectors
6657 * is close to 'db'.
6658 * We then divide rt by 32 after multiplying by db to compensate.
6659 * The '+1' avoids division by zero if db is very small.
6661 dt = ((jiffies - mddev->resync_mark) / HZ);
6662 if (!dt) dt++;
6663 db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
6664 - mddev->resync_mark_cnt;
6666 rt = max_sectors - resync; /* number of remaining sectors */
6667 sector_div(rt, db/32+1);
6668 rt *= dt;
6669 rt >>= 5;
6671 seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
6672 ((unsigned long)rt % 60)/6);
6674 seq_printf(seq, " speed=%ldK/sec", db/2/dt);
6677 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
6679 struct list_head *tmp;
6680 loff_t l = *pos;
6681 struct mddev *mddev;
6683 if (l >= 0x10000)
6684 return NULL;
6685 if (!l--)
6686 /* header */
6687 return (void*)1;
6689 spin_lock(&all_mddevs_lock);
6690 list_for_each(tmp,&all_mddevs)
6691 if (!l--) {
6692 mddev = list_entry(tmp, struct mddev, all_mddevs);
6693 mddev_get(mddev);
6694 spin_unlock(&all_mddevs_lock);
6695 return mddev;
6697 spin_unlock(&all_mddevs_lock);
6698 if (!l--)
6699 return (void*)2;/* tail */
6700 return NULL;
6703 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
6705 struct list_head *tmp;
6706 struct mddev *next_mddev, *mddev = v;
6708 ++*pos;
6709 if (v == (void*)2)
6710 return NULL;
6712 spin_lock(&all_mddevs_lock);
6713 if (v == (void*)1)
6714 tmp = all_mddevs.next;
6715 else
6716 tmp = mddev->all_mddevs.next;
6717 if (tmp != &all_mddevs)
6718 next_mddev = mddev_get(list_entry(tmp,struct mddev,all_mddevs));
6719 else {
6720 next_mddev = (void*)2;
6721 *pos = 0x10000;
6723 spin_unlock(&all_mddevs_lock);
6725 if (v != (void*)1)
6726 mddev_put(mddev);
6727 return next_mddev;
6731 static void md_seq_stop(struct seq_file *seq, void *v)
6733 struct mddev *mddev = v;
6735 if (mddev && v != (void*)1 && v != (void*)2)
6736 mddev_put(mddev);
6739 static int md_seq_show(struct seq_file *seq, void *v)
6741 struct mddev *mddev = v;
6742 sector_t sectors;
6743 struct md_rdev *rdev;
6745 if (v == (void*)1) {
6746 struct md_personality *pers;
6747 seq_printf(seq, "Personalities : ");
6748 spin_lock(&pers_lock);
6749 list_for_each_entry(pers, &pers_list, list)
6750 seq_printf(seq, "[%s] ", pers->name);
6752 spin_unlock(&pers_lock);
6753 seq_printf(seq, "\n");
6754 seq->poll_event = atomic_read(&md_event_count);
6755 return 0;
6757 if (v == (void*)2) {
6758 status_unused(seq);
6759 return 0;
6762 if (mddev_lock(mddev) < 0)
6763 return -EINTR;
6765 if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
6766 seq_printf(seq, "%s : %sactive", mdname(mddev),
6767 mddev->pers ? "" : "in");
6768 if (mddev->pers) {
6769 if (mddev->ro==1)
6770 seq_printf(seq, " (read-only)");
6771 if (mddev->ro==2)
6772 seq_printf(seq, " (auto-read-only)");
6773 seq_printf(seq, " %s", mddev->pers->name);
6776 sectors = 0;
6777 rdev_for_each(rdev, mddev) {
6778 char b[BDEVNAME_SIZE];
6779 seq_printf(seq, " %s[%d]",
6780 bdevname(rdev->bdev,b), rdev->desc_nr);
6781 if (test_bit(WriteMostly, &rdev->flags))
6782 seq_printf(seq, "(W)");
6783 if (test_bit(Faulty, &rdev->flags)) {
6784 seq_printf(seq, "(F)");
6785 continue;
6787 if (rdev->raid_disk < 0)
6788 seq_printf(seq, "(S)"); /* spare */
6789 if (test_bit(Replacement, &rdev->flags))
6790 seq_printf(seq, "(R)");
6791 sectors += rdev->sectors;
6794 if (!list_empty(&mddev->disks)) {
6795 if (mddev->pers)
6796 seq_printf(seq, "\n %llu blocks",
6797 (unsigned long long)
6798 mddev->array_sectors / 2);
6799 else
6800 seq_printf(seq, "\n %llu blocks",
6801 (unsigned long long)sectors / 2);
6803 if (mddev->persistent) {
6804 if (mddev->major_version != 0 ||
6805 mddev->minor_version != 90) {
6806 seq_printf(seq," super %d.%d",
6807 mddev->major_version,
6808 mddev->minor_version);
6810 } else if (mddev->external)
6811 seq_printf(seq, " super external:%s",
6812 mddev->metadata_type);
6813 else
6814 seq_printf(seq, " super non-persistent");
6816 if (mddev->pers) {
6817 mddev->pers->status(seq, mddev);
6818 seq_printf(seq, "\n ");
6819 if (mddev->pers->sync_request) {
6820 if (mddev->curr_resync > 2) {
6821 status_resync(seq, mddev);
6822 seq_printf(seq, "\n ");
6823 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
6824 seq_printf(seq, "\tresync=DELAYED\n ");
6825 else if (mddev->recovery_cp < MaxSector)
6826 seq_printf(seq, "\tresync=PENDING\n ");
6828 } else
6829 seq_printf(seq, "\n ");
6831 bitmap_status(seq, mddev->bitmap);
6833 seq_printf(seq, "\n");
6835 mddev_unlock(mddev);
6837 return 0;
6840 static const struct seq_operations md_seq_ops = {
6841 .start = md_seq_start,
6842 .next = md_seq_next,
6843 .stop = md_seq_stop,
6844 .show = md_seq_show,
6847 static int md_seq_open(struct inode *inode, struct file *file)
6849 struct seq_file *seq;
6850 int error;
6852 error = seq_open(file, &md_seq_ops);
6853 if (error)
6854 return error;
6856 seq = file->private_data;
6857 seq->poll_event = atomic_read(&md_event_count);
6858 return error;
6861 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
6863 struct seq_file *seq = filp->private_data;
6864 int mask;
6866 poll_wait(filp, &md_event_waiters, wait);
6868 /* always allow read */
6869 mask = POLLIN | POLLRDNORM;
6871 if (seq->poll_event != atomic_read(&md_event_count))
6872 mask |= POLLERR | POLLPRI;
6873 return mask;
6876 static const struct file_operations md_seq_fops = {
6877 .owner = THIS_MODULE,
6878 .open = md_seq_open,
6879 .read = seq_read,
6880 .llseek = seq_lseek,
6881 .release = seq_release_private,
6882 .poll = mdstat_poll,
6885 int register_md_personality(struct md_personality *p)
6887 spin_lock(&pers_lock);
6888 list_add_tail(&p->list, &pers_list);
6889 printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
6890 spin_unlock(&pers_lock);
6891 return 0;
6894 int unregister_md_personality(struct md_personality *p)
6896 printk(KERN_INFO "md: %s personality unregistered\n", p->name);
6897 spin_lock(&pers_lock);
6898 list_del_init(&p->list);
6899 spin_unlock(&pers_lock);
6900 return 0;
6903 static int is_mddev_idle(struct mddev *mddev, int init)
6905 struct md_rdev * rdev;
6906 int idle;
6907 int curr_events;
6909 idle = 1;
6910 rcu_read_lock();
6911 rdev_for_each_rcu(rdev, mddev) {
6912 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
6913 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
6914 (int)part_stat_read(&disk->part0, sectors[1]) -
6915 atomic_read(&disk->sync_io);
6916 /* sync IO will cause sync_io to increase before the disk_stats
6917 * as sync_io is counted when a request starts, and
6918 * disk_stats is counted when it completes.
6919 * So resync activity will cause curr_events to be smaller than
6920 * when there was no such activity.
6921 * non-sync IO will cause disk_stat to increase without
6922 * increasing sync_io so curr_events will (eventually)
6923 * be larger than it was before. Once it becomes
6924 * substantially larger, the test below will cause
6925 * the array to appear non-idle, and resync will slow
6926 * down.
6927 * If there is a lot of outstanding resync activity when
6928 * we set last_event to curr_events, then all that activity
6929 * completing might cause the array to appear non-idle
6930 * and resync will be slowed down even though there might
6931 * not have been non-resync activity. This will only
6932 * happen once though. 'last_events' will soon reflect
6933 * the state where there is little or no outstanding
6934 * resync requests, and further resync activity will
6935 * always make curr_events less than last_events.
6938 if (init || curr_events - rdev->last_events > 64) {
6939 rdev->last_events = curr_events;
6940 idle = 0;
6943 rcu_read_unlock();
6944 return idle;
6947 void md_done_sync(struct mddev *mddev, int blocks, int ok)
6949 /* another "blocks" (512byte) blocks have been synced */
6950 atomic_sub(blocks, &mddev->recovery_active);
6951 wake_up(&mddev->recovery_wait);
6952 if (!ok) {
6953 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6954 md_wakeup_thread(mddev->thread);
6955 // stop recovery, signal do_sync ....
6960 /* md_write_start(mddev, bi)
6961 * If we need to update some array metadata (e.g. 'active' flag
6962 * in superblock) before writing, schedule a superblock update
6963 * and wait for it to complete.
6965 void md_write_start(struct mddev *mddev, struct bio *bi)
6967 int did_change = 0;
6968 if (bio_data_dir(bi) != WRITE)
6969 return;
6971 BUG_ON(mddev->ro == 1);
6972 if (mddev->ro == 2) {
6973 /* need to switch to read/write */
6974 mddev->ro = 0;
6975 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6976 md_wakeup_thread(mddev->thread);
6977 md_wakeup_thread(mddev->sync_thread);
6978 did_change = 1;
6980 atomic_inc(&mddev->writes_pending);
6981 if (mddev->safemode == 1)
6982 mddev->safemode = 0;
6983 if (mddev->in_sync) {
6984 spin_lock_irq(&mddev->write_lock);
6985 if (mddev->in_sync) {
6986 mddev->in_sync = 0;
6987 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
6988 set_bit(MD_CHANGE_PENDING, &mddev->flags);
6989 md_wakeup_thread(mddev->thread);
6990 did_change = 1;
6992 spin_unlock_irq(&mddev->write_lock);
6994 if (did_change)
6995 sysfs_notify_dirent_safe(mddev->sysfs_state);
6996 wait_event(mddev->sb_wait,
6997 !test_bit(MD_CHANGE_PENDING, &mddev->flags));
7000 void md_write_end(struct mddev *mddev)
7002 if (atomic_dec_and_test(&mddev->writes_pending)) {
7003 if (mddev->safemode == 2)
7004 md_wakeup_thread(mddev->thread);
7005 else if (mddev->safemode_delay)
7006 mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
7010 /* md_allow_write(mddev)
7011 * Calling this ensures that the array is marked 'active' so that writes
7012 * may proceed without blocking. It is important to call this before
7013 * attempting a GFP_KERNEL allocation while holding the mddev lock.
7014 * Must be called with mddev_lock held.
7016 * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
7017 * is dropped, so return -EAGAIN after notifying userspace.
7019 int md_allow_write(struct mddev *mddev)
7021 if (!mddev->pers)
7022 return 0;
7023 if (mddev->ro)
7024 return 0;
7025 if (!mddev->pers->sync_request)
7026 return 0;
7028 spin_lock_irq(&mddev->write_lock);
7029 if (mddev->in_sync) {
7030 mddev->in_sync = 0;
7031 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7032 set_bit(MD_CHANGE_PENDING, &mddev->flags);
7033 if (mddev->safemode_delay &&
7034 mddev->safemode == 0)
7035 mddev->safemode = 1;
7036 spin_unlock_irq(&mddev->write_lock);
7037 md_update_sb(mddev, 0);
7038 sysfs_notify_dirent_safe(mddev->sysfs_state);
7039 } else
7040 spin_unlock_irq(&mddev->write_lock);
7042 if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
7043 return -EAGAIN;
7044 else
7045 return 0;
7047 EXPORT_SYMBOL_GPL(md_allow_write);
7049 #define SYNC_MARKS 10
7050 #define SYNC_MARK_STEP (3*HZ)
7051 void md_do_sync(struct mddev *mddev)
7053 struct mddev *mddev2;
7054 unsigned int currspeed = 0,
7055 window;
7056 sector_t max_sectors,j, io_sectors;
7057 unsigned long mark[SYNC_MARKS];
7058 sector_t mark_cnt[SYNC_MARKS];
7059 int last_mark,m;
7060 struct list_head *tmp;
7061 sector_t last_check;
7062 int skipped = 0;
7063 struct md_rdev *rdev;
7064 char *desc;
7066 /* just incase thread restarts... */
7067 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
7068 return;
7069 if (mddev->ro) /* never try to sync a read-only array */
7070 return;
7072 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7073 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
7074 desc = "data-check";
7075 else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7076 desc = "requested-resync";
7077 else
7078 desc = "resync";
7079 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7080 desc = "reshape";
7081 else
7082 desc = "recovery";
7084 /* we overload curr_resync somewhat here.
7085 * 0 == not engaged in resync at all
7086 * 2 == checking that there is no conflict with another sync
7087 * 1 == like 2, but have yielded to allow conflicting resync to
7088 * commense
7089 * other == active in resync - this many blocks
7091 * Before starting a resync we must have set curr_resync to
7092 * 2, and then checked that every "conflicting" array has curr_resync
7093 * less than ours. When we find one that is the same or higher
7094 * we wait on resync_wait. To avoid deadlock, we reduce curr_resync
7095 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
7096 * This will mean we have to start checking from the beginning again.
7100 do {
7101 mddev->curr_resync = 2;
7103 try_again:
7104 if (kthread_should_stop())
7105 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7107 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7108 goto skip;
7109 for_each_mddev(mddev2, tmp) {
7110 if (mddev2 == mddev)
7111 continue;
7112 if (!mddev->parallel_resync
7113 && mddev2->curr_resync
7114 && match_mddev_units(mddev, mddev2)) {
7115 DEFINE_WAIT(wq);
7116 if (mddev < mddev2 && mddev->curr_resync == 2) {
7117 /* arbitrarily yield */
7118 mddev->curr_resync = 1;
7119 wake_up(&resync_wait);
7121 if (mddev > mddev2 && mddev->curr_resync == 1)
7122 /* no need to wait here, we can wait the next
7123 * time 'round when curr_resync == 2
7125 continue;
7126 /* We need to wait 'interruptible' so as not to
7127 * contribute to the load average, and not to
7128 * be caught by 'softlockup'
7130 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
7131 if (!kthread_should_stop() &&
7132 mddev2->curr_resync >= mddev->curr_resync) {
7133 printk(KERN_INFO "md: delaying %s of %s"
7134 " until %s has finished (they"
7135 " share one or more physical units)\n",
7136 desc, mdname(mddev), mdname(mddev2));
7137 mddev_put(mddev2);
7138 if (signal_pending(current))
7139 flush_signals(current);
7140 schedule();
7141 finish_wait(&resync_wait, &wq);
7142 goto try_again;
7144 finish_wait(&resync_wait, &wq);
7147 } while (mddev->curr_resync < 2);
7149 j = 0;
7150 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7151 /* resync follows the size requested by the personality,
7152 * which defaults to physical size, but can be virtual size
7154 max_sectors = mddev->resync_max_sectors;
7155 mddev->resync_mismatches = 0;
7156 /* we don't use the checkpoint if there's a bitmap */
7157 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7158 j = mddev->resync_min;
7159 else if (!mddev->bitmap)
7160 j = mddev->recovery_cp;
7162 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7163 max_sectors = mddev->dev_sectors;
7164 else {
7165 /* recovery follows the physical size of devices */
7166 max_sectors = mddev->dev_sectors;
7167 j = MaxSector;
7168 rcu_read_lock();
7169 rdev_for_each_rcu(rdev, mddev)
7170 if (rdev->raid_disk >= 0 &&
7171 !test_bit(Faulty, &rdev->flags) &&
7172 !test_bit(In_sync, &rdev->flags) &&
7173 rdev->recovery_offset < j)
7174 j = rdev->recovery_offset;
7175 rcu_read_unlock();
7178 printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
7179 printk(KERN_INFO "md: minimum _guaranteed_ speed:"
7180 " %d KB/sec/disk.\n", speed_min(mddev));
7181 printk(KERN_INFO "md: using maximum available idle IO bandwidth "
7182 "(but not more than %d KB/sec) for %s.\n",
7183 speed_max(mddev), desc);
7185 is_mddev_idle(mddev, 1); /* this initializes IO event counters */
7187 io_sectors = 0;
7188 for (m = 0; m < SYNC_MARKS; m++) {
7189 mark[m] = jiffies;
7190 mark_cnt[m] = io_sectors;
7192 last_mark = 0;
7193 mddev->resync_mark = mark[last_mark];
7194 mddev->resync_mark_cnt = mark_cnt[last_mark];
7197 * Tune reconstruction:
7199 window = 32*(PAGE_SIZE/512);
7200 printk(KERN_INFO "md: using %dk window, over a total of %lluk.\n",
7201 window/2, (unsigned long long)max_sectors/2);
7203 atomic_set(&mddev->recovery_active, 0);
7204 last_check = 0;
7206 if (j>2) {
7207 printk(KERN_INFO
7208 "md: resuming %s of %s from checkpoint.\n",
7209 desc, mdname(mddev));
7210 mddev->curr_resync = j;
7212 mddev->curr_resync_completed = j;
7214 while (j < max_sectors) {
7215 sector_t sectors;
7217 skipped = 0;
7219 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7220 ((mddev->curr_resync > mddev->curr_resync_completed &&
7221 (mddev->curr_resync - mddev->curr_resync_completed)
7222 > (max_sectors >> 4)) ||
7223 (j - mddev->curr_resync_completed)*2
7224 >= mddev->resync_max - mddev->curr_resync_completed
7225 )) {
7226 /* time to update curr_resync_completed */
7227 wait_event(mddev->recovery_wait,
7228 atomic_read(&mddev->recovery_active) == 0);
7229 mddev->curr_resync_completed = j;
7230 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7231 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7234 while (j >= mddev->resync_max && !kthread_should_stop()) {
7235 /* As this condition is controlled by user-space,
7236 * we can block indefinitely, so use '_interruptible'
7237 * to avoid triggering warnings.
7239 flush_signals(current); /* just in case */
7240 wait_event_interruptible(mddev->recovery_wait,
7241 mddev->resync_max > j
7242 || kthread_should_stop());
7245 if (kthread_should_stop())
7246 goto interrupted;
7248 sectors = mddev->pers->sync_request(mddev, j, &skipped,
7249 currspeed < speed_min(mddev));
7250 if (sectors == 0) {
7251 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7252 goto out;
7255 if (!skipped) { /* actual IO requested */
7256 io_sectors += sectors;
7257 atomic_add(sectors, &mddev->recovery_active);
7260 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7261 break;
7263 j += sectors;
7264 if (j>1) mddev->curr_resync = j;
7265 mddev->curr_mark_cnt = io_sectors;
7266 if (last_check == 0)
7267 /* this is the earliest that rebuild will be
7268 * visible in /proc/mdstat
7270 md_new_event(mddev);
7272 if (last_check + window > io_sectors || j == max_sectors)
7273 continue;
7275 last_check = io_sectors;
7276 repeat:
7277 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
7278 /* step marks */
7279 int next = (last_mark+1) % SYNC_MARKS;
7281 mddev->resync_mark = mark[next];
7282 mddev->resync_mark_cnt = mark_cnt[next];
7283 mark[next] = jiffies;
7284 mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
7285 last_mark = next;
7289 if (kthread_should_stop())
7290 goto interrupted;
7294 * this loop exits only if either when we are slower than
7295 * the 'hard' speed limit, or the system was IO-idle for
7296 * a jiffy.
7297 * the system might be non-idle CPU-wise, but we only care
7298 * about not overloading the IO subsystem. (things like an
7299 * e2fsck being done on the RAID array should execute fast)
7301 cond_resched();
7303 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
7304 /((jiffies-mddev->resync_mark)/HZ +1) +1;
7306 if (currspeed > speed_min(mddev)) {
7307 if ((currspeed > speed_max(mddev)) ||
7308 !is_mddev_idle(mddev, 0)) {
7309 msleep(500);
7310 goto repeat;
7314 printk(KERN_INFO "md: %s: %s done.\n",mdname(mddev), desc);
7316 * this also signals 'finished resyncing' to md_stop
7318 out:
7319 wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
7321 /* tell personality that we are finished */
7322 mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
7324 if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
7325 mddev->curr_resync > 2) {
7326 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7327 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7328 if (mddev->curr_resync >= mddev->recovery_cp) {
7329 printk(KERN_INFO
7330 "md: checkpointing %s of %s.\n",
7331 desc, mdname(mddev));
7332 mddev->recovery_cp =
7333 mddev->curr_resync_completed;
7335 } else
7336 mddev->recovery_cp = MaxSector;
7337 } else {
7338 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7339 mddev->curr_resync = MaxSector;
7340 rcu_read_lock();
7341 rdev_for_each_rcu(rdev, mddev)
7342 if (rdev->raid_disk >= 0 &&
7343 mddev->delta_disks >= 0 &&
7344 !test_bit(Faulty, &rdev->flags) &&
7345 !test_bit(In_sync, &rdev->flags) &&
7346 rdev->recovery_offset < mddev->curr_resync)
7347 rdev->recovery_offset = mddev->curr_resync;
7348 rcu_read_unlock();
7351 skip:
7352 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7354 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7355 /* We completed so min/max setting can be forgotten if used. */
7356 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7357 mddev->resync_min = 0;
7358 mddev->resync_max = MaxSector;
7359 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7360 mddev->resync_min = mddev->curr_resync_completed;
7361 mddev->curr_resync = 0;
7362 wake_up(&resync_wait);
7363 set_bit(MD_RECOVERY_DONE, &mddev->recovery);
7364 md_wakeup_thread(mddev->thread);
7365 return;
7367 interrupted:
7369 * got a signal, exit.
7371 printk(KERN_INFO
7372 "md: md_do_sync() got signal ... exiting\n");
7373 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7374 goto out;
7377 EXPORT_SYMBOL_GPL(md_do_sync);
7379 static int remove_and_add_spares(struct mddev *mddev)
7381 struct md_rdev *rdev;
7382 int spares = 0;
7383 int removed = 0;
7385 mddev->curr_resync_completed = 0;
7387 rdev_for_each(rdev, mddev)
7388 if (rdev->raid_disk >= 0 &&
7389 !test_bit(Blocked, &rdev->flags) &&
7390 (test_bit(Faulty, &rdev->flags) ||
7391 ! test_bit(In_sync, &rdev->flags)) &&
7392 atomic_read(&rdev->nr_pending)==0) {
7393 if (mddev->pers->hot_remove_disk(
7394 mddev, rdev) == 0) {
7395 sysfs_unlink_rdev(mddev, rdev);
7396 rdev->raid_disk = -1;
7397 removed++;
7400 if (removed)
7401 sysfs_notify(&mddev->kobj, NULL,
7402 "degraded");
7405 rdev_for_each(rdev, mddev) {
7406 if (rdev->raid_disk >= 0 &&
7407 !test_bit(In_sync, &rdev->flags) &&
7408 !test_bit(Faulty, &rdev->flags))
7409 spares++;
7410 if (rdev->raid_disk < 0
7411 && !test_bit(Faulty, &rdev->flags)) {
7412 rdev->recovery_offset = 0;
7413 if (mddev->pers->
7414 hot_add_disk(mddev, rdev) == 0) {
7415 if (sysfs_link_rdev(mddev, rdev))
7416 /* failure here is OK */;
7417 spares++;
7418 md_new_event(mddev);
7419 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7423 if (removed)
7424 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7425 return spares;
7428 static void reap_sync_thread(struct mddev *mddev)
7430 struct md_rdev *rdev;
7432 /* resync has finished, collect result */
7433 md_unregister_thread(&mddev->sync_thread);
7434 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
7435 !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
7436 /* success...*/
7437 /* activate any spares */
7438 if (mddev->pers->spare_active(mddev)) {
7439 sysfs_notify(&mddev->kobj, NULL,
7440 "degraded");
7441 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7444 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7445 mddev->pers->finish_reshape)
7446 mddev->pers->finish_reshape(mddev);
7448 /* If array is no-longer degraded, then any saved_raid_disk
7449 * information must be scrapped. Also if any device is now
7450 * In_sync we must scrape the saved_raid_disk for that device
7451 * do the superblock for an incrementally recovered device
7452 * written out.
7454 rdev_for_each(rdev, mddev)
7455 if (!mddev->degraded ||
7456 test_bit(In_sync, &rdev->flags))
7457 rdev->saved_raid_disk = -1;
7459 md_update_sb(mddev, 1);
7460 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7461 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7462 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7463 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7464 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7465 /* flag recovery needed just to double check */
7466 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7467 sysfs_notify_dirent_safe(mddev->sysfs_action);
7468 md_new_event(mddev);
7469 if (mddev->event_work.func)
7470 queue_work(md_misc_wq, &mddev->event_work);
7474 * This routine is regularly called by all per-raid-array threads to
7475 * deal with generic issues like resync and super-block update.
7476 * Raid personalities that don't have a thread (linear/raid0) do not
7477 * need this as they never do any recovery or update the superblock.
7479 * It does not do any resync itself, but rather "forks" off other threads
7480 * to do that as needed.
7481 * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
7482 * "->recovery" and create a thread at ->sync_thread.
7483 * When the thread finishes it sets MD_RECOVERY_DONE
7484 * and wakeups up this thread which will reap the thread and finish up.
7485 * This thread also removes any faulty devices (with nr_pending == 0).
7487 * The overall approach is:
7488 * 1/ if the superblock needs updating, update it.
7489 * 2/ If a recovery thread is running, don't do anything else.
7490 * 3/ If recovery has finished, clean up, possibly marking spares active.
7491 * 4/ If there are any faulty devices, remove them.
7492 * 5/ If array is degraded, try to add spares devices
7493 * 6/ If array has spares or is not in-sync, start a resync thread.
7495 void md_check_recovery(struct mddev *mddev)
7497 if (mddev->suspended)
7498 return;
7500 if (mddev->bitmap)
7501 bitmap_daemon_work(mddev);
7503 if (signal_pending(current)) {
7504 if (mddev->pers->sync_request && !mddev->external) {
7505 printk(KERN_INFO "md: %s in immediate safe mode\n",
7506 mdname(mddev));
7507 mddev->safemode = 2;
7509 flush_signals(current);
7512 if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
7513 return;
7514 if ( ! (
7515 (mddev->flags & ~ (1<<MD_CHANGE_PENDING)) ||
7516 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7517 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
7518 (mddev->external == 0 && mddev->safemode == 1) ||
7519 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
7520 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
7522 return;
7524 if (mddev_trylock(mddev)) {
7525 int spares = 0;
7527 if (mddev->ro) {
7528 /* Only thing we do on a ro array is remove
7529 * failed devices.
7531 struct md_rdev *rdev;
7532 rdev_for_each(rdev, mddev)
7533 if (rdev->raid_disk >= 0 &&
7534 !test_bit(Blocked, &rdev->flags) &&
7535 test_bit(Faulty, &rdev->flags) &&
7536 atomic_read(&rdev->nr_pending)==0) {
7537 if (mddev->pers->hot_remove_disk(
7538 mddev, rdev) == 0) {
7539 sysfs_unlink_rdev(mddev, rdev);
7540 rdev->raid_disk = -1;
7543 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7544 goto unlock;
7547 if (!mddev->external) {
7548 int did_change = 0;
7549 spin_lock_irq(&mddev->write_lock);
7550 if (mddev->safemode &&
7551 !atomic_read(&mddev->writes_pending) &&
7552 !mddev->in_sync &&
7553 mddev->recovery_cp == MaxSector) {
7554 mddev->in_sync = 1;
7555 did_change = 1;
7556 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7558 if (mddev->safemode == 1)
7559 mddev->safemode = 0;
7560 spin_unlock_irq(&mddev->write_lock);
7561 if (did_change)
7562 sysfs_notify_dirent_safe(mddev->sysfs_state);
7565 if (mddev->flags)
7566 md_update_sb(mddev, 0);
7568 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
7569 !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
7570 /* resync/recovery still happening */
7571 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7572 goto unlock;
7574 if (mddev->sync_thread) {
7575 reap_sync_thread(mddev);
7576 goto unlock;
7578 /* Set RUNNING before clearing NEEDED to avoid
7579 * any transients in the value of "sync_action".
7581 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7582 /* Clear some bits that don't mean anything, but
7583 * might be left set
7585 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
7586 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7588 if (!test_and_clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7589 test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
7590 goto unlock;
7591 /* no recovery is running.
7592 * remove any failed drives, then
7593 * add spares if possible.
7594 * Spare are also removed and re-added, to allow
7595 * the personality to fail the re-add.
7598 if (mddev->reshape_position != MaxSector) {
7599 if (mddev->pers->check_reshape == NULL ||
7600 mddev->pers->check_reshape(mddev) != 0)
7601 /* Cannot proceed */
7602 goto unlock;
7603 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7604 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7605 } else if ((spares = remove_and_add_spares(mddev))) {
7606 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7607 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7608 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7609 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7610 } else if (mddev->recovery_cp < MaxSector) {
7611 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7612 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7613 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
7614 /* nothing to be done ... */
7615 goto unlock;
7617 if (mddev->pers->sync_request) {
7618 if (spares && mddev->bitmap && ! mddev->bitmap->file) {
7619 /* We are adding a device or devices to an array
7620 * which has the bitmap stored on all devices.
7621 * So make sure all bitmap pages get written
7623 bitmap_write_all(mddev->bitmap);
7625 mddev->sync_thread = md_register_thread(md_do_sync,
7626 mddev,
7627 "resync");
7628 if (!mddev->sync_thread) {
7629 printk(KERN_ERR "%s: could not start resync"
7630 " thread...\n",
7631 mdname(mddev));
7632 /* leave the spares where they are, it shouldn't hurt */
7633 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7634 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7635 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7636 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7637 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7638 } else
7639 md_wakeup_thread(mddev->sync_thread);
7640 sysfs_notify_dirent_safe(mddev->sysfs_action);
7641 md_new_event(mddev);
7643 unlock:
7644 if (!mddev->sync_thread) {
7645 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7646 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
7647 &mddev->recovery))
7648 if (mddev->sysfs_action)
7649 sysfs_notify_dirent_safe(mddev->sysfs_action);
7651 mddev_unlock(mddev);
7655 void md_wait_for_blocked_rdev(struct md_rdev *rdev, struct mddev *mddev)
7657 sysfs_notify_dirent_safe(rdev->sysfs_state);
7658 wait_event_timeout(rdev->blocked_wait,
7659 !test_bit(Blocked, &rdev->flags) &&
7660 !test_bit(BlockedBadBlocks, &rdev->flags),
7661 msecs_to_jiffies(5000));
7662 rdev_dec_pending(rdev, mddev);
7664 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
7667 /* Bad block management.
7668 * We can record which blocks on each device are 'bad' and so just
7669 * fail those blocks, or that stripe, rather than the whole device.
7670 * Entries in the bad-block table are 64bits wide. This comprises:
7671 * Length of bad-range, in sectors: 0-511 for lengths 1-512
7672 * Start of bad-range, sector offset, 54 bits (allows 8 exbibytes)
7673 * A 'shift' can be set so that larger blocks are tracked and
7674 * consequently larger devices can be covered.
7675 * 'Acknowledged' flag - 1 bit. - the most significant bit.
7677 * Locking of the bad-block table uses a seqlock so md_is_badblock
7678 * might need to retry if it is very unlucky.
7679 * We will sometimes want to check for bad blocks in a bi_end_io function,
7680 * so we use the write_seqlock_irq variant.
7682 * When looking for a bad block we specify a range and want to
7683 * know if any block in the range is bad. So we binary-search
7684 * to the last range that starts at-or-before the given endpoint,
7685 * (or "before the sector after the target range")
7686 * then see if it ends after the given start.
7687 * We return
7688 * 0 if there are no known bad blocks in the range
7689 * 1 if there are known bad block which are all acknowledged
7690 * -1 if there are bad blocks which have not yet been acknowledged in metadata.
7691 * plus the start/length of the first bad section we overlap.
7693 int md_is_badblock(struct badblocks *bb, sector_t s, int sectors,
7694 sector_t *first_bad, int *bad_sectors)
7696 int hi;
7697 int lo;
7698 u64 *p = bb->page;
7699 int rv;
7700 sector_t target = s + sectors;
7701 unsigned seq;
7703 if (bb->shift > 0) {
7704 /* round the start down, and the end up */
7705 s >>= bb->shift;
7706 target += (1<<bb->shift) - 1;
7707 target >>= bb->shift;
7708 sectors = target - s;
7710 /* 'target' is now the first block after the bad range */
7712 retry:
7713 seq = read_seqbegin(&bb->lock);
7714 lo = 0;
7715 rv = 0;
7716 hi = bb->count;
7718 /* Binary search between lo and hi for 'target'
7719 * i.e. for the last range that starts before 'target'
7721 /* INVARIANT: ranges before 'lo' and at-or-after 'hi'
7722 * are known not to be the last range before target.
7723 * VARIANT: hi-lo is the number of possible
7724 * ranges, and decreases until it reaches 1
7726 while (hi - lo > 1) {
7727 int mid = (lo + hi) / 2;
7728 sector_t a = BB_OFFSET(p[mid]);
7729 if (a < target)
7730 /* This could still be the one, earlier ranges
7731 * could not. */
7732 lo = mid;
7733 else
7734 /* This and later ranges are definitely out. */
7735 hi = mid;
7737 /* 'lo' might be the last that started before target, but 'hi' isn't */
7738 if (hi > lo) {
7739 /* need to check all range that end after 's' to see if
7740 * any are unacknowledged.
7742 while (lo >= 0 &&
7743 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
7744 if (BB_OFFSET(p[lo]) < target) {
7745 /* starts before the end, and finishes after
7746 * the start, so they must overlap
7748 if (rv != -1 && BB_ACK(p[lo]))
7749 rv = 1;
7750 else
7751 rv = -1;
7752 *first_bad = BB_OFFSET(p[lo]);
7753 *bad_sectors = BB_LEN(p[lo]);
7755 lo--;
7759 if (read_seqretry(&bb->lock, seq))
7760 goto retry;
7762 return rv;
7764 EXPORT_SYMBOL_GPL(md_is_badblock);
7767 * Add a range of bad blocks to the table.
7768 * This might extend the table, or might contract it
7769 * if two adjacent ranges can be merged.
7770 * We binary-search to find the 'insertion' point, then
7771 * decide how best to handle it.
7773 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
7774 int acknowledged)
7776 u64 *p;
7777 int lo, hi;
7778 int rv = 1;
7780 if (bb->shift < 0)
7781 /* badblocks are disabled */
7782 return 0;
7784 if (bb->shift) {
7785 /* round the start down, and the end up */
7786 sector_t next = s + sectors;
7787 s >>= bb->shift;
7788 next += (1<<bb->shift) - 1;
7789 next >>= bb->shift;
7790 sectors = next - s;
7793 write_seqlock_irq(&bb->lock);
7795 p = bb->page;
7796 lo = 0;
7797 hi = bb->count;
7798 /* Find the last range that starts at-or-before 's' */
7799 while (hi - lo > 1) {
7800 int mid = (lo + hi) / 2;
7801 sector_t a = BB_OFFSET(p[mid]);
7802 if (a <= s)
7803 lo = mid;
7804 else
7805 hi = mid;
7807 if (hi > lo && BB_OFFSET(p[lo]) > s)
7808 hi = lo;
7810 if (hi > lo) {
7811 /* we found a range that might merge with the start
7812 * of our new range
7814 sector_t a = BB_OFFSET(p[lo]);
7815 sector_t e = a + BB_LEN(p[lo]);
7816 int ack = BB_ACK(p[lo]);
7817 if (e >= s) {
7818 /* Yes, we can merge with a previous range */
7819 if (s == a && s + sectors >= e)
7820 /* new range covers old */
7821 ack = acknowledged;
7822 else
7823 ack = ack && acknowledged;
7825 if (e < s + sectors)
7826 e = s + sectors;
7827 if (e - a <= BB_MAX_LEN) {
7828 p[lo] = BB_MAKE(a, e-a, ack);
7829 s = e;
7830 } else {
7831 /* does not all fit in one range,
7832 * make p[lo] maximal
7834 if (BB_LEN(p[lo]) != BB_MAX_LEN)
7835 p[lo] = BB_MAKE(a, BB_MAX_LEN, ack);
7836 s = a + BB_MAX_LEN;
7838 sectors = e - s;
7841 if (sectors && hi < bb->count) {
7842 /* 'hi' points to the first range that starts after 's'.
7843 * Maybe we can merge with the start of that range */
7844 sector_t a = BB_OFFSET(p[hi]);
7845 sector_t e = a + BB_LEN(p[hi]);
7846 int ack = BB_ACK(p[hi]);
7847 if (a <= s + sectors) {
7848 /* merging is possible */
7849 if (e <= s + sectors) {
7850 /* full overlap */
7851 e = s + sectors;
7852 ack = acknowledged;
7853 } else
7854 ack = ack && acknowledged;
7856 a = s;
7857 if (e - a <= BB_MAX_LEN) {
7858 p[hi] = BB_MAKE(a, e-a, ack);
7859 s = e;
7860 } else {
7861 p[hi] = BB_MAKE(a, BB_MAX_LEN, ack);
7862 s = a + BB_MAX_LEN;
7864 sectors = e - s;
7865 lo = hi;
7866 hi++;
7869 if (sectors == 0 && hi < bb->count) {
7870 /* we might be able to combine lo and hi */
7871 /* Note: 's' is at the end of 'lo' */
7872 sector_t a = BB_OFFSET(p[hi]);
7873 int lolen = BB_LEN(p[lo]);
7874 int hilen = BB_LEN(p[hi]);
7875 int newlen = lolen + hilen - (s - a);
7876 if (s >= a && newlen < BB_MAX_LEN) {
7877 /* yes, we can combine them */
7878 int ack = BB_ACK(p[lo]) && BB_ACK(p[hi]);
7879 p[lo] = BB_MAKE(BB_OFFSET(p[lo]), newlen, ack);
7880 memmove(p + hi, p + hi + 1,
7881 (bb->count - hi - 1) * 8);
7882 bb->count--;
7885 while (sectors) {
7886 /* didn't merge (it all).
7887 * Need to add a range just before 'hi' */
7888 if (bb->count >= MD_MAX_BADBLOCKS) {
7889 /* No room for more */
7890 rv = 0;
7891 break;
7892 } else {
7893 int this_sectors = sectors;
7894 memmove(p + hi + 1, p + hi,
7895 (bb->count - hi) * 8);
7896 bb->count++;
7898 if (this_sectors > BB_MAX_LEN)
7899 this_sectors = BB_MAX_LEN;
7900 p[hi] = BB_MAKE(s, this_sectors, acknowledged);
7901 sectors -= this_sectors;
7902 s += this_sectors;
7906 bb->changed = 1;
7907 if (!acknowledged)
7908 bb->unacked_exist = 1;
7909 write_sequnlock_irq(&bb->lock);
7911 return rv;
7914 int rdev_set_badblocks(struct md_rdev *rdev, sector_t s, int sectors,
7915 int acknowledged)
7917 int rv = md_set_badblocks(&rdev->badblocks,
7918 s + rdev->data_offset, sectors, acknowledged);
7919 if (rv) {
7920 /* Make sure they get written out promptly */
7921 sysfs_notify_dirent_safe(rdev->sysfs_state);
7922 set_bit(MD_CHANGE_CLEAN, &rdev->mddev->flags);
7923 md_wakeup_thread(rdev->mddev->thread);
7925 return rv;
7927 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
7930 * Remove a range of bad blocks from the table.
7931 * This may involve extending the table if we spilt a region,
7932 * but it must not fail. So if the table becomes full, we just
7933 * drop the remove request.
7935 static int md_clear_badblocks(struct badblocks *bb, sector_t s, int sectors)
7937 u64 *p;
7938 int lo, hi;
7939 sector_t target = s + sectors;
7940 int rv = 0;
7942 if (bb->shift > 0) {
7943 /* When clearing we round the start up and the end down.
7944 * This should not matter as the shift should align with
7945 * the block size and no rounding should ever be needed.
7946 * However it is better the think a block is bad when it
7947 * isn't than to think a block is not bad when it is.
7949 s += (1<<bb->shift) - 1;
7950 s >>= bb->shift;
7951 target >>= bb->shift;
7952 sectors = target - s;
7955 write_seqlock_irq(&bb->lock);
7957 p = bb->page;
7958 lo = 0;
7959 hi = bb->count;
7960 /* Find the last range that starts before 'target' */
7961 while (hi - lo > 1) {
7962 int mid = (lo + hi) / 2;
7963 sector_t a = BB_OFFSET(p[mid]);
7964 if (a < target)
7965 lo = mid;
7966 else
7967 hi = mid;
7969 if (hi > lo) {
7970 /* p[lo] is the last range that could overlap the
7971 * current range. Earlier ranges could also overlap,
7972 * but only this one can overlap the end of the range.
7974 if (BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > target) {
7975 /* Partial overlap, leave the tail of this range */
7976 int ack = BB_ACK(p[lo]);
7977 sector_t a = BB_OFFSET(p[lo]);
7978 sector_t end = a + BB_LEN(p[lo]);
7980 if (a < s) {
7981 /* we need to split this range */
7982 if (bb->count >= MD_MAX_BADBLOCKS) {
7983 rv = 0;
7984 goto out;
7986 memmove(p+lo+1, p+lo, (bb->count - lo) * 8);
7987 bb->count++;
7988 p[lo] = BB_MAKE(a, s-a, ack);
7989 lo++;
7991 p[lo] = BB_MAKE(target, end - target, ack);
7992 /* there is no longer an overlap */
7993 hi = lo;
7994 lo--;
7996 while (lo >= 0 &&
7997 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
7998 /* This range does overlap */
7999 if (BB_OFFSET(p[lo]) < s) {
8000 /* Keep the early parts of this range. */
8001 int ack = BB_ACK(p[lo]);
8002 sector_t start = BB_OFFSET(p[lo]);
8003 p[lo] = BB_MAKE(start, s - start, ack);
8004 /* now low doesn't overlap, so.. */
8005 break;
8007 lo--;
8009 /* 'lo' is strictly before, 'hi' is strictly after,
8010 * anything between needs to be discarded
8012 if (hi - lo > 1) {
8013 memmove(p+lo+1, p+hi, (bb->count - hi) * 8);
8014 bb->count -= (hi - lo - 1);
8018 bb->changed = 1;
8019 out:
8020 write_sequnlock_irq(&bb->lock);
8021 return rv;
8024 int rdev_clear_badblocks(struct md_rdev *rdev, sector_t s, int sectors)
8026 return md_clear_badblocks(&rdev->badblocks,
8027 s + rdev->data_offset,
8028 sectors);
8030 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
8033 * Acknowledge all bad blocks in a list.
8034 * This only succeeds if ->changed is clear. It is used by
8035 * in-kernel metadata updates
8037 void md_ack_all_badblocks(struct badblocks *bb)
8039 if (bb->page == NULL || bb->changed)
8040 /* no point even trying */
8041 return;
8042 write_seqlock_irq(&bb->lock);
8044 if (bb->changed == 0 && bb->unacked_exist) {
8045 u64 *p = bb->page;
8046 int i;
8047 for (i = 0; i < bb->count ; i++) {
8048 if (!BB_ACK(p[i])) {
8049 sector_t start = BB_OFFSET(p[i]);
8050 int len = BB_LEN(p[i]);
8051 p[i] = BB_MAKE(start, len, 1);
8054 bb->unacked_exist = 0;
8056 write_sequnlock_irq(&bb->lock);
8058 EXPORT_SYMBOL_GPL(md_ack_all_badblocks);
8060 /* sysfs access to bad-blocks list.
8061 * We present two files.
8062 * 'bad-blocks' lists sector numbers and lengths of ranges that
8063 * are recorded as bad. The list is truncated to fit within
8064 * the one-page limit of sysfs.
8065 * Writing "sector length" to this file adds an acknowledged
8066 * bad block list.
8067 * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
8068 * been acknowledged. Writing to this file adds bad blocks
8069 * without acknowledging them. This is largely for testing.
8072 static ssize_t
8073 badblocks_show(struct badblocks *bb, char *page, int unack)
8075 size_t len;
8076 int i;
8077 u64 *p = bb->page;
8078 unsigned seq;
8080 if (bb->shift < 0)
8081 return 0;
8083 retry:
8084 seq = read_seqbegin(&bb->lock);
8086 len = 0;
8087 i = 0;
8089 while (len < PAGE_SIZE && i < bb->count) {
8090 sector_t s = BB_OFFSET(p[i]);
8091 unsigned int length = BB_LEN(p[i]);
8092 int ack = BB_ACK(p[i]);
8093 i++;
8095 if (unack && ack)
8096 continue;
8098 len += snprintf(page+len, PAGE_SIZE-len, "%llu %u\n",
8099 (unsigned long long)s << bb->shift,
8100 length << bb->shift);
8102 if (unack && len == 0)
8103 bb->unacked_exist = 0;
8105 if (read_seqretry(&bb->lock, seq))
8106 goto retry;
8108 return len;
8111 #define DO_DEBUG 1
8113 static ssize_t
8114 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack)
8116 unsigned long long sector;
8117 int length;
8118 char newline;
8119 #ifdef DO_DEBUG
8120 /* Allow clearing via sysfs *only* for testing/debugging.
8121 * Normally only a successful write may clear a badblock
8123 int clear = 0;
8124 if (page[0] == '-') {
8125 clear = 1;
8126 page++;
8128 #endif /* DO_DEBUG */
8130 switch (sscanf(page, "%llu %d%c", &sector, &length, &newline)) {
8131 case 3:
8132 if (newline != '\n')
8133 return -EINVAL;
8134 case 2:
8135 if (length <= 0)
8136 return -EINVAL;
8137 break;
8138 default:
8139 return -EINVAL;
8142 #ifdef DO_DEBUG
8143 if (clear) {
8144 md_clear_badblocks(bb, sector, length);
8145 return len;
8147 #endif /* DO_DEBUG */
8148 if (md_set_badblocks(bb, sector, length, !unack))
8149 return len;
8150 else
8151 return -ENOSPC;
8154 static int md_notify_reboot(struct notifier_block *this,
8155 unsigned long code, void *x)
8157 struct list_head *tmp;
8158 struct mddev *mddev;
8159 int need_delay = 0;
8161 for_each_mddev(mddev, tmp) {
8162 if (mddev_trylock(mddev)) {
8163 if (mddev->pers)
8164 __md_stop_writes(mddev);
8165 mddev->safemode = 2;
8166 mddev_unlock(mddev);
8168 need_delay = 1;
8171 * certain more exotic SCSI devices are known to be
8172 * volatile wrt too early system reboots. While the
8173 * right place to handle this issue is the given
8174 * driver, we do want to have a safe RAID driver ...
8176 if (need_delay)
8177 mdelay(1000*1);
8179 return NOTIFY_DONE;
8182 static struct notifier_block md_notifier = {
8183 .notifier_call = md_notify_reboot,
8184 .next = NULL,
8185 .priority = INT_MAX, /* before any real devices */
8188 static void md_geninit(void)
8190 pr_debug("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
8192 proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
8195 static int __init md_init(void)
8197 int ret = -ENOMEM;
8199 md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
8200 if (!md_wq)
8201 goto err_wq;
8203 md_misc_wq = alloc_workqueue("md_misc", 0, 0);
8204 if (!md_misc_wq)
8205 goto err_misc_wq;
8207 if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
8208 goto err_md;
8210 if ((ret = register_blkdev(0, "mdp")) < 0)
8211 goto err_mdp;
8212 mdp_major = ret;
8214 blk_register_region(MKDEV(MD_MAJOR, 0), 1UL<<MINORBITS, THIS_MODULE,
8215 md_probe, NULL, NULL);
8216 blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
8217 md_probe, NULL, NULL);
8219 register_reboot_notifier(&md_notifier);
8220 raid_table_header = register_sysctl_table(raid_root_table);
8222 md_geninit();
8223 return 0;
8225 err_mdp:
8226 unregister_blkdev(MD_MAJOR, "md");
8227 err_md:
8228 destroy_workqueue(md_misc_wq);
8229 err_misc_wq:
8230 destroy_workqueue(md_wq);
8231 err_wq:
8232 return ret;
8235 #ifndef MODULE
8238 * Searches all registered partitions for autorun RAID arrays
8239 * at boot time.
8242 static LIST_HEAD(all_detected_devices);
8243 struct detected_devices_node {
8244 struct list_head list;
8245 dev_t dev;
8248 void md_autodetect_dev(dev_t dev)
8250 struct detected_devices_node *node_detected_dev;
8252 node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
8253 if (node_detected_dev) {
8254 node_detected_dev->dev = dev;
8255 list_add_tail(&node_detected_dev->list, &all_detected_devices);
8256 } else {
8257 printk(KERN_CRIT "md: md_autodetect_dev: kzalloc failed"
8258 ", skipping dev(%d,%d)\n", MAJOR(dev), MINOR(dev));
8263 static void autostart_arrays(int part)
8265 struct md_rdev *rdev;
8266 struct detected_devices_node *node_detected_dev;
8267 dev_t dev;
8268 int i_scanned, i_passed;
8270 i_scanned = 0;
8271 i_passed = 0;
8273 printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
8275 while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
8276 i_scanned++;
8277 node_detected_dev = list_entry(all_detected_devices.next,
8278 struct detected_devices_node, list);
8279 list_del(&node_detected_dev->list);
8280 dev = node_detected_dev->dev;
8281 kfree(node_detected_dev);
8282 rdev = md_import_device(dev,0, 90);
8283 if (IS_ERR(rdev))
8284 continue;
8286 if (test_bit(Faulty, &rdev->flags)) {
8287 MD_BUG();
8288 continue;
8290 set_bit(AutoDetected, &rdev->flags);
8291 list_add(&rdev->same_set, &pending_raid_disks);
8292 i_passed++;
8295 printk(KERN_INFO "md: Scanned %d and added %d devices.\n",
8296 i_scanned, i_passed);
8298 autorun_devices(part);
8301 #endif /* !MODULE */
8303 static __exit void md_exit(void)
8305 struct mddev *mddev;
8306 struct list_head *tmp;
8308 blk_unregister_region(MKDEV(MD_MAJOR,0), 1U << MINORBITS);
8309 blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
8311 unregister_blkdev(MD_MAJOR,"md");
8312 unregister_blkdev(mdp_major, "mdp");
8313 unregister_reboot_notifier(&md_notifier);
8314 unregister_sysctl_table(raid_table_header);
8315 remove_proc_entry("mdstat", NULL);
8316 for_each_mddev(mddev, tmp) {
8317 export_array(mddev);
8318 mddev->hold_active = 0;
8320 destroy_workqueue(md_misc_wq);
8321 destroy_workqueue(md_wq);
8324 subsys_initcall(md_init);
8325 module_exit(md_exit)
8327 static int get_ro(char *buffer, struct kernel_param *kp)
8329 return sprintf(buffer, "%d", start_readonly);
8331 static int set_ro(const char *val, struct kernel_param *kp)
8333 char *e;
8334 int num = simple_strtoul(val, &e, 10);
8335 if (*val && (*e == '\0' || *e == '\n')) {
8336 start_readonly = num;
8337 return 0;
8339 return -EINVAL;
8342 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
8343 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
8345 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
8347 EXPORT_SYMBOL(register_md_personality);
8348 EXPORT_SYMBOL(unregister_md_personality);
8349 EXPORT_SYMBOL(md_error);
8350 EXPORT_SYMBOL(md_done_sync);
8351 EXPORT_SYMBOL(md_write_start);
8352 EXPORT_SYMBOL(md_write_end);
8353 EXPORT_SYMBOL(md_register_thread);
8354 EXPORT_SYMBOL(md_unregister_thread);
8355 EXPORT_SYMBOL(md_wakeup_thread);
8356 EXPORT_SYMBOL(md_check_recovery);
8357 MODULE_LICENSE("GPL");
8358 MODULE_DESCRIPTION("MD RAID framework");
8359 MODULE_ALIAS("md");
8360 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);