Merge remote-tracking branch 'moduleh/module.h-split'
[linux-2.6/next.git] / drivers / md / md.c
blob2546479dffaed3f974375cde75c5bae6f277a901
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/mutex.h>
40 #include <linux/buffer_head.h> /* for invalidate_bdev */
41 #include <linux/poll.h>
42 #include <linux/ctype.h>
43 #include <linux/string.h>
44 #include <linux/hdreg.h>
45 #include <linux/proc_fs.h>
46 #include <linux/random.h>
47 #include <linux/module.h>
48 #include <linux/reboot.h>
49 #include <linux/file.h>
50 #include <linux/compat.h>
51 #include <linux/delay.h>
52 #include <linux/raid/md_p.h>
53 #include <linux/raid/md_u.h>
54 #include <linux/slab.h>
55 #include "md.h"
56 #include "bitmap.h"
58 #define DEBUG 0
59 #define dprintk(x...) ((void)(DEBUG && printk(x)))
61 #ifndef MODULE
62 static void autostart_arrays(int part);
63 #endif
65 static LIST_HEAD(pers_list);
66 static DEFINE_SPINLOCK(pers_lock);
68 static void md_print_devices(void);
70 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
71 static struct workqueue_struct *md_wq;
72 static struct workqueue_struct *md_misc_wq;
74 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
77 * Default number of read corrections we'll attempt on an rdev
78 * before ejecting it from the array. We divide the read error
79 * count by 2 for every hour elapsed between read errors.
81 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
83 * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
84 * is 1000 KB/sec, so the extra system load does not show up that much.
85 * Increase it if you want to have more _guaranteed_ speed. Note that
86 * the RAID driver will use the maximum available bandwidth if the IO
87 * subsystem is idle. There is also an 'absolute maximum' reconstruction
88 * speed limit - in case reconstruction slows down your system despite
89 * idle IO detection.
91 * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
92 * or /sys/block/mdX/md/sync_speed_{min,max}
95 static int sysctl_speed_limit_min = 1000;
96 static int sysctl_speed_limit_max = 200000;
97 static inline int speed_min(mddev_t *mddev)
99 return mddev->sync_speed_min ?
100 mddev->sync_speed_min : sysctl_speed_limit_min;
103 static inline int speed_max(mddev_t *mddev)
105 return mddev->sync_speed_max ?
106 mddev->sync_speed_max : sysctl_speed_limit_max;
109 static struct ctl_table_header *raid_table_header;
111 static ctl_table raid_table[] = {
113 .procname = "speed_limit_min",
114 .data = &sysctl_speed_limit_min,
115 .maxlen = sizeof(int),
116 .mode = S_IRUGO|S_IWUSR,
117 .proc_handler = proc_dointvec,
120 .procname = "speed_limit_max",
121 .data = &sysctl_speed_limit_max,
122 .maxlen = sizeof(int),
123 .mode = S_IRUGO|S_IWUSR,
124 .proc_handler = proc_dointvec,
129 static ctl_table raid_dir_table[] = {
131 .procname = "raid",
132 .maxlen = 0,
133 .mode = S_IRUGO|S_IXUGO,
134 .child = raid_table,
139 static ctl_table raid_root_table[] = {
141 .procname = "dev",
142 .maxlen = 0,
143 .mode = 0555,
144 .child = raid_dir_table,
149 static const struct block_device_operations md_fops;
151 static int start_readonly;
153 /* bio_clone_mddev
154 * like bio_clone, but with a local bio set
157 static void mddev_bio_destructor(struct bio *bio)
159 mddev_t *mddev, **mddevp;
161 mddevp = (void*)bio;
162 mddev = mddevp[-1];
164 bio_free(bio, mddev->bio_set);
167 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
168 mddev_t *mddev)
170 struct bio *b;
171 mddev_t **mddevp;
173 if (!mddev || !mddev->bio_set)
174 return bio_alloc(gfp_mask, nr_iovecs);
176 b = bio_alloc_bioset(gfp_mask, nr_iovecs,
177 mddev->bio_set);
178 if (!b)
179 return NULL;
180 mddevp = (void*)b;
181 mddevp[-1] = mddev;
182 b->bi_destructor = mddev_bio_destructor;
183 return b;
185 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
187 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
188 mddev_t *mddev)
190 struct bio *b;
191 mddev_t **mddevp;
193 if (!mddev || !mddev->bio_set)
194 return bio_clone(bio, gfp_mask);
196 b = bio_alloc_bioset(gfp_mask, bio->bi_max_vecs,
197 mddev->bio_set);
198 if (!b)
199 return NULL;
200 mddevp = (void*)b;
201 mddevp[-1] = mddev;
202 b->bi_destructor = mddev_bio_destructor;
203 __bio_clone(b, bio);
204 if (bio_integrity(bio)) {
205 int ret;
207 ret = bio_integrity_clone(b, bio, gfp_mask, mddev->bio_set);
209 if (ret < 0) {
210 bio_put(b);
211 return NULL;
215 return b;
217 EXPORT_SYMBOL_GPL(bio_clone_mddev);
219 void md_trim_bio(struct bio *bio, int offset, int size)
221 /* 'bio' is a cloned bio which we need to trim to match
222 * the given offset and size.
223 * This requires adjusting bi_sector, bi_size, and bi_io_vec
225 int i;
226 struct bio_vec *bvec;
227 int sofar = 0;
229 size <<= 9;
230 if (offset == 0 && size == bio->bi_size)
231 return;
233 bio->bi_sector += offset;
234 bio->bi_size = size;
235 offset <<= 9;
236 clear_bit(BIO_SEG_VALID, &bio->bi_flags);
238 while (bio->bi_idx < bio->bi_vcnt &&
239 bio->bi_io_vec[bio->bi_idx].bv_len <= offset) {
240 /* remove this whole bio_vec */
241 offset -= bio->bi_io_vec[bio->bi_idx].bv_len;
242 bio->bi_idx++;
244 if (bio->bi_idx < bio->bi_vcnt) {
245 bio->bi_io_vec[bio->bi_idx].bv_offset += offset;
246 bio->bi_io_vec[bio->bi_idx].bv_len -= offset;
248 /* avoid any complications with bi_idx being non-zero*/
249 if (bio->bi_idx) {
250 memmove(bio->bi_io_vec, bio->bi_io_vec+bio->bi_idx,
251 (bio->bi_vcnt - bio->bi_idx) * sizeof(struct bio_vec));
252 bio->bi_vcnt -= bio->bi_idx;
253 bio->bi_idx = 0;
255 /* Make sure vcnt and last bv are not too big */
256 bio_for_each_segment(bvec, bio, i) {
257 if (sofar + bvec->bv_len > size)
258 bvec->bv_len = size - sofar;
259 if (bvec->bv_len == 0) {
260 bio->bi_vcnt = i;
261 break;
263 sofar += bvec->bv_len;
266 EXPORT_SYMBOL_GPL(md_trim_bio);
269 * We have a system wide 'event count' that is incremented
270 * on any 'interesting' event, and readers of /proc/mdstat
271 * can use 'poll' or 'select' to find out when the event
272 * count increases.
274 * Events are:
275 * start array, stop array, error, add device, remove device,
276 * start build, activate spare
278 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
279 static atomic_t md_event_count;
280 void md_new_event(mddev_t *mddev)
282 atomic_inc(&md_event_count);
283 wake_up(&md_event_waiters);
285 EXPORT_SYMBOL_GPL(md_new_event);
287 /* Alternate version that can be called from interrupts
288 * when calling sysfs_notify isn't needed.
290 static void md_new_event_inintr(mddev_t *mddev)
292 atomic_inc(&md_event_count);
293 wake_up(&md_event_waiters);
297 * Enables to iterate over all existing md arrays
298 * all_mddevs_lock protects this list.
300 static LIST_HEAD(all_mddevs);
301 static DEFINE_SPINLOCK(all_mddevs_lock);
305 * iterates through all used mddevs in the system.
306 * We take care to grab the all_mddevs_lock whenever navigating
307 * the list, and to always hold a refcount when unlocked.
308 * Any code which breaks out of this loop while own
309 * a reference to the current mddev and must mddev_put it.
311 #define for_each_mddev(mddev,tmp) \
313 for (({ spin_lock(&all_mddevs_lock); \
314 tmp = all_mddevs.next; \
315 mddev = NULL;}); \
316 ({ if (tmp != &all_mddevs) \
317 mddev_get(list_entry(tmp, mddev_t, all_mddevs));\
318 spin_unlock(&all_mddevs_lock); \
319 if (mddev) mddev_put(mddev); \
320 mddev = list_entry(tmp, mddev_t, all_mddevs); \
321 tmp != &all_mddevs;}); \
322 ({ spin_lock(&all_mddevs_lock); \
323 tmp = tmp->next;}) \
327 /* Rather than calling directly into the personality make_request function,
328 * IO requests come here first so that we can check if the device is
329 * being suspended pending a reconfiguration.
330 * We hold a refcount over the call to ->make_request. By the time that
331 * call has finished, the bio has been linked into some internal structure
332 * and so is visible to ->quiesce(), so we don't need the refcount any more.
334 static int md_make_request(struct request_queue *q, struct bio *bio)
336 const int rw = bio_data_dir(bio);
337 mddev_t *mddev = q->queuedata;
338 int rv;
339 int cpu;
340 unsigned int sectors;
342 if (mddev == NULL || mddev->pers == NULL
343 || !mddev->ready) {
344 bio_io_error(bio);
345 return 0;
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 rv = 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);
380 return rv;
383 /* mddev_suspend makes sure no new requests are submitted
384 * to the device, and that any requests that have been submitted
385 * are completely handled.
386 * Once ->stop is called and completes, the module will be completely
387 * unused.
389 void mddev_suspend(mddev_t *mddev)
391 BUG_ON(mddev->suspended);
392 mddev->suspended = 1;
393 synchronize_rcu();
394 wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
395 mddev->pers->quiesce(mddev, 1);
397 EXPORT_SYMBOL_GPL(mddev_suspend);
399 void mddev_resume(mddev_t *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(mddev_t *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 mdk_rdev_t *rdev = bio->bi_private;
423 mddev_t *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 mddev_t *mddev = container_of(ws, mddev_t, flush_work);
439 mdk_rdev_t *rdev;
441 INIT_WORK(&mddev->flush_work, md_submit_flush_data);
442 atomic_set(&mddev->flush_pending, 1);
443 rcu_read_lock();
444 list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
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_KERNEL, 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 mddev_t *mddev = container_of(ws, mddev_t, 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 if (mddev->pers->make_request(mddev, bio))
480 generic_make_request(bio);
483 mddev->flush_bio = NULL;
484 wake_up(&mddev->sb_wait);
487 void md_flush_request(mddev_t *mddev, struct bio *bio)
489 spin_lock_irq(&mddev->write_lock);
490 wait_event_lock_irq(mddev->sb_wait,
491 !mddev->flush_bio,
492 mddev->write_lock, /*nothing*/);
493 mddev->flush_bio = bio;
494 spin_unlock_irq(&mddev->write_lock);
496 INIT_WORK(&mddev->flush_work, submit_flushes);
497 queue_work(md_wq, &mddev->flush_work);
499 EXPORT_SYMBOL(md_flush_request);
501 /* Support for plugging.
502 * This mirrors the plugging support in request_queue, but does not
503 * require having a whole queue or request structures.
504 * We allocate an md_plug_cb for each md device and each thread it gets
505 * plugged on. This links tot the private plug_handle structure in the
506 * personality data where we keep a count of the number of outstanding
507 * plugs so other code can see if a plug is active.
509 struct md_plug_cb {
510 struct blk_plug_cb cb;
511 mddev_t *mddev;
514 static void plugger_unplug(struct blk_plug_cb *cb)
516 struct md_plug_cb *mdcb = container_of(cb, struct md_plug_cb, cb);
517 if (atomic_dec_and_test(&mdcb->mddev->plug_cnt))
518 md_wakeup_thread(mdcb->mddev->thread);
519 kfree(mdcb);
522 /* Check that an unplug wakeup will come shortly.
523 * If not, wakeup the md thread immediately
525 int mddev_check_plugged(mddev_t *mddev)
527 struct blk_plug *plug = current->plug;
528 struct md_plug_cb *mdcb;
530 if (!plug)
531 return 0;
533 list_for_each_entry(mdcb, &plug->cb_list, cb.list) {
534 if (mdcb->cb.callback == plugger_unplug &&
535 mdcb->mddev == mddev) {
536 /* Already on the list, move to top */
537 if (mdcb != list_first_entry(&plug->cb_list,
538 struct md_plug_cb,
539 cb.list))
540 list_move(&mdcb->cb.list, &plug->cb_list);
541 return 1;
544 /* Not currently on the callback list */
545 mdcb = kmalloc(sizeof(*mdcb), GFP_ATOMIC);
546 if (!mdcb)
547 return 0;
549 mdcb->mddev = mddev;
550 mdcb->cb.callback = plugger_unplug;
551 atomic_inc(&mddev->plug_cnt);
552 list_add(&mdcb->cb.list, &plug->cb_list);
553 return 1;
555 EXPORT_SYMBOL_GPL(mddev_check_plugged);
557 static inline mddev_t *mddev_get(mddev_t *mddev)
559 atomic_inc(&mddev->active);
560 return mddev;
563 static void mddev_delayed_delete(struct work_struct *ws);
565 static void mddev_put(mddev_t *mddev)
567 struct bio_set *bs = NULL;
569 if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
570 return;
571 if (!mddev->raid_disks && list_empty(&mddev->disks) &&
572 mddev->ctime == 0 && !mddev->hold_active) {
573 /* Array is not configured at all, and not held active,
574 * so destroy it */
575 list_del(&mddev->all_mddevs);
576 bs = mddev->bio_set;
577 mddev->bio_set = NULL;
578 if (mddev->gendisk) {
579 /* We did a probe so need to clean up. Call
580 * queue_work inside the spinlock so that
581 * flush_workqueue() after mddev_find will
582 * succeed in waiting for the work to be done.
584 INIT_WORK(&mddev->del_work, mddev_delayed_delete);
585 queue_work(md_misc_wq, &mddev->del_work);
586 } else
587 kfree(mddev);
589 spin_unlock(&all_mddevs_lock);
590 if (bs)
591 bioset_free(bs);
594 void mddev_init(mddev_t *mddev)
596 mutex_init(&mddev->open_mutex);
597 mutex_init(&mddev->reconfig_mutex);
598 mutex_init(&mddev->bitmap_info.mutex);
599 INIT_LIST_HEAD(&mddev->disks);
600 INIT_LIST_HEAD(&mddev->all_mddevs);
601 init_timer(&mddev->safemode_timer);
602 atomic_set(&mddev->active, 1);
603 atomic_set(&mddev->openers, 0);
604 atomic_set(&mddev->active_io, 0);
605 atomic_set(&mddev->plug_cnt, 0);
606 spin_lock_init(&mddev->write_lock);
607 atomic_set(&mddev->flush_pending, 0);
608 init_waitqueue_head(&mddev->sb_wait);
609 init_waitqueue_head(&mddev->recovery_wait);
610 mddev->reshape_position = MaxSector;
611 mddev->resync_min = 0;
612 mddev->resync_max = MaxSector;
613 mddev->level = LEVEL_NONE;
615 EXPORT_SYMBOL_GPL(mddev_init);
617 static mddev_t * mddev_find(dev_t unit)
619 mddev_t *mddev, *new = NULL;
621 if (unit && MAJOR(unit) != MD_MAJOR)
622 unit &= ~((1<<MdpMinorShift)-1);
624 retry:
625 spin_lock(&all_mddevs_lock);
627 if (unit) {
628 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
629 if (mddev->unit == unit) {
630 mddev_get(mddev);
631 spin_unlock(&all_mddevs_lock);
632 kfree(new);
633 return mddev;
636 if (new) {
637 list_add(&new->all_mddevs, &all_mddevs);
638 spin_unlock(&all_mddevs_lock);
639 new->hold_active = UNTIL_IOCTL;
640 return new;
642 } else if (new) {
643 /* find an unused unit number */
644 static int next_minor = 512;
645 int start = next_minor;
646 int is_free = 0;
647 int dev = 0;
648 while (!is_free) {
649 dev = MKDEV(MD_MAJOR, next_minor);
650 next_minor++;
651 if (next_minor > MINORMASK)
652 next_minor = 0;
653 if (next_minor == start) {
654 /* Oh dear, all in use. */
655 spin_unlock(&all_mddevs_lock);
656 kfree(new);
657 return NULL;
660 is_free = 1;
661 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
662 if (mddev->unit == dev) {
663 is_free = 0;
664 break;
667 new->unit = dev;
668 new->md_minor = MINOR(dev);
669 new->hold_active = UNTIL_STOP;
670 list_add(&new->all_mddevs, &all_mddevs);
671 spin_unlock(&all_mddevs_lock);
672 return new;
674 spin_unlock(&all_mddevs_lock);
676 new = kzalloc(sizeof(*new), GFP_KERNEL);
677 if (!new)
678 return NULL;
680 new->unit = unit;
681 if (MAJOR(unit) == MD_MAJOR)
682 new->md_minor = MINOR(unit);
683 else
684 new->md_minor = MINOR(unit) >> MdpMinorShift;
686 mddev_init(new);
688 goto retry;
691 static inline int mddev_lock(mddev_t * mddev)
693 return mutex_lock_interruptible(&mddev->reconfig_mutex);
696 static inline int mddev_is_locked(mddev_t *mddev)
698 return mutex_is_locked(&mddev->reconfig_mutex);
701 static inline int mddev_trylock(mddev_t * mddev)
703 return mutex_trylock(&mddev->reconfig_mutex);
706 static struct attribute_group md_redundancy_group;
708 static void mddev_unlock(mddev_t * mddev)
710 if (mddev->to_remove) {
711 /* These cannot be removed under reconfig_mutex as
712 * an access to the files will try to take reconfig_mutex
713 * while holding the file unremovable, which leads to
714 * a deadlock.
715 * So hold set sysfs_active while the remove in happeing,
716 * and anything else which might set ->to_remove or my
717 * otherwise change the sysfs namespace will fail with
718 * -EBUSY if sysfs_active is still set.
719 * We set sysfs_active under reconfig_mutex and elsewhere
720 * test it under the same mutex to ensure its correct value
721 * is seen.
723 struct attribute_group *to_remove = mddev->to_remove;
724 mddev->to_remove = NULL;
725 mddev->sysfs_active = 1;
726 mutex_unlock(&mddev->reconfig_mutex);
728 if (mddev->kobj.sd) {
729 if (to_remove != &md_redundancy_group)
730 sysfs_remove_group(&mddev->kobj, to_remove);
731 if (mddev->pers == NULL ||
732 mddev->pers->sync_request == NULL) {
733 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
734 if (mddev->sysfs_action)
735 sysfs_put(mddev->sysfs_action);
736 mddev->sysfs_action = NULL;
739 mddev->sysfs_active = 0;
740 } else
741 mutex_unlock(&mddev->reconfig_mutex);
743 md_wakeup_thread(mddev->thread);
746 static mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
748 mdk_rdev_t *rdev;
750 list_for_each_entry(rdev, &mddev->disks, same_set)
751 if (rdev->desc_nr == nr)
752 return rdev;
754 return NULL;
757 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
759 mdk_rdev_t *rdev;
761 list_for_each_entry(rdev, &mddev->disks, same_set)
762 if (rdev->bdev->bd_dev == dev)
763 return rdev;
765 return NULL;
768 static struct mdk_personality *find_pers(int level, char *clevel)
770 struct mdk_personality *pers;
771 list_for_each_entry(pers, &pers_list, list) {
772 if (level != LEVEL_NONE && pers->level == level)
773 return pers;
774 if (strcmp(pers->name, clevel)==0)
775 return pers;
777 return NULL;
780 /* return the offset of the super block in 512byte sectors */
781 static inline sector_t calc_dev_sboffset(mdk_rdev_t *rdev)
783 sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
784 return MD_NEW_SIZE_SECTORS(num_sectors);
787 static int alloc_disk_sb(mdk_rdev_t * rdev)
789 if (rdev->sb_page)
790 MD_BUG();
792 rdev->sb_page = alloc_page(GFP_KERNEL);
793 if (!rdev->sb_page) {
794 printk(KERN_ALERT "md: out of memory.\n");
795 return -ENOMEM;
798 return 0;
801 static void free_disk_sb(mdk_rdev_t * rdev)
803 if (rdev->sb_page) {
804 put_page(rdev->sb_page);
805 rdev->sb_loaded = 0;
806 rdev->sb_page = NULL;
807 rdev->sb_start = 0;
808 rdev->sectors = 0;
810 if (rdev->bb_page) {
811 put_page(rdev->bb_page);
812 rdev->bb_page = NULL;
817 static void super_written(struct bio *bio, int error)
819 mdk_rdev_t *rdev = bio->bi_private;
820 mddev_t *mddev = rdev->mddev;
822 if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
823 printk("md: super_written gets error=%d, uptodate=%d\n",
824 error, test_bit(BIO_UPTODATE, &bio->bi_flags));
825 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
826 md_error(mddev, rdev);
829 if (atomic_dec_and_test(&mddev->pending_writes))
830 wake_up(&mddev->sb_wait);
831 bio_put(bio);
834 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
835 sector_t sector, int size, struct page *page)
837 /* write first size bytes of page to sector of rdev
838 * Increment mddev->pending_writes before returning
839 * and decrement it on completion, waking up sb_wait
840 * if zero is reached.
841 * If an error occurred, call md_error
843 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
845 bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
846 bio->bi_sector = sector;
847 bio_add_page(bio, page, size, 0);
848 bio->bi_private = rdev;
849 bio->bi_end_io = super_written;
851 atomic_inc(&mddev->pending_writes);
852 submit_bio(WRITE_FLUSH_FUA, bio);
855 void md_super_wait(mddev_t *mddev)
857 /* wait for all superblock writes that were scheduled to complete */
858 DEFINE_WAIT(wq);
859 for(;;) {
860 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
861 if (atomic_read(&mddev->pending_writes)==0)
862 break;
863 schedule();
865 finish_wait(&mddev->sb_wait, &wq);
868 static void bi_complete(struct bio *bio, int error)
870 complete((struct completion*)bio->bi_private);
873 int sync_page_io(mdk_rdev_t *rdev, sector_t sector, int size,
874 struct page *page, int rw, bool metadata_op)
876 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
877 struct completion event;
878 int ret;
880 rw |= REQ_SYNC;
882 bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
883 rdev->meta_bdev : rdev->bdev;
884 if (metadata_op)
885 bio->bi_sector = sector + rdev->sb_start;
886 else
887 bio->bi_sector = sector + rdev->data_offset;
888 bio_add_page(bio, page, size, 0);
889 init_completion(&event);
890 bio->bi_private = &event;
891 bio->bi_end_io = bi_complete;
892 submit_bio(rw, bio);
893 wait_for_completion(&event);
895 ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
896 bio_put(bio);
897 return ret;
899 EXPORT_SYMBOL_GPL(sync_page_io);
901 static int read_disk_sb(mdk_rdev_t * rdev, int size)
903 char b[BDEVNAME_SIZE];
904 if (!rdev->sb_page) {
905 MD_BUG();
906 return -EINVAL;
908 if (rdev->sb_loaded)
909 return 0;
912 if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
913 goto fail;
914 rdev->sb_loaded = 1;
915 return 0;
917 fail:
918 printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
919 bdevname(rdev->bdev,b));
920 return -EINVAL;
923 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
925 return sb1->set_uuid0 == sb2->set_uuid0 &&
926 sb1->set_uuid1 == sb2->set_uuid1 &&
927 sb1->set_uuid2 == sb2->set_uuid2 &&
928 sb1->set_uuid3 == sb2->set_uuid3;
931 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
933 int ret;
934 mdp_super_t *tmp1, *tmp2;
936 tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
937 tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
939 if (!tmp1 || !tmp2) {
940 ret = 0;
941 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
942 goto abort;
945 *tmp1 = *sb1;
946 *tmp2 = *sb2;
949 * nr_disks is not constant
951 tmp1->nr_disks = 0;
952 tmp2->nr_disks = 0;
954 ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
955 abort:
956 kfree(tmp1);
957 kfree(tmp2);
958 return ret;
962 static u32 md_csum_fold(u32 csum)
964 csum = (csum & 0xffff) + (csum >> 16);
965 return (csum & 0xffff) + (csum >> 16);
968 static unsigned int calc_sb_csum(mdp_super_t * sb)
970 u64 newcsum = 0;
971 u32 *sb32 = (u32*)sb;
972 int i;
973 unsigned int disk_csum, csum;
975 disk_csum = sb->sb_csum;
976 sb->sb_csum = 0;
978 for (i = 0; i < MD_SB_BYTES/4 ; i++)
979 newcsum += sb32[i];
980 csum = (newcsum & 0xffffffff) + (newcsum>>32);
983 #ifdef CONFIG_ALPHA
984 /* This used to use csum_partial, which was wrong for several
985 * reasons including that different results are returned on
986 * different architectures. It isn't critical that we get exactly
987 * the same return value as before (we always csum_fold before
988 * testing, and that removes any differences). However as we
989 * know that csum_partial always returned a 16bit value on
990 * alphas, do a fold to maximise conformity to previous behaviour.
992 sb->sb_csum = md_csum_fold(disk_csum);
993 #else
994 sb->sb_csum = disk_csum;
995 #endif
996 return csum;
1001 * Handle superblock details.
1002 * We want to be able to handle multiple superblock formats
1003 * so we have a common interface to them all, and an array of
1004 * different handlers.
1005 * We rely on user-space to write the initial superblock, and support
1006 * reading and updating of superblocks.
1007 * Interface methods are:
1008 * int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
1009 * loads and validates a superblock on dev.
1010 * if refdev != NULL, compare superblocks on both devices
1011 * Return:
1012 * 0 - dev has a superblock that is compatible with refdev
1013 * 1 - dev has a superblock that is compatible and newer than refdev
1014 * so dev should be used as the refdev in future
1015 * -EINVAL superblock incompatible or invalid
1016 * -othererror e.g. -EIO
1018 * int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
1019 * Verify that dev is acceptable into mddev.
1020 * The first time, mddev->raid_disks will be 0, and data from
1021 * dev should be merged in. Subsequent calls check that dev
1022 * is new enough. Return 0 or -EINVAL
1024 * void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
1025 * Update the superblock for rdev with data in mddev
1026 * This does not write to disc.
1030 struct super_type {
1031 char *name;
1032 struct module *owner;
1033 int (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev,
1034 int minor_version);
1035 int (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
1036 void (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
1037 unsigned long long (*rdev_size_change)(mdk_rdev_t *rdev,
1038 sector_t num_sectors);
1042 * Check that the given mddev has no bitmap.
1044 * This function is called from the run method of all personalities that do not
1045 * support bitmaps. It prints an error message and returns non-zero if mddev
1046 * has a bitmap. Otherwise, it returns 0.
1049 int md_check_no_bitmap(mddev_t *mddev)
1051 if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1052 return 0;
1053 printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
1054 mdname(mddev), mddev->pers->name);
1055 return 1;
1057 EXPORT_SYMBOL(md_check_no_bitmap);
1060 * load_super for 0.90.0
1062 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1064 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1065 mdp_super_t *sb;
1066 int ret;
1069 * Calculate the position of the superblock (512byte sectors),
1070 * it's at the end of the disk.
1072 * It also happens to be a multiple of 4Kb.
1074 rdev->sb_start = calc_dev_sboffset(rdev);
1076 ret = read_disk_sb(rdev, MD_SB_BYTES);
1077 if (ret) return ret;
1079 ret = -EINVAL;
1081 bdevname(rdev->bdev, b);
1082 sb = page_address(rdev->sb_page);
1084 if (sb->md_magic != MD_SB_MAGIC) {
1085 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
1087 goto abort;
1090 if (sb->major_version != 0 ||
1091 sb->minor_version < 90 ||
1092 sb->minor_version > 91) {
1093 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
1094 sb->major_version, sb->minor_version,
1096 goto abort;
1099 if (sb->raid_disks <= 0)
1100 goto abort;
1102 if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1103 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1105 goto abort;
1108 rdev->preferred_minor = sb->md_minor;
1109 rdev->data_offset = 0;
1110 rdev->sb_size = MD_SB_BYTES;
1111 rdev->badblocks.shift = -1;
1113 if (sb->level == LEVEL_MULTIPATH)
1114 rdev->desc_nr = -1;
1115 else
1116 rdev->desc_nr = sb->this_disk.number;
1118 if (!refdev) {
1119 ret = 1;
1120 } else {
1121 __u64 ev1, ev2;
1122 mdp_super_t *refsb = page_address(refdev->sb_page);
1123 if (!uuid_equal(refsb, sb)) {
1124 printk(KERN_WARNING "md: %s has different UUID to %s\n",
1125 b, bdevname(refdev->bdev,b2));
1126 goto abort;
1128 if (!sb_equal(refsb, sb)) {
1129 printk(KERN_WARNING "md: %s has same UUID"
1130 " but different superblock to %s\n",
1131 b, bdevname(refdev->bdev, b2));
1132 goto abort;
1134 ev1 = md_event(sb);
1135 ev2 = md_event(refsb);
1136 if (ev1 > ev2)
1137 ret = 1;
1138 else
1139 ret = 0;
1141 rdev->sectors = rdev->sb_start;
1143 if (rdev->sectors < sb->size * 2 && sb->level > 1)
1144 /* "this cannot possibly happen" ... */
1145 ret = -EINVAL;
1147 abort:
1148 return ret;
1152 * validate_super for 0.90.0
1154 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1156 mdp_disk_t *desc;
1157 mdp_super_t *sb = page_address(rdev->sb_page);
1158 __u64 ev1 = md_event(sb);
1160 rdev->raid_disk = -1;
1161 clear_bit(Faulty, &rdev->flags);
1162 clear_bit(In_sync, &rdev->flags);
1163 clear_bit(WriteMostly, &rdev->flags);
1165 if (mddev->raid_disks == 0) {
1166 mddev->major_version = 0;
1167 mddev->minor_version = sb->minor_version;
1168 mddev->patch_version = sb->patch_version;
1169 mddev->external = 0;
1170 mddev->chunk_sectors = sb->chunk_size >> 9;
1171 mddev->ctime = sb->ctime;
1172 mddev->utime = sb->utime;
1173 mddev->level = sb->level;
1174 mddev->clevel[0] = 0;
1175 mddev->layout = sb->layout;
1176 mddev->raid_disks = sb->raid_disks;
1177 mddev->dev_sectors = sb->size * 2;
1178 mddev->events = ev1;
1179 mddev->bitmap_info.offset = 0;
1180 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1182 if (mddev->minor_version >= 91) {
1183 mddev->reshape_position = sb->reshape_position;
1184 mddev->delta_disks = sb->delta_disks;
1185 mddev->new_level = sb->new_level;
1186 mddev->new_layout = sb->new_layout;
1187 mddev->new_chunk_sectors = sb->new_chunk >> 9;
1188 } else {
1189 mddev->reshape_position = MaxSector;
1190 mddev->delta_disks = 0;
1191 mddev->new_level = mddev->level;
1192 mddev->new_layout = mddev->layout;
1193 mddev->new_chunk_sectors = mddev->chunk_sectors;
1196 if (sb->state & (1<<MD_SB_CLEAN))
1197 mddev->recovery_cp = MaxSector;
1198 else {
1199 if (sb->events_hi == sb->cp_events_hi &&
1200 sb->events_lo == sb->cp_events_lo) {
1201 mddev->recovery_cp = sb->recovery_cp;
1202 } else
1203 mddev->recovery_cp = 0;
1206 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1207 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1208 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1209 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1211 mddev->max_disks = MD_SB_DISKS;
1213 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1214 mddev->bitmap_info.file == NULL)
1215 mddev->bitmap_info.offset =
1216 mddev->bitmap_info.default_offset;
1218 } else if (mddev->pers == NULL) {
1219 /* Insist on good event counter while assembling, except
1220 * for spares (which don't need an event count) */
1221 ++ev1;
1222 if (sb->disks[rdev->desc_nr].state & (
1223 (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1224 if (ev1 < mddev->events)
1225 return -EINVAL;
1226 } else if (mddev->bitmap) {
1227 /* if adding to array with a bitmap, then we can accept an
1228 * older device ... but not too old.
1230 if (ev1 < mddev->bitmap->events_cleared)
1231 return 0;
1232 } else {
1233 if (ev1 < mddev->events)
1234 /* just a hot-add of a new device, leave raid_disk at -1 */
1235 return 0;
1238 if (mddev->level != LEVEL_MULTIPATH) {
1239 desc = sb->disks + rdev->desc_nr;
1241 if (desc->state & (1<<MD_DISK_FAULTY))
1242 set_bit(Faulty, &rdev->flags);
1243 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1244 desc->raid_disk < mddev->raid_disks */) {
1245 set_bit(In_sync, &rdev->flags);
1246 rdev->raid_disk = desc->raid_disk;
1247 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1248 /* active but not in sync implies recovery up to
1249 * reshape position. We don't know exactly where
1250 * that is, so set to zero for now */
1251 if (mddev->minor_version >= 91) {
1252 rdev->recovery_offset = 0;
1253 rdev->raid_disk = desc->raid_disk;
1256 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1257 set_bit(WriteMostly, &rdev->flags);
1258 } else /* MULTIPATH are always insync */
1259 set_bit(In_sync, &rdev->flags);
1260 return 0;
1264 * sync_super for 0.90.0
1266 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1268 mdp_super_t *sb;
1269 mdk_rdev_t *rdev2;
1270 int next_spare = mddev->raid_disks;
1273 /* make rdev->sb match mddev data..
1275 * 1/ zero out disks
1276 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1277 * 3/ any empty disks < next_spare become removed
1279 * disks[0] gets initialised to REMOVED because
1280 * we cannot be sure from other fields if it has
1281 * been initialised or not.
1283 int i;
1284 int active=0, working=0,failed=0,spare=0,nr_disks=0;
1286 rdev->sb_size = MD_SB_BYTES;
1288 sb = page_address(rdev->sb_page);
1290 memset(sb, 0, sizeof(*sb));
1292 sb->md_magic = MD_SB_MAGIC;
1293 sb->major_version = mddev->major_version;
1294 sb->patch_version = mddev->patch_version;
1295 sb->gvalid_words = 0; /* ignored */
1296 memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1297 memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1298 memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1299 memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1301 sb->ctime = mddev->ctime;
1302 sb->level = mddev->level;
1303 sb->size = mddev->dev_sectors / 2;
1304 sb->raid_disks = mddev->raid_disks;
1305 sb->md_minor = mddev->md_minor;
1306 sb->not_persistent = 0;
1307 sb->utime = mddev->utime;
1308 sb->state = 0;
1309 sb->events_hi = (mddev->events>>32);
1310 sb->events_lo = (u32)mddev->events;
1312 if (mddev->reshape_position == MaxSector)
1313 sb->minor_version = 90;
1314 else {
1315 sb->minor_version = 91;
1316 sb->reshape_position = mddev->reshape_position;
1317 sb->new_level = mddev->new_level;
1318 sb->delta_disks = mddev->delta_disks;
1319 sb->new_layout = mddev->new_layout;
1320 sb->new_chunk = mddev->new_chunk_sectors << 9;
1322 mddev->minor_version = sb->minor_version;
1323 if (mddev->in_sync)
1325 sb->recovery_cp = mddev->recovery_cp;
1326 sb->cp_events_hi = (mddev->events>>32);
1327 sb->cp_events_lo = (u32)mddev->events;
1328 if (mddev->recovery_cp == MaxSector)
1329 sb->state = (1<< MD_SB_CLEAN);
1330 } else
1331 sb->recovery_cp = 0;
1333 sb->layout = mddev->layout;
1334 sb->chunk_size = mddev->chunk_sectors << 9;
1336 if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1337 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1339 sb->disks[0].state = (1<<MD_DISK_REMOVED);
1340 list_for_each_entry(rdev2, &mddev->disks, same_set) {
1341 mdp_disk_t *d;
1342 int desc_nr;
1343 int is_active = test_bit(In_sync, &rdev2->flags);
1345 if (rdev2->raid_disk >= 0 &&
1346 sb->minor_version >= 91)
1347 /* we have nowhere to store the recovery_offset,
1348 * but if it is not below the reshape_position,
1349 * we can piggy-back on that.
1351 is_active = 1;
1352 if (rdev2->raid_disk < 0 ||
1353 test_bit(Faulty, &rdev2->flags))
1354 is_active = 0;
1355 if (is_active)
1356 desc_nr = rdev2->raid_disk;
1357 else
1358 desc_nr = next_spare++;
1359 rdev2->desc_nr = desc_nr;
1360 d = &sb->disks[rdev2->desc_nr];
1361 nr_disks++;
1362 d->number = rdev2->desc_nr;
1363 d->major = MAJOR(rdev2->bdev->bd_dev);
1364 d->minor = MINOR(rdev2->bdev->bd_dev);
1365 if (is_active)
1366 d->raid_disk = rdev2->raid_disk;
1367 else
1368 d->raid_disk = rdev2->desc_nr; /* compatibility */
1369 if (test_bit(Faulty, &rdev2->flags))
1370 d->state = (1<<MD_DISK_FAULTY);
1371 else if (is_active) {
1372 d->state = (1<<MD_DISK_ACTIVE);
1373 if (test_bit(In_sync, &rdev2->flags))
1374 d->state |= (1<<MD_DISK_SYNC);
1375 active++;
1376 working++;
1377 } else {
1378 d->state = 0;
1379 spare++;
1380 working++;
1382 if (test_bit(WriteMostly, &rdev2->flags))
1383 d->state |= (1<<MD_DISK_WRITEMOSTLY);
1385 /* now set the "removed" and "faulty" bits on any missing devices */
1386 for (i=0 ; i < mddev->raid_disks ; i++) {
1387 mdp_disk_t *d = &sb->disks[i];
1388 if (d->state == 0 && d->number == 0) {
1389 d->number = i;
1390 d->raid_disk = i;
1391 d->state = (1<<MD_DISK_REMOVED);
1392 d->state |= (1<<MD_DISK_FAULTY);
1393 failed++;
1396 sb->nr_disks = nr_disks;
1397 sb->active_disks = active;
1398 sb->working_disks = working;
1399 sb->failed_disks = failed;
1400 sb->spare_disks = spare;
1402 sb->this_disk = sb->disks[rdev->desc_nr];
1403 sb->sb_csum = calc_sb_csum(sb);
1407 * rdev_size_change for 0.90.0
1409 static unsigned long long
1410 super_90_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1412 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1413 return 0; /* component must fit device */
1414 if (rdev->mddev->bitmap_info.offset)
1415 return 0; /* can't move bitmap */
1416 rdev->sb_start = calc_dev_sboffset(rdev);
1417 if (!num_sectors || num_sectors > rdev->sb_start)
1418 num_sectors = rdev->sb_start;
1419 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1420 rdev->sb_page);
1421 md_super_wait(rdev->mddev);
1422 return num_sectors;
1427 * version 1 superblock
1430 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1432 __le32 disk_csum;
1433 u32 csum;
1434 unsigned long long newcsum;
1435 int size = 256 + le32_to_cpu(sb->max_dev)*2;
1436 __le32 *isuper = (__le32*)sb;
1437 int i;
1439 disk_csum = sb->sb_csum;
1440 sb->sb_csum = 0;
1441 newcsum = 0;
1442 for (i=0; size>=4; size -= 4 )
1443 newcsum += le32_to_cpu(*isuper++);
1445 if (size == 2)
1446 newcsum += le16_to_cpu(*(__le16*) isuper);
1448 csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1449 sb->sb_csum = disk_csum;
1450 return cpu_to_le32(csum);
1453 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
1454 int acknowledged);
1455 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1457 struct mdp_superblock_1 *sb;
1458 int ret;
1459 sector_t sb_start;
1460 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1461 int bmask;
1464 * Calculate the position of the superblock in 512byte sectors.
1465 * It is always aligned to a 4K boundary and
1466 * depeding on minor_version, it can be:
1467 * 0: At least 8K, but less than 12K, from end of device
1468 * 1: At start of device
1469 * 2: 4K from start of device.
1471 switch(minor_version) {
1472 case 0:
1473 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1474 sb_start -= 8*2;
1475 sb_start &= ~(sector_t)(4*2-1);
1476 break;
1477 case 1:
1478 sb_start = 0;
1479 break;
1480 case 2:
1481 sb_start = 8;
1482 break;
1483 default:
1484 return -EINVAL;
1486 rdev->sb_start = sb_start;
1488 /* superblock is rarely larger than 1K, but it can be larger,
1489 * and it is safe to read 4k, so we do that
1491 ret = read_disk_sb(rdev, 4096);
1492 if (ret) return ret;
1495 sb = page_address(rdev->sb_page);
1497 if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1498 sb->major_version != cpu_to_le32(1) ||
1499 le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1500 le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1501 (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1502 return -EINVAL;
1504 if (calc_sb_1_csum(sb) != sb->sb_csum) {
1505 printk("md: invalid superblock checksum on %s\n",
1506 bdevname(rdev->bdev,b));
1507 return -EINVAL;
1509 if (le64_to_cpu(sb->data_size) < 10) {
1510 printk("md: data_size too small on %s\n",
1511 bdevname(rdev->bdev,b));
1512 return -EINVAL;
1515 rdev->preferred_minor = 0xffff;
1516 rdev->data_offset = le64_to_cpu(sb->data_offset);
1517 atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1519 rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1520 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1521 if (rdev->sb_size & bmask)
1522 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1524 if (minor_version
1525 && rdev->data_offset < sb_start + (rdev->sb_size/512))
1526 return -EINVAL;
1528 if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1529 rdev->desc_nr = -1;
1530 else
1531 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1533 if (!rdev->bb_page) {
1534 rdev->bb_page = alloc_page(GFP_KERNEL);
1535 if (!rdev->bb_page)
1536 return -ENOMEM;
1538 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1539 rdev->badblocks.count == 0) {
1540 /* need to load the bad block list.
1541 * Currently we limit it to one page.
1543 s32 offset;
1544 sector_t bb_sector;
1545 u64 *bbp;
1546 int i;
1547 int sectors = le16_to_cpu(sb->bblog_size);
1548 if (sectors > (PAGE_SIZE / 512))
1549 return -EINVAL;
1550 offset = le32_to_cpu(sb->bblog_offset);
1551 if (offset == 0)
1552 return -EINVAL;
1553 bb_sector = (long long)offset;
1554 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1555 rdev->bb_page, READ, true))
1556 return -EIO;
1557 bbp = (u64 *)page_address(rdev->bb_page);
1558 rdev->badblocks.shift = sb->bblog_shift;
1559 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1560 u64 bb = le64_to_cpu(*bbp);
1561 int count = bb & (0x3ff);
1562 u64 sector = bb >> 10;
1563 sector <<= sb->bblog_shift;
1564 count <<= sb->bblog_shift;
1565 if (bb + 1 == 0)
1566 break;
1567 if (md_set_badblocks(&rdev->badblocks,
1568 sector, count, 1) == 0)
1569 return -EINVAL;
1571 } else if (sb->bblog_offset == 0)
1572 rdev->badblocks.shift = -1;
1574 if (!refdev) {
1575 ret = 1;
1576 } else {
1577 __u64 ev1, ev2;
1578 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1580 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1581 sb->level != refsb->level ||
1582 sb->layout != refsb->layout ||
1583 sb->chunksize != refsb->chunksize) {
1584 printk(KERN_WARNING "md: %s has strangely different"
1585 " superblock to %s\n",
1586 bdevname(rdev->bdev,b),
1587 bdevname(refdev->bdev,b2));
1588 return -EINVAL;
1590 ev1 = le64_to_cpu(sb->events);
1591 ev2 = le64_to_cpu(refsb->events);
1593 if (ev1 > ev2)
1594 ret = 1;
1595 else
1596 ret = 0;
1598 if (minor_version)
1599 rdev->sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
1600 le64_to_cpu(sb->data_offset);
1601 else
1602 rdev->sectors = rdev->sb_start;
1603 if (rdev->sectors < le64_to_cpu(sb->data_size))
1604 return -EINVAL;
1605 rdev->sectors = le64_to_cpu(sb->data_size);
1606 if (le64_to_cpu(sb->size) > rdev->sectors)
1607 return -EINVAL;
1608 return ret;
1611 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1613 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1614 __u64 ev1 = le64_to_cpu(sb->events);
1616 rdev->raid_disk = -1;
1617 clear_bit(Faulty, &rdev->flags);
1618 clear_bit(In_sync, &rdev->flags);
1619 clear_bit(WriteMostly, &rdev->flags);
1621 if (mddev->raid_disks == 0) {
1622 mddev->major_version = 1;
1623 mddev->patch_version = 0;
1624 mddev->external = 0;
1625 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1626 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1627 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1628 mddev->level = le32_to_cpu(sb->level);
1629 mddev->clevel[0] = 0;
1630 mddev->layout = le32_to_cpu(sb->layout);
1631 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1632 mddev->dev_sectors = le64_to_cpu(sb->size);
1633 mddev->events = ev1;
1634 mddev->bitmap_info.offset = 0;
1635 mddev->bitmap_info.default_offset = 1024 >> 9;
1637 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1638 memcpy(mddev->uuid, sb->set_uuid, 16);
1640 mddev->max_disks = (4096-256)/2;
1642 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1643 mddev->bitmap_info.file == NULL )
1644 mddev->bitmap_info.offset =
1645 (__s32)le32_to_cpu(sb->bitmap_offset);
1647 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1648 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1649 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1650 mddev->new_level = le32_to_cpu(sb->new_level);
1651 mddev->new_layout = le32_to_cpu(sb->new_layout);
1652 mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1653 } else {
1654 mddev->reshape_position = MaxSector;
1655 mddev->delta_disks = 0;
1656 mddev->new_level = mddev->level;
1657 mddev->new_layout = mddev->layout;
1658 mddev->new_chunk_sectors = mddev->chunk_sectors;
1661 } else if (mddev->pers == NULL) {
1662 /* Insist of good event counter while assembling, except for
1663 * spares (which don't need an event count) */
1664 ++ev1;
1665 if (rdev->desc_nr >= 0 &&
1666 rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1667 le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1668 if (ev1 < mddev->events)
1669 return -EINVAL;
1670 } else if (mddev->bitmap) {
1671 /* If adding to array with a bitmap, then we can accept an
1672 * older device, but not too old.
1674 if (ev1 < mddev->bitmap->events_cleared)
1675 return 0;
1676 } else {
1677 if (ev1 < mddev->events)
1678 /* just a hot-add of a new device, leave raid_disk at -1 */
1679 return 0;
1681 if (mddev->level != LEVEL_MULTIPATH) {
1682 int role;
1683 if (rdev->desc_nr < 0 ||
1684 rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1685 role = 0xffff;
1686 rdev->desc_nr = -1;
1687 } else
1688 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1689 switch(role) {
1690 case 0xffff: /* spare */
1691 break;
1692 case 0xfffe: /* faulty */
1693 set_bit(Faulty, &rdev->flags);
1694 break;
1695 default:
1696 if ((le32_to_cpu(sb->feature_map) &
1697 MD_FEATURE_RECOVERY_OFFSET))
1698 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1699 else
1700 set_bit(In_sync, &rdev->flags);
1701 rdev->raid_disk = role;
1702 break;
1704 if (sb->devflags & WriteMostly1)
1705 set_bit(WriteMostly, &rdev->flags);
1706 } else /* MULTIPATH are always insync */
1707 set_bit(In_sync, &rdev->flags);
1709 return 0;
1712 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1714 struct mdp_superblock_1 *sb;
1715 mdk_rdev_t *rdev2;
1716 int max_dev, i;
1717 /* make rdev->sb match mddev and rdev data. */
1719 sb = page_address(rdev->sb_page);
1721 sb->feature_map = 0;
1722 sb->pad0 = 0;
1723 sb->recovery_offset = cpu_to_le64(0);
1724 memset(sb->pad1, 0, sizeof(sb->pad1));
1725 memset(sb->pad3, 0, sizeof(sb->pad3));
1727 sb->utime = cpu_to_le64((__u64)mddev->utime);
1728 sb->events = cpu_to_le64(mddev->events);
1729 if (mddev->in_sync)
1730 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1731 else
1732 sb->resync_offset = cpu_to_le64(0);
1734 sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1736 sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1737 sb->size = cpu_to_le64(mddev->dev_sectors);
1738 sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1739 sb->level = cpu_to_le32(mddev->level);
1740 sb->layout = cpu_to_le32(mddev->layout);
1742 if (test_bit(WriteMostly, &rdev->flags))
1743 sb->devflags |= WriteMostly1;
1744 else
1745 sb->devflags &= ~WriteMostly1;
1747 if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1748 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1749 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1752 if (rdev->raid_disk >= 0 &&
1753 !test_bit(In_sync, &rdev->flags)) {
1754 sb->feature_map |=
1755 cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1756 sb->recovery_offset =
1757 cpu_to_le64(rdev->recovery_offset);
1760 if (mddev->reshape_position != MaxSector) {
1761 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1762 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1763 sb->new_layout = cpu_to_le32(mddev->new_layout);
1764 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1765 sb->new_level = cpu_to_le32(mddev->new_level);
1766 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1769 if (rdev->badblocks.count == 0)
1770 /* Nothing to do for bad blocks*/ ;
1771 else if (sb->bblog_offset == 0)
1772 /* Cannot record bad blocks on this device */
1773 md_error(mddev, rdev);
1774 else {
1775 struct badblocks *bb = &rdev->badblocks;
1776 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1777 u64 *p = bb->page;
1778 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1779 if (bb->changed) {
1780 unsigned seq;
1782 retry:
1783 seq = read_seqbegin(&bb->lock);
1785 memset(bbp, 0xff, PAGE_SIZE);
1787 for (i = 0 ; i < bb->count ; i++) {
1788 u64 internal_bb = *p++;
1789 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1790 | BB_LEN(internal_bb));
1791 *bbp++ = cpu_to_le64(store_bb);
1793 if (read_seqretry(&bb->lock, seq))
1794 goto retry;
1796 bb->sector = (rdev->sb_start +
1797 (int)le32_to_cpu(sb->bblog_offset));
1798 bb->size = le16_to_cpu(sb->bblog_size);
1799 bb->changed = 0;
1803 max_dev = 0;
1804 list_for_each_entry(rdev2, &mddev->disks, same_set)
1805 if (rdev2->desc_nr+1 > max_dev)
1806 max_dev = rdev2->desc_nr+1;
1808 if (max_dev > le32_to_cpu(sb->max_dev)) {
1809 int bmask;
1810 sb->max_dev = cpu_to_le32(max_dev);
1811 rdev->sb_size = max_dev * 2 + 256;
1812 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1813 if (rdev->sb_size & bmask)
1814 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1815 } else
1816 max_dev = le32_to_cpu(sb->max_dev);
1818 for (i=0; i<max_dev;i++)
1819 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1821 list_for_each_entry(rdev2, &mddev->disks, same_set) {
1822 i = rdev2->desc_nr;
1823 if (test_bit(Faulty, &rdev2->flags))
1824 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1825 else if (test_bit(In_sync, &rdev2->flags))
1826 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1827 else if (rdev2->raid_disk >= 0)
1828 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1829 else
1830 sb->dev_roles[i] = cpu_to_le16(0xffff);
1833 sb->sb_csum = calc_sb_1_csum(sb);
1836 static unsigned long long
1837 super_1_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1839 struct mdp_superblock_1 *sb;
1840 sector_t max_sectors;
1841 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1842 return 0; /* component must fit device */
1843 if (rdev->sb_start < rdev->data_offset) {
1844 /* minor versions 1 and 2; superblock before data */
1845 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1846 max_sectors -= rdev->data_offset;
1847 if (!num_sectors || num_sectors > max_sectors)
1848 num_sectors = max_sectors;
1849 } else if (rdev->mddev->bitmap_info.offset) {
1850 /* minor version 0 with bitmap we can't move */
1851 return 0;
1852 } else {
1853 /* minor version 0; superblock after data */
1854 sector_t sb_start;
1855 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1856 sb_start &= ~(sector_t)(4*2 - 1);
1857 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1858 if (!num_sectors || num_sectors > max_sectors)
1859 num_sectors = max_sectors;
1860 rdev->sb_start = sb_start;
1862 sb = page_address(rdev->sb_page);
1863 sb->data_size = cpu_to_le64(num_sectors);
1864 sb->super_offset = rdev->sb_start;
1865 sb->sb_csum = calc_sb_1_csum(sb);
1866 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1867 rdev->sb_page);
1868 md_super_wait(rdev->mddev);
1869 return num_sectors;
1872 static struct super_type super_types[] = {
1873 [0] = {
1874 .name = "0.90.0",
1875 .owner = THIS_MODULE,
1876 .load_super = super_90_load,
1877 .validate_super = super_90_validate,
1878 .sync_super = super_90_sync,
1879 .rdev_size_change = super_90_rdev_size_change,
1881 [1] = {
1882 .name = "md-1",
1883 .owner = THIS_MODULE,
1884 .load_super = super_1_load,
1885 .validate_super = super_1_validate,
1886 .sync_super = super_1_sync,
1887 .rdev_size_change = super_1_rdev_size_change,
1891 static void sync_super(mddev_t *mddev, mdk_rdev_t *rdev)
1893 if (mddev->sync_super) {
1894 mddev->sync_super(mddev, rdev);
1895 return;
1898 BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
1900 super_types[mddev->major_version].sync_super(mddev, rdev);
1903 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1905 mdk_rdev_t *rdev, *rdev2;
1907 rcu_read_lock();
1908 rdev_for_each_rcu(rdev, mddev1)
1909 rdev_for_each_rcu(rdev2, mddev2)
1910 if (rdev->bdev->bd_contains ==
1911 rdev2->bdev->bd_contains) {
1912 rcu_read_unlock();
1913 return 1;
1915 rcu_read_unlock();
1916 return 0;
1919 static LIST_HEAD(pending_raid_disks);
1922 * Try to register data integrity profile for an mddev
1924 * This is called when an array is started and after a disk has been kicked
1925 * from the array. It only succeeds if all working and active component devices
1926 * are integrity capable with matching profiles.
1928 int md_integrity_register(mddev_t *mddev)
1930 mdk_rdev_t *rdev, *reference = NULL;
1932 if (list_empty(&mddev->disks))
1933 return 0; /* nothing to do */
1934 if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
1935 return 0; /* shouldn't register, or already is */
1936 list_for_each_entry(rdev, &mddev->disks, same_set) {
1937 /* skip spares and non-functional disks */
1938 if (test_bit(Faulty, &rdev->flags))
1939 continue;
1940 if (rdev->raid_disk < 0)
1941 continue;
1942 if (!reference) {
1943 /* Use the first rdev as the reference */
1944 reference = rdev;
1945 continue;
1947 /* does this rdev's profile match the reference profile? */
1948 if (blk_integrity_compare(reference->bdev->bd_disk,
1949 rdev->bdev->bd_disk) < 0)
1950 return -EINVAL;
1952 if (!reference || !bdev_get_integrity(reference->bdev))
1953 return 0;
1955 * All component devices are integrity capable and have matching
1956 * profiles, register the common profile for the md device.
1958 if (blk_integrity_register(mddev->gendisk,
1959 bdev_get_integrity(reference->bdev)) != 0) {
1960 printk(KERN_ERR "md: failed to register integrity for %s\n",
1961 mdname(mddev));
1962 return -EINVAL;
1964 printk(KERN_NOTICE "md: data integrity enabled on %s\n", mdname(mddev));
1965 if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
1966 printk(KERN_ERR "md: failed to create integrity pool for %s\n",
1967 mdname(mddev));
1968 return -EINVAL;
1970 return 0;
1972 EXPORT_SYMBOL(md_integrity_register);
1974 /* Disable data integrity if non-capable/non-matching disk is being added */
1975 void md_integrity_add_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
1977 struct blk_integrity *bi_rdev = bdev_get_integrity(rdev->bdev);
1978 struct blk_integrity *bi_mddev = blk_get_integrity(mddev->gendisk);
1980 if (!bi_mddev) /* nothing to do */
1981 return;
1982 if (rdev->raid_disk < 0) /* skip spares */
1983 return;
1984 if (bi_rdev && blk_integrity_compare(mddev->gendisk,
1985 rdev->bdev->bd_disk) >= 0)
1986 return;
1987 printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
1988 blk_integrity_unregister(mddev->gendisk);
1990 EXPORT_SYMBOL(md_integrity_add_rdev);
1992 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1994 char b[BDEVNAME_SIZE];
1995 struct kobject *ko;
1996 char *s;
1997 int err;
1999 if (rdev->mddev) {
2000 MD_BUG();
2001 return -EINVAL;
2004 /* prevent duplicates */
2005 if (find_rdev(mddev, rdev->bdev->bd_dev))
2006 return -EEXIST;
2008 /* make sure rdev->sectors exceeds mddev->dev_sectors */
2009 if (rdev->sectors && (mddev->dev_sectors == 0 ||
2010 rdev->sectors < mddev->dev_sectors)) {
2011 if (mddev->pers) {
2012 /* Cannot change size, so fail
2013 * If mddev->level <= 0, then we don't care
2014 * about aligning sizes (e.g. linear)
2016 if (mddev->level > 0)
2017 return -ENOSPC;
2018 } else
2019 mddev->dev_sectors = rdev->sectors;
2022 /* Verify rdev->desc_nr is unique.
2023 * If it is -1, assign a free number, else
2024 * check number is not in use
2026 if (rdev->desc_nr < 0) {
2027 int choice = 0;
2028 if (mddev->pers) choice = mddev->raid_disks;
2029 while (find_rdev_nr(mddev, choice))
2030 choice++;
2031 rdev->desc_nr = choice;
2032 } else {
2033 if (find_rdev_nr(mddev, rdev->desc_nr))
2034 return -EBUSY;
2036 if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2037 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
2038 mdname(mddev), mddev->max_disks);
2039 return -EBUSY;
2041 bdevname(rdev->bdev,b);
2042 while ( (s=strchr(b, '/')) != NULL)
2043 *s = '!';
2045 rdev->mddev = mddev;
2046 printk(KERN_INFO "md: bind<%s>\n", b);
2048 if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2049 goto fail;
2051 ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2052 if (sysfs_create_link(&rdev->kobj, ko, "block"))
2053 /* failure here is OK */;
2054 rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2056 list_add_rcu(&rdev->same_set, &mddev->disks);
2057 bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2059 /* May as well allow recovery to be retried once */
2060 mddev->recovery_disabled++;
2062 return 0;
2064 fail:
2065 printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
2066 b, mdname(mddev));
2067 return err;
2070 static void md_delayed_delete(struct work_struct *ws)
2072 mdk_rdev_t *rdev = container_of(ws, mdk_rdev_t, del_work);
2073 kobject_del(&rdev->kobj);
2074 kobject_put(&rdev->kobj);
2077 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
2079 char b[BDEVNAME_SIZE];
2080 if (!rdev->mddev) {
2081 MD_BUG();
2082 return;
2084 bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2085 list_del_rcu(&rdev->same_set);
2086 printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
2087 rdev->mddev = NULL;
2088 sysfs_remove_link(&rdev->kobj, "block");
2089 sysfs_put(rdev->sysfs_state);
2090 rdev->sysfs_state = NULL;
2091 kfree(rdev->badblocks.page);
2092 rdev->badblocks.count = 0;
2093 rdev->badblocks.page = NULL;
2094 /* We need to delay this, otherwise we can deadlock when
2095 * writing to 'remove' to "dev/state". We also need
2096 * to delay it due to rcu usage.
2098 synchronize_rcu();
2099 INIT_WORK(&rdev->del_work, md_delayed_delete);
2100 kobject_get(&rdev->kobj);
2101 queue_work(md_misc_wq, &rdev->del_work);
2105 * prevent the device from being mounted, repartitioned or
2106 * otherwise reused by a RAID array (or any other kernel
2107 * subsystem), by bd_claiming the device.
2109 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev, int shared)
2111 int err = 0;
2112 struct block_device *bdev;
2113 char b[BDEVNAME_SIZE];
2115 bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2116 shared ? (mdk_rdev_t *)lock_rdev : rdev);
2117 if (IS_ERR(bdev)) {
2118 printk(KERN_ERR "md: could not open %s.\n",
2119 __bdevname(dev, b));
2120 return PTR_ERR(bdev);
2122 rdev->bdev = bdev;
2123 return err;
2126 static void unlock_rdev(mdk_rdev_t *rdev)
2128 struct block_device *bdev = rdev->bdev;
2129 rdev->bdev = NULL;
2130 if (!bdev)
2131 MD_BUG();
2132 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2135 void md_autodetect_dev(dev_t dev);
2137 static void export_rdev(mdk_rdev_t * rdev)
2139 char b[BDEVNAME_SIZE];
2140 printk(KERN_INFO "md: export_rdev(%s)\n",
2141 bdevname(rdev->bdev,b));
2142 if (rdev->mddev)
2143 MD_BUG();
2144 free_disk_sb(rdev);
2145 #ifndef MODULE
2146 if (test_bit(AutoDetected, &rdev->flags))
2147 md_autodetect_dev(rdev->bdev->bd_dev);
2148 #endif
2149 unlock_rdev(rdev);
2150 kobject_put(&rdev->kobj);
2153 static void kick_rdev_from_array(mdk_rdev_t * rdev)
2155 unbind_rdev_from_array(rdev);
2156 export_rdev(rdev);
2159 static void export_array(mddev_t *mddev)
2161 mdk_rdev_t *rdev, *tmp;
2163 rdev_for_each(rdev, tmp, mddev) {
2164 if (!rdev->mddev) {
2165 MD_BUG();
2166 continue;
2168 kick_rdev_from_array(rdev);
2170 if (!list_empty(&mddev->disks))
2171 MD_BUG();
2172 mddev->raid_disks = 0;
2173 mddev->major_version = 0;
2176 static void print_desc(mdp_disk_t *desc)
2178 printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
2179 desc->major,desc->minor,desc->raid_disk,desc->state);
2182 static void print_sb_90(mdp_super_t *sb)
2184 int i;
2186 printk(KERN_INFO
2187 "md: SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
2188 sb->major_version, sb->minor_version, sb->patch_version,
2189 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
2190 sb->ctime);
2191 printk(KERN_INFO "md: L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
2192 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
2193 sb->md_minor, sb->layout, sb->chunk_size);
2194 printk(KERN_INFO "md: UT:%08x ST:%d AD:%d WD:%d"
2195 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
2196 sb->utime, sb->state, sb->active_disks, sb->working_disks,
2197 sb->failed_disks, sb->spare_disks,
2198 sb->sb_csum, (unsigned long)sb->events_lo);
2200 printk(KERN_INFO);
2201 for (i = 0; i < MD_SB_DISKS; i++) {
2202 mdp_disk_t *desc;
2204 desc = sb->disks + i;
2205 if (desc->number || desc->major || desc->minor ||
2206 desc->raid_disk || (desc->state && (desc->state != 4))) {
2207 printk(" D %2d: ", i);
2208 print_desc(desc);
2211 printk(KERN_INFO "md: THIS: ");
2212 print_desc(&sb->this_disk);
2215 static void print_sb_1(struct mdp_superblock_1 *sb)
2217 __u8 *uuid;
2219 uuid = sb->set_uuid;
2220 printk(KERN_INFO
2221 "md: SB: (V:%u) (F:0x%08x) Array-ID:<%pU>\n"
2222 "md: Name: \"%s\" CT:%llu\n",
2223 le32_to_cpu(sb->major_version),
2224 le32_to_cpu(sb->feature_map),
2225 uuid,
2226 sb->set_name,
2227 (unsigned long long)le64_to_cpu(sb->ctime)
2228 & MD_SUPERBLOCK_1_TIME_SEC_MASK);
2230 uuid = sb->device_uuid;
2231 printk(KERN_INFO
2232 "md: L%u SZ%llu RD:%u LO:%u CS:%u DO:%llu DS:%llu SO:%llu"
2233 " RO:%llu\n"
2234 "md: Dev:%08x UUID: %pU\n"
2235 "md: (F:0x%08x) UT:%llu Events:%llu ResyncOffset:%llu CSUM:0x%08x\n"
2236 "md: (MaxDev:%u) \n",
2237 le32_to_cpu(sb->level),
2238 (unsigned long long)le64_to_cpu(sb->size),
2239 le32_to_cpu(sb->raid_disks),
2240 le32_to_cpu(sb->layout),
2241 le32_to_cpu(sb->chunksize),
2242 (unsigned long long)le64_to_cpu(sb->data_offset),
2243 (unsigned long long)le64_to_cpu(sb->data_size),
2244 (unsigned long long)le64_to_cpu(sb->super_offset),
2245 (unsigned long long)le64_to_cpu(sb->recovery_offset),
2246 le32_to_cpu(sb->dev_number),
2247 uuid,
2248 sb->devflags,
2249 (unsigned long long)le64_to_cpu(sb->utime) & MD_SUPERBLOCK_1_TIME_SEC_MASK,
2250 (unsigned long long)le64_to_cpu(sb->events),
2251 (unsigned long long)le64_to_cpu(sb->resync_offset),
2252 le32_to_cpu(sb->sb_csum),
2253 le32_to_cpu(sb->max_dev)
2257 static void print_rdev(mdk_rdev_t *rdev, int major_version)
2259 char b[BDEVNAME_SIZE];
2260 printk(KERN_INFO "md: rdev %s, Sect:%08llu F:%d S:%d DN:%u\n",
2261 bdevname(rdev->bdev, b), (unsigned long long)rdev->sectors,
2262 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
2263 rdev->desc_nr);
2264 if (rdev->sb_loaded) {
2265 printk(KERN_INFO "md: rdev superblock (MJ:%d):\n", major_version);
2266 switch (major_version) {
2267 case 0:
2268 print_sb_90(page_address(rdev->sb_page));
2269 break;
2270 case 1:
2271 print_sb_1(page_address(rdev->sb_page));
2272 break;
2274 } else
2275 printk(KERN_INFO "md: no rdev superblock!\n");
2278 static void md_print_devices(void)
2280 struct list_head *tmp;
2281 mdk_rdev_t *rdev;
2282 mddev_t *mddev;
2283 char b[BDEVNAME_SIZE];
2285 printk("\n");
2286 printk("md: **********************************\n");
2287 printk("md: * <COMPLETE RAID STATE PRINTOUT> *\n");
2288 printk("md: **********************************\n");
2289 for_each_mddev(mddev, tmp) {
2291 if (mddev->bitmap)
2292 bitmap_print_sb(mddev->bitmap);
2293 else
2294 printk("%s: ", mdname(mddev));
2295 list_for_each_entry(rdev, &mddev->disks, same_set)
2296 printk("<%s>", bdevname(rdev->bdev,b));
2297 printk("\n");
2299 list_for_each_entry(rdev, &mddev->disks, same_set)
2300 print_rdev(rdev, mddev->major_version);
2302 printk("md: **********************************\n");
2303 printk("\n");
2307 static void sync_sbs(mddev_t * mddev, int nospares)
2309 /* Update each superblock (in-memory image), but
2310 * if we are allowed to, skip spares which already
2311 * have the right event counter, or have one earlier
2312 * (which would mean they aren't being marked as dirty
2313 * with the rest of the array)
2315 mdk_rdev_t *rdev;
2316 list_for_each_entry(rdev, &mddev->disks, same_set) {
2317 if (rdev->sb_events == mddev->events ||
2318 (nospares &&
2319 rdev->raid_disk < 0 &&
2320 rdev->sb_events+1 == mddev->events)) {
2321 /* Don't update this superblock */
2322 rdev->sb_loaded = 2;
2323 } else {
2324 sync_super(mddev, rdev);
2325 rdev->sb_loaded = 1;
2330 static void md_update_sb(mddev_t * mddev, int force_change)
2332 mdk_rdev_t *rdev;
2333 int sync_req;
2334 int nospares = 0;
2335 int any_badblocks_changed = 0;
2337 repeat:
2338 /* First make sure individual recovery_offsets are correct */
2339 list_for_each_entry(rdev, &mddev->disks, same_set) {
2340 if (rdev->raid_disk >= 0 &&
2341 mddev->delta_disks >= 0 &&
2342 !test_bit(In_sync, &rdev->flags) &&
2343 mddev->curr_resync_completed > rdev->recovery_offset)
2344 rdev->recovery_offset = mddev->curr_resync_completed;
2347 if (!mddev->persistent) {
2348 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2349 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2350 if (!mddev->external) {
2351 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2352 list_for_each_entry(rdev, &mddev->disks, same_set) {
2353 if (rdev->badblocks.changed) {
2354 md_ack_all_badblocks(&rdev->badblocks);
2355 md_error(mddev, rdev);
2357 clear_bit(Blocked, &rdev->flags);
2358 clear_bit(BlockedBadBlocks, &rdev->flags);
2359 wake_up(&rdev->blocked_wait);
2362 wake_up(&mddev->sb_wait);
2363 return;
2366 spin_lock_irq(&mddev->write_lock);
2368 mddev->utime = get_seconds();
2370 if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2371 force_change = 1;
2372 if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2373 /* just a clean<-> dirty transition, possibly leave spares alone,
2374 * though if events isn't the right even/odd, we will have to do
2375 * spares after all
2377 nospares = 1;
2378 if (force_change)
2379 nospares = 0;
2380 if (mddev->degraded)
2381 /* If the array is degraded, then skipping spares is both
2382 * dangerous and fairly pointless.
2383 * Dangerous because a device that was removed from the array
2384 * might have a event_count that still looks up-to-date,
2385 * so it can be re-added without a resync.
2386 * Pointless because if there are any spares to skip,
2387 * then a recovery will happen and soon that array won't
2388 * be degraded any more and the spare can go back to sleep then.
2390 nospares = 0;
2392 sync_req = mddev->in_sync;
2394 /* If this is just a dirty<->clean transition, and the array is clean
2395 * and 'events' is odd, we can roll back to the previous clean state */
2396 if (nospares
2397 && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2398 && mddev->can_decrease_events
2399 && mddev->events != 1) {
2400 mddev->events--;
2401 mddev->can_decrease_events = 0;
2402 } else {
2403 /* otherwise we have to go forward and ... */
2404 mddev->events ++;
2405 mddev->can_decrease_events = nospares;
2408 if (!mddev->events) {
2410 * oops, this 64-bit counter should never wrap.
2411 * Either we are in around ~1 trillion A.C., assuming
2412 * 1 reboot per second, or we have a bug:
2414 MD_BUG();
2415 mddev->events --;
2418 list_for_each_entry(rdev, &mddev->disks, same_set) {
2419 if (rdev->badblocks.changed)
2420 any_badblocks_changed++;
2421 if (test_bit(Faulty, &rdev->flags))
2422 set_bit(FaultRecorded, &rdev->flags);
2425 sync_sbs(mddev, nospares);
2426 spin_unlock_irq(&mddev->write_lock);
2428 dprintk(KERN_INFO
2429 "md: updating %s RAID superblock on device (in sync %d)\n",
2430 mdname(mddev),mddev->in_sync);
2432 bitmap_update_sb(mddev->bitmap);
2433 list_for_each_entry(rdev, &mddev->disks, same_set) {
2434 char b[BDEVNAME_SIZE];
2435 dprintk(KERN_INFO "md: ");
2436 if (rdev->sb_loaded != 1)
2437 continue; /* no noise on spare devices */
2438 if (test_bit(Faulty, &rdev->flags))
2439 dprintk("(skipping faulty ");
2441 dprintk("%s ", bdevname(rdev->bdev,b));
2442 if (!test_bit(Faulty, &rdev->flags)) {
2443 md_super_write(mddev,rdev,
2444 rdev->sb_start, rdev->sb_size,
2445 rdev->sb_page);
2446 dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
2447 bdevname(rdev->bdev,b),
2448 (unsigned long long)rdev->sb_start);
2449 rdev->sb_events = mddev->events;
2450 if (rdev->badblocks.size) {
2451 md_super_write(mddev, rdev,
2452 rdev->badblocks.sector,
2453 rdev->badblocks.size << 9,
2454 rdev->bb_page);
2455 rdev->badblocks.size = 0;
2458 } else
2459 dprintk(")\n");
2460 if (mddev->level == LEVEL_MULTIPATH)
2461 /* only need to write one superblock... */
2462 break;
2464 md_super_wait(mddev);
2465 /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2467 spin_lock_irq(&mddev->write_lock);
2468 if (mddev->in_sync != sync_req ||
2469 test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2470 /* have to write it out again */
2471 spin_unlock_irq(&mddev->write_lock);
2472 goto repeat;
2474 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2475 spin_unlock_irq(&mddev->write_lock);
2476 wake_up(&mddev->sb_wait);
2477 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2478 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2480 list_for_each_entry(rdev, &mddev->disks, same_set) {
2481 if (test_and_clear_bit(FaultRecorded, &rdev->flags))
2482 clear_bit(Blocked, &rdev->flags);
2484 if (any_badblocks_changed)
2485 md_ack_all_badblocks(&rdev->badblocks);
2486 clear_bit(BlockedBadBlocks, &rdev->flags);
2487 wake_up(&rdev->blocked_wait);
2491 /* words written to sysfs files may, or may not, be \n terminated.
2492 * We want to accept with case. For this we use cmd_match.
2494 static int cmd_match(const char *cmd, const char *str)
2496 /* See if cmd, written into a sysfs file, matches
2497 * str. They must either be the same, or cmd can
2498 * have a trailing newline
2500 while (*cmd && *str && *cmd == *str) {
2501 cmd++;
2502 str++;
2504 if (*cmd == '\n')
2505 cmd++;
2506 if (*str || *cmd)
2507 return 0;
2508 return 1;
2511 struct rdev_sysfs_entry {
2512 struct attribute attr;
2513 ssize_t (*show)(mdk_rdev_t *, char *);
2514 ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
2517 static ssize_t
2518 state_show(mdk_rdev_t *rdev, char *page)
2520 char *sep = "";
2521 size_t len = 0;
2523 if (test_bit(Faulty, &rdev->flags) ||
2524 rdev->badblocks.unacked_exist) {
2525 len+= sprintf(page+len, "%sfaulty",sep);
2526 sep = ",";
2528 if (test_bit(In_sync, &rdev->flags)) {
2529 len += sprintf(page+len, "%sin_sync",sep);
2530 sep = ",";
2532 if (test_bit(WriteMostly, &rdev->flags)) {
2533 len += sprintf(page+len, "%swrite_mostly",sep);
2534 sep = ",";
2536 if (test_bit(Blocked, &rdev->flags) ||
2537 rdev->badblocks.unacked_exist) {
2538 len += sprintf(page+len, "%sblocked", sep);
2539 sep = ",";
2541 if (!test_bit(Faulty, &rdev->flags) &&
2542 !test_bit(In_sync, &rdev->flags)) {
2543 len += sprintf(page+len, "%sspare", sep);
2544 sep = ",";
2546 if (test_bit(WriteErrorSeen, &rdev->flags)) {
2547 len += sprintf(page+len, "%swrite_error", sep);
2548 sep = ",";
2550 return len+sprintf(page+len, "\n");
2553 static ssize_t
2554 state_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2556 /* can write
2557 * faulty - simulates an error
2558 * remove - disconnects the device
2559 * writemostly - sets write_mostly
2560 * -writemostly - clears write_mostly
2561 * blocked - sets the Blocked flags
2562 * -blocked - clears the Blocked and possibly simulates an error
2563 * insync - sets Insync providing device isn't active
2564 * write_error - sets WriteErrorSeen
2565 * -write_error - clears WriteErrorSeen
2567 int err = -EINVAL;
2568 if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2569 md_error(rdev->mddev, rdev);
2570 if (test_bit(Faulty, &rdev->flags))
2571 err = 0;
2572 else
2573 err = -EBUSY;
2574 } else if (cmd_match(buf, "remove")) {
2575 if (rdev->raid_disk >= 0)
2576 err = -EBUSY;
2577 else {
2578 mddev_t *mddev = rdev->mddev;
2579 kick_rdev_from_array(rdev);
2580 if (mddev->pers)
2581 md_update_sb(mddev, 1);
2582 md_new_event(mddev);
2583 err = 0;
2585 } else if (cmd_match(buf, "writemostly")) {
2586 set_bit(WriteMostly, &rdev->flags);
2587 err = 0;
2588 } else if (cmd_match(buf, "-writemostly")) {
2589 clear_bit(WriteMostly, &rdev->flags);
2590 err = 0;
2591 } else if (cmd_match(buf, "blocked")) {
2592 set_bit(Blocked, &rdev->flags);
2593 err = 0;
2594 } else if (cmd_match(buf, "-blocked")) {
2595 if (!test_bit(Faulty, &rdev->flags) &&
2596 rdev->badblocks.unacked_exist) {
2597 /* metadata handler doesn't understand badblocks,
2598 * so we need to fail the device
2600 md_error(rdev->mddev, rdev);
2602 clear_bit(Blocked, &rdev->flags);
2603 clear_bit(BlockedBadBlocks, &rdev->flags);
2604 wake_up(&rdev->blocked_wait);
2605 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2606 md_wakeup_thread(rdev->mddev->thread);
2608 err = 0;
2609 } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2610 set_bit(In_sync, &rdev->flags);
2611 err = 0;
2612 } else if (cmd_match(buf, "write_error")) {
2613 set_bit(WriteErrorSeen, &rdev->flags);
2614 err = 0;
2615 } else if (cmd_match(buf, "-write_error")) {
2616 clear_bit(WriteErrorSeen, &rdev->flags);
2617 err = 0;
2619 if (!err)
2620 sysfs_notify_dirent_safe(rdev->sysfs_state);
2621 return err ? err : len;
2623 static struct rdev_sysfs_entry rdev_state =
2624 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
2626 static ssize_t
2627 errors_show(mdk_rdev_t *rdev, char *page)
2629 return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2632 static ssize_t
2633 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2635 char *e;
2636 unsigned long n = simple_strtoul(buf, &e, 10);
2637 if (*buf && (*e == 0 || *e == '\n')) {
2638 atomic_set(&rdev->corrected_errors, n);
2639 return len;
2641 return -EINVAL;
2643 static struct rdev_sysfs_entry rdev_errors =
2644 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2646 static ssize_t
2647 slot_show(mdk_rdev_t *rdev, char *page)
2649 if (rdev->raid_disk < 0)
2650 return sprintf(page, "none\n");
2651 else
2652 return sprintf(page, "%d\n", rdev->raid_disk);
2655 static ssize_t
2656 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2658 char *e;
2659 int err;
2660 int slot = simple_strtoul(buf, &e, 10);
2661 if (strncmp(buf, "none", 4)==0)
2662 slot = -1;
2663 else if (e==buf || (*e && *e!= '\n'))
2664 return -EINVAL;
2665 if (rdev->mddev->pers && slot == -1) {
2666 /* Setting 'slot' on an active array requires also
2667 * updating the 'rd%d' link, and communicating
2668 * with the personality with ->hot_*_disk.
2669 * For now we only support removing
2670 * failed/spare devices. This normally happens automatically,
2671 * but not when the metadata is externally managed.
2673 if (rdev->raid_disk == -1)
2674 return -EEXIST;
2675 /* personality does all needed checks */
2676 if (rdev->mddev->pers->hot_remove_disk == NULL)
2677 return -EINVAL;
2678 err = rdev->mddev->pers->
2679 hot_remove_disk(rdev->mddev, rdev->raid_disk);
2680 if (err)
2681 return err;
2682 sysfs_unlink_rdev(rdev->mddev, rdev);
2683 rdev->raid_disk = -1;
2684 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2685 md_wakeup_thread(rdev->mddev->thread);
2686 } else if (rdev->mddev->pers) {
2687 mdk_rdev_t *rdev2;
2688 /* Activating a spare .. or possibly reactivating
2689 * if we ever get bitmaps working here.
2692 if (rdev->raid_disk != -1)
2693 return -EBUSY;
2695 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2696 return -EBUSY;
2698 if (rdev->mddev->pers->hot_add_disk == NULL)
2699 return -EINVAL;
2701 list_for_each_entry(rdev2, &rdev->mddev->disks, same_set)
2702 if (rdev2->raid_disk == slot)
2703 return -EEXIST;
2705 if (slot >= rdev->mddev->raid_disks &&
2706 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2707 return -ENOSPC;
2709 rdev->raid_disk = slot;
2710 if (test_bit(In_sync, &rdev->flags))
2711 rdev->saved_raid_disk = slot;
2712 else
2713 rdev->saved_raid_disk = -1;
2714 err = rdev->mddev->pers->
2715 hot_add_disk(rdev->mddev, rdev);
2716 if (err) {
2717 rdev->raid_disk = -1;
2718 return err;
2719 } else
2720 sysfs_notify_dirent_safe(rdev->sysfs_state);
2721 if (sysfs_link_rdev(rdev->mddev, rdev))
2722 /* failure here is OK */;
2723 /* don't wakeup anyone, leave that to userspace. */
2724 } else {
2725 if (slot >= rdev->mddev->raid_disks &&
2726 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2727 return -ENOSPC;
2728 rdev->raid_disk = slot;
2729 /* assume it is working */
2730 clear_bit(Faulty, &rdev->flags);
2731 clear_bit(WriteMostly, &rdev->flags);
2732 set_bit(In_sync, &rdev->flags);
2733 sysfs_notify_dirent_safe(rdev->sysfs_state);
2735 return len;
2739 static struct rdev_sysfs_entry rdev_slot =
2740 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2742 static ssize_t
2743 offset_show(mdk_rdev_t *rdev, char *page)
2745 return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2748 static ssize_t
2749 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2751 char *e;
2752 unsigned long long offset = simple_strtoull(buf, &e, 10);
2753 if (e==buf || (*e && *e != '\n'))
2754 return -EINVAL;
2755 if (rdev->mddev->pers && rdev->raid_disk >= 0)
2756 return -EBUSY;
2757 if (rdev->sectors && rdev->mddev->external)
2758 /* Must set offset before size, so overlap checks
2759 * can be sane */
2760 return -EBUSY;
2761 rdev->data_offset = offset;
2762 return len;
2765 static struct rdev_sysfs_entry rdev_offset =
2766 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2768 static ssize_t
2769 rdev_size_show(mdk_rdev_t *rdev, char *page)
2771 return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2774 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2776 /* check if two start/length pairs overlap */
2777 if (s1+l1 <= s2)
2778 return 0;
2779 if (s2+l2 <= s1)
2780 return 0;
2781 return 1;
2784 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2786 unsigned long long blocks;
2787 sector_t new;
2789 if (strict_strtoull(buf, 10, &blocks) < 0)
2790 return -EINVAL;
2792 if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2793 return -EINVAL; /* sector conversion overflow */
2795 new = blocks * 2;
2796 if (new != blocks * 2)
2797 return -EINVAL; /* unsigned long long to sector_t overflow */
2799 *sectors = new;
2800 return 0;
2803 static ssize_t
2804 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2806 mddev_t *my_mddev = rdev->mddev;
2807 sector_t oldsectors = rdev->sectors;
2808 sector_t sectors;
2810 if (strict_blocks_to_sectors(buf, &sectors) < 0)
2811 return -EINVAL;
2812 if (my_mddev->pers && rdev->raid_disk >= 0) {
2813 if (my_mddev->persistent) {
2814 sectors = super_types[my_mddev->major_version].
2815 rdev_size_change(rdev, sectors);
2816 if (!sectors)
2817 return -EBUSY;
2818 } else if (!sectors)
2819 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
2820 rdev->data_offset;
2822 if (sectors < my_mddev->dev_sectors)
2823 return -EINVAL; /* component must fit device */
2825 rdev->sectors = sectors;
2826 if (sectors > oldsectors && my_mddev->external) {
2827 /* need to check that all other rdevs with the same ->bdev
2828 * do not overlap. We need to unlock the mddev to avoid
2829 * a deadlock. We have already changed rdev->sectors, and if
2830 * we have to change it back, we will have the lock again.
2832 mddev_t *mddev;
2833 int overlap = 0;
2834 struct list_head *tmp;
2836 mddev_unlock(my_mddev);
2837 for_each_mddev(mddev, tmp) {
2838 mdk_rdev_t *rdev2;
2840 mddev_lock(mddev);
2841 list_for_each_entry(rdev2, &mddev->disks, same_set)
2842 if (rdev->bdev == rdev2->bdev &&
2843 rdev != rdev2 &&
2844 overlaps(rdev->data_offset, rdev->sectors,
2845 rdev2->data_offset,
2846 rdev2->sectors)) {
2847 overlap = 1;
2848 break;
2850 mddev_unlock(mddev);
2851 if (overlap) {
2852 mddev_put(mddev);
2853 break;
2856 mddev_lock(my_mddev);
2857 if (overlap) {
2858 /* Someone else could have slipped in a size
2859 * change here, but doing so is just silly.
2860 * We put oldsectors back because we *know* it is
2861 * safe, and trust userspace not to race with
2862 * itself
2864 rdev->sectors = oldsectors;
2865 return -EBUSY;
2868 return len;
2871 static struct rdev_sysfs_entry rdev_size =
2872 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2875 static ssize_t recovery_start_show(mdk_rdev_t *rdev, char *page)
2877 unsigned long long recovery_start = rdev->recovery_offset;
2879 if (test_bit(In_sync, &rdev->flags) ||
2880 recovery_start == MaxSector)
2881 return sprintf(page, "none\n");
2883 return sprintf(page, "%llu\n", recovery_start);
2886 static ssize_t recovery_start_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2888 unsigned long long recovery_start;
2890 if (cmd_match(buf, "none"))
2891 recovery_start = MaxSector;
2892 else if (strict_strtoull(buf, 10, &recovery_start))
2893 return -EINVAL;
2895 if (rdev->mddev->pers &&
2896 rdev->raid_disk >= 0)
2897 return -EBUSY;
2899 rdev->recovery_offset = recovery_start;
2900 if (recovery_start == MaxSector)
2901 set_bit(In_sync, &rdev->flags);
2902 else
2903 clear_bit(In_sync, &rdev->flags);
2904 return len;
2907 static struct rdev_sysfs_entry rdev_recovery_start =
2908 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
2911 static ssize_t
2912 badblocks_show(struct badblocks *bb, char *page, int unack);
2913 static ssize_t
2914 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack);
2916 static ssize_t bb_show(mdk_rdev_t *rdev, char *page)
2918 return badblocks_show(&rdev->badblocks, page, 0);
2920 static ssize_t bb_store(mdk_rdev_t *rdev, const char *page, size_t len)
2922 int rv = badblocks_store(&rdev->badblocks, page, len, 0);
2923 /* Maybe that ack was all we needed */
2924 if (test_and_clear_bit(BlockedBadBlocks, &rdev->flags))
2925 wake_up(&rdev->blocked_wait);
2926 return rv;
2928 static struct rdev_sysfs_entry rdev_bad_blocks =
2929 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
2932 static ssize_t ubb_show(mdk_rdev_t *rdev, char *page)
2934 return badblocks_show(&rdev->badblocks, page, 1);
2936 static ssize_t ubb_store(mdk_rdev_t *rdev, const char *page, size_t len)
2938 return badblocks_store(&rdev->badblocks, page, len, 1);
2940 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
2941 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
2943 static struct attribute *rdev_default_attrs[] = {
2944 &rdev_state.attr,
2945 &rdev_errors.attr,
2946 &rdev_slot.attr,
2947 &rdev_offset.attr,
2948 &rdev_size.attr,
2949 &rdev_recovery_start.attr,
2950 &rdev_bad_blocks.attr,
2951 &rdev_unack_bad_blocks.attr,
2952 NULL,
2954 static ssize_t
2955 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2957 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2958 mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2959 mddev_t *mddev = rdev->mddev;
2960 ssize_t rv;
2962 if (!entry->show)
2963 return -EIO;
2965 rv = mddev ? mddev_lock(mddev) : -EBUSY;
2966 if (!rv) {
2967 if (rdev->mddev == NULL)
2968 rv = -EBUSY;
2969 else
2970 rv = entry->show(rdev, page);
2971 mddev_unlock(mddev);
2973 return rv;
2976 static ssize_t
2977 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
2978 const char *page, size_t length)
2980 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2981 mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2982 ssize_t rv;
2983 mddev_t *mddev = rdev->mddev;
2985 if (!entry->store)
2986 return -EIO;
2987 if (!capable(CAP_SYS_ADMIN))
2988 return -EACCES;
2989 rv = mddev ? mddev_lock(mddev): -EBUSY;
2990 if (!rv) {
2991 if (rdev->mddev == NULL)
2992 rv = -EBUSY;
2993 else
2994 rv = entry->store(rdev, page, length);
2995 mddev_unlock(mddev);
2997 return rv;
3000 static void rdev_free(struct kobject *ko)
3002 mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
3003 kfree(rdev);
3005 static const struct sysfs_ops rdev_sysfs_ops = {
3006 .show = rdev_attr_show,
3007 .store = rdev_attr_store,
3009 static struct kobj_type rdev_ktype = {
3010 .release = rdev_free,
3011 .sysfs_ops = &rdev_sysfs_ops,
3012 .default_attrs = rdev_default_attrs,
3015 int md_rdev_init(mdk_rdev_t *rdev)
3017 rdev->desc_nr = -1;
3018 rdev->saved_raid_disk = -1;
3019 rdev->raid_disk = -1;
3020 rdev->flags = 0;
3021 rdev->data_offset = 0;
3022 rdev->sb_events = 0;
3023 rdev->last_read_error.tv_sec = 0;
3024 rdev->last_read_error.tv_nsec = 0;
3025 rdev->sb_loaded = 0;
3026 rdev->bb_page = NULL;
3027 atomic_set(&rdev->nr_pending, 0);
3028 atomic_set(&rdev->read_errors, 0);
3029 atomic_set(&rdev->corrected_errors, 0);
3031 INIT_LIST_HEAD(&rdev->same_set);
3032 init_waitqueue_head(&rdev->blocked_wait);
3034 /* Add space to store bad block list.
3035 * This reserves the space even on arrays where it cannot
3036 * be used - I wonder if that matters
3038 rdev->badblocks.count = 0;
3039 rdev->badblocks.shift = 0;
3040 rdev->badblocks.page = kmalloc(PAGE_SIZE, GFP_KERNEL);
3041 seqlock_init(&rdev->badblocks.lock);
3042 if (rdev->badblocks.page == NULL)
3043 return -ENOMEM;
3045 return 0;
3047 EXPORT_SYMBOL_GPL(md_rdev_init);
3049 * Import a device. If 'super_format' >= 0, then sanity check the superblock
3051 * mark the device faulty if:
3053 * - the device is nonexistent (zero size)
3054 * - the device has no valid superblock
3056 * a faulty rdev _never_ has rdev->sb set.
3058 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
3060 char b[BDEVNAME_SIZE];
3061 int err;
3062 mdk_rdev_t *rdev;
3063 sector_t size;
3065 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3066 if (!rdev) {
3067 printk(KERN_ERR "md: could not alloc mem for new device!\n");
3068 return ERR_PTR(-ENOMEM);
3071 err = md_rdev_init(rdev);
3072 if (err)
3073 goto abort_free;
3074 err = alloc_disk_sb(rdev);
3075 if (err)
3076 goto abort_free;
3078 err = lock_rdev(rdev, newdev, super_format == -2);
3079 if (err)
3080 goto abort_free;
3082 kobject_init(&rdev->kobj, &rdev_ktype);
3084 size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3085 if (!size) {
3086 printk(KERN_WARNING
3087 "md: %s has zero or unknown size, marking faulty!\n",
3088 bdevname(rdev->bdev,b));
3089 err = -EINVAL;
3090 goto abort_free;
3093 if (super_format >= 0) {
3094 err = super_types[super_format].
3095 load_super(rdev, NULL, super_minor);
3096 if (err == -EINVAL) {
3097 printk(KERN_WARNING
3098 "md: %s does not have a valid v%d.%d "
3099 "superblock, not importing!\n",
3100 bdevname(rdev->bdev,b),
3101 super_format, super_minor);
3102 goto abort_free;
3104 if (err < 0) {
3105 printk(KERN_WARNING
3106 "md: could not read %s's sb, not importing!\n",
3107 bdevname(rdev->bdev,b));
3108 goto abort_free;
3111 if (super_format == -1)
3112 /* hot-add for 0.90, or non-persistent: so no badblocks */
3113 rdev->badblocks.shift = -1;
3115 return rdev;
3117 abort_free:
3118 if (rdev->bdev)
3119 unlock_rdev(rdev);
3120 free_disk_sb(rdev);
3121 kfree(rdev->badblocks.page);
3122 kfree(rdev);
3123 return ERR_PTR(err);
3127 * Check a full RAID array for plausibility
3131 static void analyze_sbs(mddev_t * mddev)
3133 int i;
3134 mdk_rdev_t *rdev, *freshest, *tmp;
3135 char b[BDEVNAME_SIZE];
3137 freshest = NULL;
3138 rdev_for_each(rdev, tmp, mddev)
3139 switch (super_types[mddev->major_version].
3140 load_super(rdev, freshest, mddev->minor_version)) {
3141 case 1:
3142 freshest = rdev;
3143 break;
3144 case 0:
3145 break;
3146 default:
3147 printk( KERN_ERR \
3148 "md: fatal superblock inconsistency in %s"
3149 " -- removing from array\n",
3150 bdevname(rdev->bdev,b));
3151 kick_rdev_from_array(rdev);
3155 super_types[mddev->major_version].
3156 validate_super(mddev, freshest);
3158 i = 0;
3159 rdev_for_each(rdev, tmp, mddev) {
3160 if (mddev->max_disks &&
3161 (rdev->desc_nr >= mddev->max_disks ||
3162 i > mddev->max_disks)) {
3163 printk(KERN_WARNING
3164 "md: %s: %s: only %d devices permitted\n",
3165 mdname(mddev), bdevname(rdev->bdev, b),
3166 mddev->max_disks);
3167 kick_rdev_from_array(rdev);
3168 continue;
3170 if (rdev != freshest)
3171 if (super_types[mddev->major_version].
3172 validate_super(mddev, rdev)) {
3173 printk(KERN_WARNING "md: kicking non-fresh %s"
3174 " from array!\n",
3175 bdevname(rdev->bdev,b));
3176 kick_rdev_from_array(rdev);
3177 continue;
3179 if (mddev->level == LEVEL_MULTIPATH) {
3180 rdev->desc_nr = i++;
3181 rdev->raid_disk = rdev->desc_nr;
3182 set_bit(In_sync, &rdev->flags);
3183 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
3184 rdev->raid_disk = -1;
3185 clear_bit(In_sync, &rdev->flags);
3190 /* Read a fixed-point number.
3191 * Numbers in sysfs attributes should be in "standard" units where
3192 * possible, so time should be in seconds.
3193 * However we internally use a a much smaller unit such as
3194 * milliseconds or jiffies.
3195 * This function takes a decimal number with a possible fractional
3196 * component, and produces an integer which is the result of
3197 * multiplying that number by 10^'scale'.
3198 * all without any floating-point arithmetic.
3200 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3202 unsigned long result = 0;
3203 long decimals = -1;
3204 while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3205 if (*cp == '.')
3206 decimals = 0;
3207 else if (decimals < scale) {
3208 unsigned int value;
3209 value = *cp - '0';
3210 result = result * 10 + value;
3211 if (decimals >= 0)
3212 decimals++;
3214 cp++;
3216 if (*cp == '\n')
3217 cp++;
3218 if (*cp)
3219 return -EINVAL;
3220 if (decimals < 0)
3221 decimals = 0;
3222 while (decimals < scale) {
3223 result *= 10;
3224 decimals ++;
3226 *res = result;
3227 return 0;
3231 static void md_safemode_timeout(unsigned long data);
3233 static ssize_t
3234 safe_delay_show(mddev_t *mddev, char *page)
3236 int msec = (mddev->safemode_delay*1000)/HZ;
3237 return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3239 static ssize_t
3240 safe_delay_store(mddev_t *mddev, const char *cbuf, size_t len)
3242 unsigned long msec;
3244 if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3245 return -EINVAL;
3246 if (msec == 0)
3247 mddev->safemode_delay = 0;
3248 else {
3249 unsigned long old_delay = mddev->safemode_delay;
3250 mddev->safemode_delay = (msec*HZ)/1000;
3251 if (mddev->safemode_delay == 0)
3252 mddev->safemode_delay = 1;
3253 if (mddev->safemode_delay < old_delay)
3254 md_safemode_timeout((unsigned long)mddev);
3256 return len;
3258 static struct md_sysfs_entry md_safe_delay =
3259 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3261 static ssize_t
3262 level_show(mddev_t *mddev, char *page)
3264 struct mdk_personality *p = mddev->pers;
3265 if (p)
3266 return sprintf(page, "%s\n", p->name);
3267 else if (mddev->clevel[0])
3268 return sprintf(page, "%s\n", mddev->clevel);
3269 else if (mddev->level != LEVEL_NONE)
3270 return sprintf(page, "%d\n", mddev->level);
3271 else
3272 return 0;
3275 static ssize_t
3276 level_store(mddev_t *mddev, const char *buf, size_t len)
3278 char clevel[16];
3279 ssize_t rv = len;
3280 struct mdk_personality *pers;
3281 long level;
3282 void *priv;
3283 mdk_rdev_t *rdev;
3285 if (mddev->pers == NULL) {
3286 if (len == 0)
3287 return 0;
3288 if (len >= sizeof(mddev->clevel))
3289 return -ENOSPC;
3290 strncpy(mddev->clevel, buf, len);
3291 if (mddev->clevel[len-1] == '\n')
3292 len--;
3293 mddev->clevel[len] = 0;
3294 mddev->level = LEVEL_NONE;
3295 return rv;
3298 /* request to change the personality. Need to ensure:
3299 * - array is not engaged in resync/recovery/reshape
3300 * - old personality can be suspended
3301 * - new personality will access other array.
3304 if (mddev->sync_thread ||
3305 mddev->reshape_position != MaxSector ||
3306 mddev->sysfs_active)
3307 return -EBUSY;
3309 if (!mddev->pers->quiesce) {
3310 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3311 mdname(mddev), mddev->pers->name);
3312 return -EINVAL;
3315 /* Now find the new personality */
3316 if (len == 0 || len >= sizeof(clevel))
3317 return -EINVAL;
3318 strncpy(clevel, buf, len);
3319 if (clevel[len-1] == '\n')
3320 len--;
3321 clevel[len] = 0;
3322 if (strict_strtol(clevel, 10, &level))
3323 level = LEVEL_NONE;
3325 if (request_module("md-%s", clevel) != 0)
3326 request_module("md-level-%s", clevel);
3327 spin_lock(&pers_lock);
3328 pers = find_pers(level, clevel);
3329 if (!pers || !try_module_get(pers->owner)) {
3330 spin_unlock(&pers_lock);
3331 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3332 return -EINVAL;
3334 spin_unlock(&pers_lock);
3336 if (pers == mddev->pers) {
3337 /* Nothing to do! */
3338 module_put(pers->owner);
3339 return rv;
3341 if (!pers->takeover) {
3342 module_put(pers->owner);
3343 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3344 mdname(mddev), clevel);
3345 return -EINVAL;
3348 list_for_each_entry(rdev, &mddev->disks, same_set)
3349 rdev->new_raid_disk = rdev->raid_disk;
3351 /* ->takeover must set new_* and/or delta_disks
3352 * if it succeeds, and may set them when it fails.
3354 priv = pers->takeover(mddev);
3355 if (IS_ERR(priv)) {
3356 mddev->new_level = mddev->level;
3357 mddev->new_layout = mddev->layout;
3358 mddev->new_chunk_sectors = mddev->chunk_sectors;
3359 mddev->raid_disks -= mddev->delta_disks;
3360 mddev->delta_disks = 0;
3361 module_put(pers->owner);
3362 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3363 mdname(mddev), clevel);
3364 return PTR_ERR(priv);
3367 /* Looks like we have a winner */
3368 mddev_suspend(mddev);
3369 mddev->pers->stop(mddev);
3371 if (mddev->pers->sync_request == NULL &&
3372 pers->sync_request != NULL) {
3373 /* need to add the md_redundancy_group */
3374 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3375 printk(KERN_WARNING
3376 "md: cannot register extra attributes for %s\n",
3377 mdname(mddev));
3378 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, NULL, "sync_action");
3380 if (mddev->pers->sync_request != NULL &&
3381 pers->sync_request == NULL) {
3382 /* need to remove the md_redundancy_group */
3383 if (mddev->to_remove == NULL)
3384 mddev->to_remove = &md_redundancy_group;
3387 if (mddev->pers->sync_request == NULL &&
3388 mddev->external) {
3389 /* We are converting from a no-redundancy array
3390 * to a redundancy array and metadata is managed
3391 * externally so we need to be sure that writes
3392 * won't block due to a need to transition
3393 * clean->dirty
3394 * until external management is started.
3396 mddev->in_sync = 0;
3397 mddev->safemode_delay = 0;
3398 mddev->safemode = 0;
3401 list_for_each_entry(rdev, &mddev->disks, same_set) {
3402 if (rdev->raid_disk < 0)
3403 continue;
3404 if (rdev->new_raid_disk >= mddev->raid_disks)
3405 rdev->new_raid_disk = -1;
3406 if (rdev->new_raid_disk == rdev->raid_disk)
3407 continue;
3408 sysfs_unlink_rdev(mddev, rdev);
3410 list_for_each_entry(rdev, &mddev->disks, same_set) {
3411 if (rdev->raid_disk < 0)
3412 continue;
3413 if (rdev->new_raid_disk == rdev->raid_disk)
3414 continue;
3415 rdev->raid_disk = rdev->new_raid_disk;
3416 if (rdev->raid_disk < 0)
3417 clear_bit(In_sync, &rdev->flags);
3418 else {
3419 if (sysfs_link_rdev(mddev, rdev))
3420 printk(KERN_WARNING "md: cannot register rd%d"
3421 " for %s after level change\n",
3422 rdev->raid_disk, mdname(mddev));
3426 module_put(mddev->pers->owner);
3427 mddev->pers = pers;
3428 mddev->private = priv;
3429 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3430 mddev->level = mddev->new_level;
3431 mddev->layout = mddev->new_layout;
3432 mddev->chunk_sectors = mddev->new_chunk_sectors;
3433 mddev->delta_disks = 0;
3434 mddev->degraded = 0;
3435 if (mddev->pers->sync_request == NULL) {
3436 /* this is now an array without redundancy, so
3437 * it must always be in_sync
3439 mddev->in_sync = 1;
3440 del_timer_sync(&mddev->safemode_timer);
3442 pers->run(mddev);
3443 mddev_resume(mddev);
3444 set_bit(MD_CHANGE_DEVS, &mddev->flags);
3445 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3446 md_wakeup_thread(mddev->thread);
3447 sysfs_notify(&mddev->kobj, NULL, "level");
3448 md_new_event(mddev);
3449 return rv;
3452 static struct md_sysfs_entry md_level =
3453 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3456 static ssize_t
3457 layout_show(mddev_t *mddev, char *page)
3459 /* just a number, not meaningful for all levels */
3460 if (mddev->reshape_position != MaxSector &&
3461 mddev->layout != mddev->new_layout)
3462 return sprintf(page, "%d (%d)\n",
3463 mddev->new_layout, mddev->layout);
3464 return sprintf(page, "%d\n", mddev->layout);
3467 static ssize_t
3468 layout_store(mddev_t *mddev, const char *buf, size_t len)
3470 char *e;
3471 unsigned long n = simple_strtoul(buf, &e, 10);
3473 if (!*buf || (*e && *e != '\n'))
3474 return -EINVAL;
3476 if (mddev->pers) {
3477 int err;
3478 if (mddev->pers->check_reshape == NULL)
3479 return -EBUSY;
3480 mddev->new_layout = n;
3481 err = mddev->pers->check_reshape(mddev);
3482 if (err) {
3483 mddev->new_layout = mddev->layout;
3484 return err;
3486 } else {
3487 mddev->new_layout = n;
3488 if (mddev->reshape_position == MaxSector)
3489 mddev->layout = n;
3491 return len;
3493 static struct md_sysfs_entry md_layout =
3494 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3497 static ssize_t
3498 raid_disks_show(mddev_t *mddev, char *page)
3500 if (mddev->raid_disks == 0)
3501 return 0;
3502 if (mddev->reshape_position != MaxSector &&
3503 mddev->delta_disks != 0)
3504 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3505 mddev->raid_disks - mddev->delta_disks);
3506 return sprintf(page, "%d\n", mddev->raid_disks);
3509 static int update_raid_disks(mddev_t *mddev, int raid_disks);
3511 static ssize_t
3512 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
3514 char *e;
3515 int rv = 0;
3516 unsigned long n = simple_strtoul(buf, &e, 10);
3518 if (!*buf || (*e && *e != '\n'))
3519 return -EINVAL;
3521 if (mddev->pers)
3522 rv = update_raid_disks(mddev, n);
3523 else if (mddev->reshape_position != MaxSector) {
3524 int olddisks = mddev->raid_disks - mddev->delta_disks;
3525 mddev->delta_disks = n - olddisks;
3526 mddev->raid_disks = n;
3527 } else
3528 mddev->raid_disks = n;
3529 return rv ? rv : len;
3531 static struct md_sysfs_entry md_raid_disks =
3532 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3534 static ssize_t
3535 chunk_size_show(mddev_t *mddev, char *page)
3537 if (mddev->reshape_position != MaxSector &&
3538 mddev->chunk_sectors != mddev->new_chunk_sectors)
3539 return sprintf(page, "%d (%d)\n",
3540 mddev->new_chunk_sectors << 9,
3541 mddev->chunk_sectors << 9);
3542 return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3545 static ssize_t
3546 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
3548 char *e;
3549 unsigned long n = simple_strtoul(buf, &e, 10);
3551 if (!*buf || (*e && *e != '\n'))
3552 return -EINVAL;
3554 if (mddev->pers) {
3555 int err;
3556 if (mddev->pers->check_reshape == NULL)
3557 return -EBUSY;
3558 mddev->new_chunk_sectors = n >> 9;
3559 err = mddev->pers->check_reshape(mddev);
3560 if (err) {
3561 mddev->new_chunk_sectors = mddev->chunk_sectors;
3562 return err;
3564 } else {
3565 mddev->new_chunk_sectors = n >> 9;
3566 if (mddev->reshape_position == MaxSector)
3567 mddev->chunk_sectors = n >> 9;
3569 return len;
3571 static struct md_sysfs_entry md_chunk_size =
3572 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3574 static ssize_t
3575 resync_start_show(mddev_t *mddev, char *page)
3577 if (mddev->recovery_cp == MaxSector)
3578 return sprintf(page, "none\n");
3579 return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3582 static ssize_t
3583 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
3585 char *e;
3586 unsigned long long n = simple_strtoull(buf, &e, 10);
3588 if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3589 return -EBUSY;
3590 if (cmd_match(buf, "none"))
3591 n = MaxSector;
3592 else if (!*buf || (*e && *e != '\n'))
3593 return -EINVAL;
3595 mddev->recovery_cp = n;
3596 return len;
3598 static struct md_sysfs_entry md_resync_start =
3599 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
3602 * The array state can be:
3604 * clear
3605 * No devices, no size, no level
3606 * Equivalent to STOP_ARRAY ioctl
3607 * inactive
3608 * May have some settings, but array is not active
3609 * all IO results in error
3610 * When written, doesn't tear down array, but just stops it
3611 * suspended (not supported yet)
3612 * All IO requests will block. The array can be reconfigured.
3613 * Writing this, if accepted, will block until array is quiescent
3614 * readonly
3615 * no resync can happen. no superblocks get written.
3616 * write requests fail
3617 * read-auto
3618 * like readonly, but behaves like 'clean' on a write request.
3620 * clean - no pending writes, but otherwise active.
3621 * When written to inactive array, starts without resync
3622 * If a write request arrives then
3623 * if metadata is known, mark 'dirty' and switch to 'active'.
3624 * if not known, block and switch to write-pending
3625 * If written to an active array that has pending writes, then fails.
3626 * active
3627 * fully active: IO and resync can be happening.
3628 * When written to inactive array, starts with resync
3630 * write-pending
3631 * clean, but writes are blocked waiting for 'active' to be written.
3633 * active-idle
3634 * like active, but no writes have been seen for a while (100msec).
3637 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3638 write_pending, active_idle, bad_word};
3639 static char *array_states[] = {
3640 "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3641 "write-pending", "active-idle", NULL };
3643 static int match_word(const char *word, char **list)
3645 int n;
3646 for (n=0; list[n]; n++)
3647 if (cmd_match(word, list[n]))
3648 break;
3649 return n;
3652 static ssize_t
3653 array_state_show(mddev_t *mddev, char *page)
3655 enum array_state st = inactive;
3657 if (mddev->pers)
3658 switch(mddev->ro) {
3659 case 1:
3660 st = readonly;
3661 break;
3662 case 2:
3663 st = read_auto;
3664 break;
3665 case 0:
3666 if (mddev->in_sync)
3667 st = clean;
3668 else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3669 st = write_pending;
3670 else if (mddev->safemode)
3671 st = active_idle;
3672 else
3673 st = active;
3675 else {
3676 if (list_empty(&mddev->disks) &&
3677 mddev->raid_disks == 0 &&
3678 mddev->dev_sectors == 0)
3679 st = clear;
3680 else
3681 st = inactive;
3683 return sprintf(page, "%s\n", array_states[st]);
3686 static int do_md_stop(mddev_t * mddev, int ro, int is_open);
3687 static int md_set_readonly(mddev_t * mddev, int is_open);
3688 static int do_md_run(mddev_t * mddev);
3689 static int restart_array(mddev_t *mddev);
3691 static ssize_t
3692 array_state_store(mddev_t *mddev, const char *buf, size_t len)
3694 int err = -EINVAL;
3695 enum array_state st = match_word(buf, array_states);
3696 switch(st) {
3697 case bad_word:
3698 break;
3699 case clear:
3700 /* stopping an active array */
3701 if (atomic_read(&mddev->openers) > 0)
3702 return -EBUSY;
3703 err = do_md_stop(mddev, 0, 0);
3704 break;
3705 case inactive:
3706 /* stopping an active array */
3707 if (mddev->pers) {
3708 if (atomic_read(&mddev->openers) > 0)
3709 return -EBUSY;
3710 err = do_md_stop(mddev, 2, 0);
3711 } else
3712 err = 0; /* already inactive */
3713 break;
3714 case suspended:
3715 break; /* not supported yet */
3716 case readonly:
3717 if (mddev->pers)
3718 err = md_set_readonly(mddev, 0);
3719 else {
3720 mddev->ro = 1;
3721 set_disk_ro(mddev->gendisk, 1);
3722 err = do_md_run(mddev);
3724 break;
3725 case read_auto:
3726 if (mddev->pers) {
3727 if (mddev->ro == 0)
3728 err = md_set_readonly(mddev, 0);
3729 else if (mddev->ro == 1)
3730 err = restart_array(mddev);
3731 if (err == 0) {
3732 mddev->ro = 2;
3733 set_disk_ro(mddev->gendisk, 0);
3735 } else {
3736 mddev->ro = 2;
3737 err = do_md_run(mddev);
3739 break;
3740 case clean:
3741 if (mddev->pers) {
3742 restart_array(mddev);
3743 spin_lock_irq(&mddev->write_lock);
3744 if (atomic_read(&mddev->writes_pending) == 0) {
3745 if (mddev->in_sync == 0) {
3746 mddev->in_sync = 1;
3747 if (mddev->safemode == 1)
3748 mddev->safemode = 0;
3749 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3751 err = 0;
3752 } else
3753 err = -EBUSY;
3754 spin_unlock_irq(&mddev->write_lock);
3755 } else
3756 err = -EINVAL;
3757 break;
3758 case active:
3759 if (mddev->pers) {
3760 restart_array(mddev);
3761 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3762 wake_up(&mddev->sb_wait);
3763 err = 0;
3764 } else {
3765 mddev->ro = 0;
3766 set_disk_ro(mddev->gendisk, 0);
3767 err = do_md_run(mddev);
3769 break;
3770 case write_pending:
3771 case active_idle:
3772 /* these cannot be set */
3773 break;
3775 if (err)
3776 return err;
3777 else {
3778 sysfs_notify_dirent_safe(mddev->sysfs_state);
3779 return len;
3782 static struct md_sysfs_entry md_array_state =
3783 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3785 static ssize_t
3786 max_corrected_read_errors_show(mddev_t *mddev, char *page) {
3787 return sprintf(page, "%d\n",
3788 atomic_read(&mddev->max_corr_read_errors));
3791 static ssize_t
3792 max_corrected_read_errors_store(mddev_t *mddev, const char *buf, size_t len)
3794 char *e;
3795 unsigned long n = simple_strtoul(buf, &e, 10);
3797 if (*buf && (*e == 0 || *e == '\n')) {
3798 atomic_set(&mddev->max_corr_read_errors, n);
3799 return len;
3801 return -EINVAL;
3804 static struct md_sysfs_entry max_corr_read_errors =
3805 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
3806 max_corrected_read_errors_store);
3808 static ssize_t
3809 null_show(mddev_t *mddev, char *page)
3811 return -EINVAL;
3814 static ssize_t
3815 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
3817 /* buf must be %d:%d\n? giving major and minor numbers */
3818 /* The new device is added to the array.
3819 * If the array has a persistent superblock, we read the
3820 * superblock to initialise info and check validity.
3821 * Otherwise, only checking done is that in bind_rdev_to_array,
3822 * which mainly checks size.
3824 char *e;
3825 int major = simple_strtoul(buf, &e, 10);
3826 int minor;
3827 dev_t dev;
3828 mdk_rdev_t *rdev;
3829 int err;
3831 if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
3832 return -EINVAL;
3833 minor = simple_strtoul(e+1, &e, 10);
3834 if (*e && *e != '\n')
3835 return -EINVAL;
3836 dev = MKDEV(major, minor);
3837 if (major != MAJOR(dev) ||
3838 minor != MINOR(dev))
3839 return -EOVERFLOW;
3842 if (mddev->persistent) {
3843 rdev = md_import_device(dev, mddev->major_version,
3844 mddev->minor_version);
3845 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
3846 mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
3847 mdk_rdev_t, same_set);
3848 err = super_types[mddev->major_version]
3849 .load_super(rdev, rdev0, mddev->minor_version);
3850 if (err < 0)
3851 goto out;
3853 } else if (mddev->external)
3854 rdev = md_import_device(dev, -2, -1);
3855 else
3856 rdev = md_import_device(dev, -1, -1);
3858 if (IS_ERR(rdev))
3859 return PTR_ERR(rdev);
3860 err = bind_rdev_to_array(rdev, mddev);
3861 out:
3862 if (err)
3863 export_rdev(rdev);
3864 return err ? err : len;
3867 static struct md_sysfs_entry md_new_device =
3868 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
3870 static ssize_t
3871 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
3873 char *end;
3874 unsigned long chunk, end_chunk;
3876 if (!mddev->bitmap)
3877 goto out;
3878 /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
3879 while (*buf) {
3880 chunk = end_chunk = simple_strtoul(buf, &end, 0);
3881 if (buf == end) break;
3882 if (*end == '-') { /* range */
3883 buf = end + 1;
3884 end_chunk = simple_strtoul(buf, &end, 0);
3885 if (buf == end) break;
3887 if (*end && !isspace(*end)) break;
3888 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
3889 buf = skip_spaces(end);
3891 bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
3892 out:
3893 return len;
3896 static struct md_sysfs_entry md_bitmap =
3897 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
3899 static ssize_t
3900 size_show(mddev_t *mddev, char *page)
3902 return sprintf(page, "%llu\n",
3903 (unsigned long long)mddev->dev_sectors / 2);
3906 static int update_size(mddev_t *mddev, sector_t num_sectors);
3908 static ssize_t
3909 size_store(mddev_t *mddev, const char *buf, size_t len)
3911 /* If array is inactive, we can reduce the component size, but
3912 * not increase it (except from 0).
3913 * If array is active, we can try an on-line resize
3915 sector_t sectors;
3916 int err = strict_blocks_to_sectors(buf, &sectors);
3918 if (err < 0)
3919 return err;
3920 if (mddev->pers) {
3921 err = update_size(mddev, sectors);
3922 md_update_sb(mddev, 1);
3923 } else {
3924 if (mddev->dev_sectors == 0 ||
3925 mddev->dev_sectors > sectors)
3926 mddev->dev_sectors = sectors;
3927 else
3928 err = -ENOSPC;
3930 return err ? err : len;
3933 static struct md_sysfs_entry md_size =
3934 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
3937 /* Metdata version.
3938 * This is one of
3939 * 'none' for arrays with no metadata (good luck...)
3940 * 'external' for arrays with externally managed metadata,
3941 * or N.M for internally known formats
3943 static ssize_t
3944 metadata_show(mddev_t *mddev, char *page)
3946 if (mddev->persistent)
3947 return sprintf(page, "%d.%d\n",
3948 mddev->major_version, mddev->minor_version);
3949 else if (mddev->external)
3950 return sprintf(page, "external:%s\n", mddev->metadata_type);
3951 else
3952 return sprintf(page, "none\n");
3955 static ssize_t
3956 metadata_store(mddev_t *mddev, const char *buf, size_t len)
3958 int major, minor;
3959 char *e;
3960 /* Changing the details of 'external' metadata is
3961 * always permitted. Otherwise there must be
3962 * no devices attached to the array.
3964 if (mddev->external && strncmp(buf, "external:", 9) == 0)
3966 else if (!list_empty(&mddev->disks))
3967 return -EBUSY;
3969 if (cmd_match(buf, "none")) {
3970 mddev->persistent = 0;
3971 mddev->external = 0;
3972 mddev->major_version = 0;
3973 mddev->minor_version = 90;
3974 return len;
3976 if (strncmp(buf, "external:", 9) == 0) {
3977 size_t namelen = len-9;
3978 if (namelen >= sizeof(mddev->metadata_type))
3979 namelen = sizeof(mddev->metadata_type)-1;
3980 strncpy(mddev->metadata_type, buf+9, namelen);
3981 mddev->metadata_type[namelen] = 0;
3982 if (namelen && mddev->metadata_type[namelen-1] == '\n')
3983 mddev->metadata_type[--namelen] = 0;
3984 mddev->persistent = 0;
3985 mddev->external = 1;
3986 mddev->major_version = 0;
3987 mddev->minor_version = 90;
3988 return len;
3990 major = simple_strtoul(buf, &e, 10);
3991 if (e==buf || *e != '.')
3992 return -EINVAL;
3993 buf = e+1;
3994 minor = simple_strtoul(buf, &e, 10);
3995 if (e==buf || (*e && *e != '\n') )
3996 return -EINVAL;
3997 if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
3998 return -ENOENT;
3999 mddev->major_version = major;
4000 mddev->minor_version = minor;
4001 mddev->persistent = 1;
4002 mddev->external = 0;
4003 return len;
4006 static struct md_sysfs_entry md_metadata =
4007 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
4009 static ssize_t
4010 action_show(mddev_t *mddev, char *page)
4012 char *type = "idle";
4013 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
4014 type = "frozen";
4015 else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4016 (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
4017 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
4018 type = "reshape";
4019 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
4020 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
4021 type = "resync";
4022 else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
4023 type = "check";
4024 else
4025 type = "repair";
4026 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
4027 type = "recover";
4029 return sprintf(page, "%s\n", type);
4032 static void reap_sync_thread(mddev_t *mddev);
4034 static ssize_t
4035 action_store(mddev_t *mddev, const char *page, size_t len)
4037 if (!mddev->pers || !mddev->pers->sync_request)
4038 return -EINVAL;
4040 if (cmd_match(page, "frozen"))
4041 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4042 else
4043 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4045 if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
4046 if (mddev->sync_thread) {
4047 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4048 reap_sync_thread(mddev);
4050 } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
4051 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
4052 return -EBUSY;
4053 else if (cmd_match(page, "resync"))
4054 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4055 else if (cmd_match(page, "recover")) {
4056 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4057 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4058 } else if (cmd_match(page, "reshape")) {
4059 int err;
4060 if (mddev->pers->start_reshape == NULL)
4061 return -EINVAL;
4062 err = mddev->pers->start_reshape(mddev);
4063 if (err)
4064 return err;
4065 sysfs_notify(&mddev->kobj, NULL, "degraded");
4066 } else {
4067 if (cmd_match(page, "check"))
4068 set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4069 else if (!cmd_match(page, "repair"))
4070 return -EINVAL;
4071 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4072 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4074 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4075 md_wakeup_thread(mddev->thread);
4076 sysfs_notify_dirent_safe(mddev->sysfs_action);
4077 return len;
4080 static ssize_t
4081 mismatch_cnt_show(mddev_t *mddev, char *page)
4083 return sprintf(page, "%llu\n",
4084 (unsigned long long) mddev->resync_mismatches);
4087 static struct md_sysfs_entry md_scan_mode =
4088 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4091 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4093 static ssize_t
4094 sync_min_show(mddev_t *mddev, char *page)
4096 return sprintf(page, "%d (%s)\n", speed_min(mddev),
4097 mddev->sync_speed_min ? "local": "system");
4100 static ssize_t
4101 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
4103 int min;
4104 char *e;
4105 if (strncmp(buf, "system", 6)==0) {
4106 mddev->sync_speed_min = 0;
4107 return len;
4109 min = simple_strtoul(buf, &e, 10);
4110 if (buf == e || (*e && *e != '\n') || min <= 0)
4111 return -EINVAL;
4112 mddev->sync_speed_min = min;
4113 return len;
4116 static struct md_sysfs_entry md_sync_min =
4117 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4119 static ssize_t
4120 sync_max_show(mddev_t *mddev, char *page)
4122 return sprintf(page, "%d (%s)\n", speed_max(mddev),
4123 mddev->sync_speed_max ? "local": "system");
4126 static ssize_t
4127 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
4129 int max;
4130 char *e;
4131 if (strncmp(buf, "system", 6)==0) {
4132 mddev->sync_speed_max = 0;
4133 return len;
4135 max = simple_strtoul(buf, &e, 10);
4136 if (buf == e || (*e && *e != '\n') || max <= 0)
4137 return -EINVAL;
4138 mddev->sync_speed_max = max;
4139 return len;
4142 static struct md_sysfs_entry md_sync_max =
4143 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4145 static ssize_t
4146 degraded_show(mddev_t *mddev, char *page)
4148 return sprintf(page, "%d\n", mddev->degraded);
4150 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4152 static ssize_t
4153 sync_force_parallel_show(mddev_t *mddev, char *page)
4155 return sprintf(page, "%d\n", mddev->parallel_resync);
4158 static ssize_t
4159 sync_force_parallel_store(mddev_t *mddev, const char *buf, size_t len)
4161 long n;
4163 if (strict_strtol(buf, 10, &n))
4164 return -EINVAL;
4166 if (n != 0 && n != 1)
4167 return -EINVAL;
4169 mddev->parallel_resync = n;
4171 if (mddev->sync_thread)
4172 wake_up(&resync_wait);
4174 return len;
4177 /* force parallel resync, even with shared block devices */
4178 static struct md_sysfs_entry md_sync_force_parallel =
4179 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4180 sync_force_parallel_show, sync_force_parallel_store);
4182 static ssize_t
4183 sync_speed_show(mddev_t *mddev, char *page)
4185 unsigned long resync, dt, db;
4186 if (mddev->curr_resync == 0)
4187 return sprintf(page, "none\n");
4188 resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4189 dt = (jiffies - mddev->resync_mark) / HZ;
4190 if (!dt) dt++;
4191 db = resync - mddev->resync_mark_cnt;
4192 return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4195 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4197 static ssize_t
4198 sync_completed_show(mddev_t *mddev, char *page)
4200 unsigned long long max_sectors, resync;
4202 if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4203 return sprintf(page, "none\n");
4205 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4206 max_sectors = mddev->resync_max_sectors;
4207 else
4208 max_sectors = mddev->dev_sectors;
4210 resync = mddev->curr_resync_completed;
4211 return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4214 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
4216 static ssize_t
4217 min_sync_show(mddev_t *mddev, char *page)
4219 return sprintf(page, "%llu\n",
4220 (unsigned long long)mddev->resync_min);
4222 static ssize_t
4223 min_sync_store(mddev_t *mddev, const char *buf, size_t len)
4225 unsigned long long min;
4226 if (strict_strtoull(buf, 10, &min))
4227 return -EINVAL;
4228 if (min > mddev->resync_max)
4229 return -EINVAL;
4230 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4231 return -EBUSY;
4233 /* Must be a multiple of chunk_size */
4234 if (mddev->chunk_sectors) {
4235 sector_t temp = min;
4236 if (sector_div(temp, mddev->chunk_sectors))
4237 return -EINVAL;
4239 mddev->resync_min = min;
4241 return len;
4244 static struct md_sysfs_entry md_min_sync =
4245 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4247 static ssize_t
4248 max_sync_show(mddev_t *mddev, char *page)
4250 if (mddev->resync_max == MaxSector)
4251 return sprintf(page, "max\n");
4252 else
4253 return sprintf(page, "%llu\n",
4254 (unsigned long long)mddev->resync_max);
4256 static ssize_t
4257 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
4259 if (strncmp(buf, "max", 3) == 0)
4260 mddev->resync_max = MaxSector;
4261 else {
4262 unsigned long long max;
4263 if (strict_strtoull(buf, 10, &max))
4264 return -EINVAL;
4265 if (max < mddev->resync_min)
4266 return -EINVAL;
4267 if (max < mddev->resync_max &&
4268 mddev->ro == 0 &&
4269 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4270 return -EBUSY;
4272 /* Must be a multiple of chunk_size */
4273 if (mddev->chunk_sectors) {
4274 sector_t temp = max;
4275 if (sector_div(temp, mddev->chunk_sectors))
4276 return -EINVAL;
4278 mddev->resync_max = max;
4280 wake_up(&mddev->recovery_wait);
4281 return len;
4284 static struct md_sysfs_entry md_max_sync =
4285 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4287 static ssize_t
4288 suspend_lo_show(mddev_t *mddev, char *page)
4290 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4293 static ssize_t
4294 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
4296 char *e;
4297 unsigned long long new = simple_strtoull(buf, &e, 10);
4298 unsigned long long old = mddev->suspend_lo;
4300 if (mddev->pers == NULL ||
4301 mddev->pers->quiesce == NULL)
4302 return -EINVAL;
4303 if (buf == e || (*e && *e != '\n'))
4304 return -EINVAL;
4306 mddev->suspend_lo = new;
4307 if (new >= old)
4308 /* Shrinking suspended region */
4309 mddev->pers->quiesce(mddev, 2);
4310 else {
4311 /* Expanding suspended region - need to wait */
4312 mddev->pers->quiesce(mddev, 1);
4313 mddev->pers->quiesce(mddev, 0);
4315 return len;
4317 static struct md_sysfs_entry md_suspend_lo =
4318 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4321 static ssize_t
4322 suspend_hi_show(mddev_t *mddev, char *page)
4324 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4327 static ssize_t
4328 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
4330 char *e;
4331 unsigned long long new = simple_strtoull(buf, &e, 10);
4332 unsigned long long old = mddev->suspend_hi;
4334 if (mddev->pers == NULL ||
4335 mddev->pers->quiesce == NULL)
4336 return -EINVAL;
4337 if (buf == e || (*e && *e != '\n'))
4338 return -EINVAL;
4340 mddev->suspend_hi = new;
4341 if (new <= old)
4342 /* Shrinking suspended region */
4343 mddev->pers->quiesce(mddev, 2);
4344 else {
4345 /* Expanding suspended region - need to wait */
4346 mddev->pers->quiesce(mddev, 1);
4347 mddev->pers->quiesce(mddev, 0);
4349 return len;
4351 static struct md_sysfs_entry md_suspend_hi =
4352 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4354 static ssize_t
4355 reshape_position_show(mddev_t *mddev, char *page)
4357 if (mddev->reshape_position != MaxSector)
4358 return sprintf(page, "%llu\n",
4359 (unsigned long long)mddev->reshape_position);
4360 strcpy(page, "none\n");
4361 return 5;
4364 static ssize_t
4365 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
4367 char *e;
4368 unsigned long long new = simple_strtoull(buf, &e, 10);
4369 if (mddev->pers)
4370 return -EBUSY;
4371 if (buf == e || (*e && *e != '\n'))
4372 return -EINVAL;
4373 mddev->reshape_position = new;
4374 mddev->delta_disks = 0;
4375 mddev->new_level = mddev->level;
4376 mddev->new_layout = mddev->layout;
4377 mddev->new_chunk_sectors = mddev->chunk_sectors;
4378 return len;
4381 static struct md_sysfs_entry md_reshape_position =
4382 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4383 reshape_position_store);
4385 static ssize_t
4386 array_size_show(mddev_t *mddev, char *page)
4388 if (mddev->external_size)
4389 return sprintf(page, "%llu\n",
4390 (unsigned long long)mddev->array_sectors/2);
4391 else
4392 return sprintf(page, "default\n");
4395 static ssize_t
4396 array_size_store(mddev_t *mddev, const char *buf, size_t len)
4398 sector_t sectors;
4400 if (strncmp(buf, "default", 7) == 0) {
4401 if (mddev->pers)
4402 sectors = mddev->pers->size(mddev, 0, 0);
4403 else
4404 sectors = mddev->array_sectors;
4406 mddev->external_size = 0;
4407 } else {
4408 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4409 return -EINVAL;
4410 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4411 return -E2BIG;
4413 mddev->external_size = 1;
4416 mddev->array_sectors = sectors;
4417 if (mddev->pers) {
4418 set_capacity(mddev->gendisk, mddev->array_sectors);
4419 revalidate_disk(mddev->gendisk);
4421 return len;
4424 static struct md_sysfs_entry md_array_size =
4425 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4426 array_size_store);
4428 static struct attribute *md_default_attrs[] = {
4429 &md_level.attr,
4430 &md_layout.attr,
4431 &md_raid_disks.attr,
4432 &md_chunk_size.attr,
4433 &md_size.attr,
4434 &md_resync_start.attr,
4435 &md_metadata.attr,
4436 &md_new_device.attr,
4437 &md_safe_delay.attr,
4438 &md_array_state.attr,
4439 &md_reshape_position.attr,
4440 &md_array_size.attr,
4441 &max_corr_read_errors.attr,
4442 NULL,
4445 static struct attribute *md_redundancy_attrs[] = {
4446 &md_scan_mode.attr,
4447 &md_mismatches.attr,
4448 &md_sync_min.attr,
4449 &md_sync_max.attr,
4450 &md_sync_speed.attr,
4451 &md_sync_force_parallel.attr,
4452 &md_sync_completed.attr,
4453 &md_min_sync.attr,
4454 &md_max_sync.attr,
4455 &md_suspend_lo.attr,
4456 &md_suspend_hi.attr,
4457 &md_bitmap.attr,
4458 &md_degraded.attr,
4459 NULL,
4461 static struct attribute_group md_redundancy_group = {
4462 .name = NULL,
4463 .attrs = md_redundancy_attrs,
4467 static ssize_t
4468 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4470 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4471 mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
4472 ssize_t rv;
4474 if (!entry->show)
4475 return -EIO;
4476 rv = mddev_lock(mddev);
4477 if (!rv) {
4478 rv = entry->show(mddev, page);
4479 mddev_unlock(mddev);
4481 return rv;
4484 static ssize_t
4485 md_attr_store(struct kobject *kobj, struct attribute *attr,
4486 const char *page, size_t length)
4488 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4489 mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
4490 ssize_t rv;
4492 if (!entry->store)
4493 return -EIO;
4494 if (!capable(CAP_SYS_ADMIN))
4495 return -EACCES;
4496 rv = mddev_lock(mddev);
4497 if (mddev->hold_active == UNTIL_IOCTL)
4498 mddev->hold_active = 0;
4499 if (!rv) {
4500 rv = entry->store(mddev, page, length);
4501 mddev_unlock(mddev);
4503 return rv;
4506 static void md_free(struct kobject *ko)
4508 mddev_t *mddev = container_of(ko, mddev_t, kobj);
4510 if (mddev->sysfs_state)
4511 sysfs_put(mddev->sysfs_state);
4513 if (mddev->gendisk) {
4514 del_gendisk(mddev->gendisk);
4515 put_disk(mddev->gendisk);
4517 if (mddev->queue)
4518 blk_cleanup_queue(mddev->queue);
4520 kfree(mddev);
4523 static const struct sysfs_ops md_sysfs_ops = {
4524 .show = md_attr_show,
4525 .store = md_attr_store,
4527 static struct kobj_type md_ktype = {
4528 .release = md_free,
4529 .sysfs_ops = &md_sysfs_ops,
4530 .default_attrs = md_default_attrs,
4533 int mdp_major = 0;
4535 static void mddev_delayed_delete(struct work_struct *ws)
4537 mddev_t *mddev = container_of(ws, mddev_t, del_work);
4539 sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4540 kobject_del(&mddev->kobj);
4541 kobject_put(&mddev->kobj);
4544 static int md_alloc(dev_t dev, char *name)
4546 static DEFINE_MUTEX(disks_mutex);
4547 mddev_t *mddev = mddev_find(dev);
4548 struct gendisk *disk;
4549 int partitioned;
4550 int shift;
4551 int unit;
4552 int error;
4554 if (!mddev)
4555 return -ENODEV;
4557 partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4558 shift = partitioned ? MdpMinorShift : 0;
4559 unit = MINOR(mddev->unit) >> shift;
4561 /* wait for any previous instance of this device to be
4562 * completely removed (mddev_delayed_delete).
4564 flush_workqueue(md_misc_wq);
4566 mutex_lock(&disks_mutex);
4567 error = -EEXIST;
4568 if (mddev->gendisk)
4569 goto abort;
4571 if (name) {
4572 /* Need to ensure that 'name' is not a duplicate.
4574 mddev_t *mddev2;
4575 spin_lock(&all_mddevs_lock);
4577 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4578 if (mddev2->gendisk &&
4579 strcmp(mddev2->gendisk->disk_name, name) == 0) {
4580 spin_unlock(&all_mddevs_lock);
4581 goto abort;
4583 spin_unlock(&all_mddevs_lock);
4586 error = -ENOMEM;
4587 mddev->queue = blk_alloc_queue(GFP_KERNEL);
4588 if (!mddev->queue)
4589 goto abort;
4590 mddev->queue->queuedata = mddev;
4592 blk_queue_make_request(mddev->queue, md_make_request);
4594 disk = alloc_disk(1 << shift);
4595 if (!disk) {
4596 blk_cleanup_queue(mddev->queue);
4597 mddev->queue = NULL;
4598 goto abort;
4600 disk->major = MAJOR(mddev->unit);
4601 disk->first_minor = unit << shift;
4602 if (name)
4603 strcpy(disk->disk_name, name);
4604 else if (partitioned)
4605 sprintf(disk->disk_name, "md_d%d", unit);
4606 else
4607 sprintf(disk->disk_name, "md%d", unit);
4608 disk->fops = &md_fops;
4609 disk->private_data = mddev;
4610 disk->queue = mddev->queue;
4611 blk_queue_flush(mddev->queue, REQ_FLUSH | REQ_FUA);
4612 /* Allow extended partitions. This makes the
4613 * 'mdp' device redundant, but we can't really
4614 * remove it now.
4616 disk->flags |= GENHD_FL_EXT_DEVT;
4617 mddev->gendisk = disk;
4618 /* As soon as we call add_disk(), another thread could get
4619 * through to md_open, so make sure it doesn't get too far
4621 mutex_lock(&mddev->open_mutex);
4622 add_disk(disk);
4624 error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4625 &disk_to_dev(disk)->kobj, "%s", "md");
4626 if (error) {
4627 /* This isn't possible, but as kobject_init_and_add is marked
4628 * __must_check, we must do something with the result
4630 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4631 disk->disk_name);
4632 error = 0;
4634 if (mddev->kobj.sd &&
4635 sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4636 printk(KERN_DEBUG "pointless warning\n");
4637 mutex_unlock(&mddev->open_mutex);
4638 abort:
4639 mutex_unlock(&disks_mutex);
4640 if (!error && mddev->kobj.sd) {
4641 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4642 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4644 mddev_put(mddev);
4645 return error;
4648 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4650 md_alloc(dev, NULL);
4651 return NULL;
4654 static int add_named_array(const char *val, struct kernel_param *kp)
4656 /* val must be "md_*" where * is not all digits.
4657 * We allocate an array with a large free minor number, and
4658 * set the name to val. val must not already be an active name.
4660 int len = strlen(val);
4661 char buf[DISK_NAME_LEN];
4663 while (len && val[len-1] == '\n')
4664 len--;
4665 if (len >= DISK_NAME_LEN)
4666 return -E2BIG;
4667 strlcpy(buf, val, len+1);
4668 if (strncmp(buf, "md_", 3) != 0)
4669 return -EINVAL;
4670 return md_alloc(0, buf);
4673 static void md_safemode_timeout(unsigned long data)
4675 mddev_t *mddev = (mddev_t *) data;
4677 if (!atomic_read(&mddev->writes_pending)) {
4678 mddev->safemode = 1;
4679 if (mddev->external)
4680 sysfs_notify_dirent_safe(mddev->sysfs_state);
4682 md_wakeup_thread(mddev->thread);
4685 static int start_dirty_degraded;
4687 int md_run(mddev_t *mddev)
4689 int err;
4690 mdk_rdev_t *rdev;
4691 struct mdk_personality *pers;
4693 if (list_empty(&mddev->disks))
4694 /* cannot run an array with no devices.. */
4695 return -EINVAL;
4697 if (mddev->pers)
4698 return -EBUSY;
4699 /* Cannot run until previous stop completes properly */
4700 if (mddev->sysfs_active)
4701 return -EBUSY;
4704 * Analyze all RAID superblock(s)
4706 if (!mddev->raid_disks) {
4707 if (!mddev->persistent)
4708 return -EINVAL;
4709 analyze_sbs(mddev);
4712 if (mddev->level != LEVEL_NONE)
4713 request_module("md-level-%d", mddev->level);
4714 else if (mddev->clevel[0])
4715 request_module("md-%s", mddev->clevel);
4718 * Drop all container device buffers, from now on
4719 * the only valid external interface is through the md
4720 * device.
4722 list_for_each_entry(rdev, &mddev->disks, same_set) {
4723 if (test_bit(Faulty, &rdev->flags))
4724 continue;
4725 sync_blockdev(rdev->bdev);
4726 invalidate_bdev(rdev->bdev);
4728 /* perform some consistency tests on the device.
4729 * We don't want the data to overlap the metadata,
4730 * Internal Bitmap issues have been handled elsewhere.
4732 if (rdev->meta_bdev) {
4733 /* Nothing to check */;
4734 } else if (rdev->data_offset < rdev->sb_start) {
4735 if (mddev->dev_sectors &&
4736 rdev->data_offset + mddev->dev_sectors
4737 > rdev->sb_start) {
4738 printk("md: %s: data overlaps metadata\n",
4739 mdname(mddev));
4740 return -EINVAL;
4742 } else {
4743 if (rdev->sb_start + rdev->sb_size/512
4744 > rdev->data_offset) {
4745 printk("md: %s: metadata overlaps data\n",
4746 mdname(mddev));
4747 return -EINVAL;
4750 sysfs_notify_dirent_safe(rdev->sysfs_state);
4753 if (mddev->bio_set == NULL)
4754 mddev->bio_set = bioset_create(BIO_POOL_SIZE,
4755 sizeof(mddev_t *));
4757 spin_lock(&pers_lock);
4758 pers = find_pers(mddev->level, mddev->clevel);
4759 if (!pers || !try_module_get(pers->owner)) {
4760 spin_unlock(&pers_lock);
4761 if (mddev->level != LEVEL_NONE)
4762 printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
4763 mddev->level);
4764 else
4765 printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
4766 mddev->clevel);
4767 return -EINVAL;
4769 mddev->pers = pers;
4770 spin_unlock(&pers_lock);
4771 if (mddev->level != pers->level) {
4772 mddev->level = pers->level;
4773 mddev->new_level = pers->level;
4775 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
4777 if (mddev->reshape_position != MaxSector &&
4778 pers->start_reshape == NULL) {
4779 /* This personality cannot handle reshaping... */
4780 mddev->pers = NULL;
4781 module_put(pers->owner);
4782 return -EINVAL;
4785 if (pers->sync_request) {
4786 /* Warn if this is a potentially silly
4787 * configuration.
4789 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4790 mdk_rdev_t *rdev2;
4791 int warned = 0;
4793 list_for_each_entry(rdev, &mddev->disks, same_set)
4794 list_for_each_entry(rdev2, &mddev->disks, same_set) {
4795 if (rdev < rdev2 &&
4796 rdev->bdev->bd_contains ==
4797 rdev2->bdev->bd_contains) {
4798 printk(KERN_WARNING
4799 "%s: WARNING: %s appears to be"
4800 " on the same physical disk as"
4801 " %s.\n",
4802 mdname(mddev),
4803 bdevname(rdev->bdev,b),
4804 bdevname(rdev2->bdev,b2));
4805 warned = 1;
4809 if (warned)
4810 printk(KERN_WARNING
4811 "True protection against single-disk"
4812 " failure might be compromised.\n");
4815 mddev->recovery = 0;
4816 /* may be over-ridden by personality */
4817 mddev->resync_max_sectors = mddev->dev_sectors;
4819 mddev->ok_start_degraded = start_dirty_degraded;
4821 if (start_readonly && mddev->ro == 0)
4822 mddev->ro = 2; /* read-only, but switch on first write */
4824 err = mddev->pers->run(mddev);
4825 if (err)
4826 printk(KERN_ERR "md: pers->run() failed ...\n");
4827 else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
4828 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
4829 " but 'external_size' not in effect?\n", __func__);
4830 printk(KERN_ERR
4831 "md: invalid array_size %llu > default size %llu\n",
4832 (unsigned long long)mddev->array_sectors / 2,
4833 (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
4834 err = -EINVAL;
4835 mddev->pers->stop(mddev);
4837 if (err == 0 && mddev->pers->sync_request) {
4838 err = bitmap_create(mddev);
4839 if (err) {
4840 printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
4841 mdname(mddev), err);
4842 mddev->pers->stop(mddev);
4845 if (err) {
4846 module_put(mddev->pers->owner);
4847 mddev->pers = NULL;
4848 bitmap_destroy(mddev);
4849 return err;
4851 if (mddev->pers->sync_request) {
4852 if (mddev->kobj.sd &&
4853 sysfs_create_group(&mddev->kobj, &md_redundancy_group))
4854 printk(KERN_WARNING
4855 "md: cannot register extra attributes for %s\n",
4856 mdname(mddev));
4857 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
4858 } else if (mddev->ro == 2) /* auto-readonly not meaningful */
4859 mddev->ro = 0;
4861 atomic_set(&mddev->writes_pending,0);
4862 atomic_set(&mddev->max_corr_read_errors,
4863 MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
4864 mddev->safemode = 0;
4865 mddev->safemode_timer.function = md_safemode_timeout;
4866 mddev->safemode_timer.data = (unsigned long) mddev;
4867 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
4868 mddev->in_sync = 1;
4869 smp_wmb();
4870 mddev->ready = 1;
4871 list_for_each_entry(rdev, &mddev->disks, same_set)
4872 if (rdev->raid_disk >= 0)
4873 if (sysfs_link_rdev(mddev, rdev))
4874 /* failure here is OK */;
4876 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4878 if (mddev->flags)
4879 md_update_sb(mddev, 0);
4881 md_new_event(mddev);
4882 sysfs_notify_dirent_safe(mddev->sysfs_state);
4883 sysfs_notify_dirent_safe(mddev->sysfs_action);
4884 sysfs_notify(&mddev->kobj, NULL, "degraded");
4885 return 0;
4887 EXPORT_SYMBOL_GPL(md_run);
4889 static int do_md_run(mddev_t *mddev)
4891 int err;
4893 err = md_run(mddev);
4894 if (err)
4895 goto out;
4896 err = bitmap_load(mddev);
4897 if (err) {
4898 bitmap_destroy(mddev);
4899 goto out;
4902 md_wakeup_thread(mddev->thread);
4903 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
4905 set_capacity(mddev->gendisk, mddev->array_sectors);
4906 revalidate_disk(mddev->gendisk);
4907 mddev->changed = 1;
4908 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4909 out:
4910 return err;
4913 static int restart_array(mddev_t *mddev)
4915 struct gendisk *disk = mddev->gendisk;
4917 /* Complain if it has no devices */
4918 if (list_empty(&mddev->disks))
4919 return -ENXIO;
4920 if (!mddev->pers)
4921 return -EINVAL;
4922 if (!mddev->ro)
4923 return -EBUSY;
4924 mddev->safemode = 0;
4925 mddev->ro = 0;
4926 set_disk_ro(disk, 0);
4927 printk(KERN_INFO "md: %s switched to read-write mode.\n",
4928 mdname(mddev));
4929 /* Kick recovery or resync if necessary */
4930 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4931 md_wakeup_thread(mddev->thread);
4932 md_wakeup_thread(mddev->sync_thread);
4933 sysfs_notify_dirent_safe(mddev->sysfs_state);
4934 return 0;
4937 /* similar to deny_write_access, but accounts for our holding a reference
4938 * to the file ourselves */
4939 static int deny_bitmap_write_access(struct file * file)
4941 struct inode *inode = file->f_mapping->host;
4943 spin_lock(&inode->i_lock);
4944 if (atomic_read(&inode->i_writecount) > 1) {
4945 spin_unlock(&inode->i_lock);
4946 return -ETXTBSY;
4948 atomic_set(&inode->i_writecount, -1);
4949 spin_unlock(&inode->i_lock);
4951 return 0;
4954 void restore_bitmap_write_access(struct file *file)
4956 struct inode *inode = file->f_mapping->host;
4958 spin_lock(&inode->i_lock);
4959 atomic_set(&inode->i_writecount, 1);
4960 spin_unlock(&inode->i_lock);
4963 static void md_clean(mddev_t *mddev)
4965 mddev->array_sectors = 0;
4966 mddev->external_size = 0;
4967 mddev->dev_sectors = 0;
4968 mddev->raid_disks = 0;
4969 mddev->recovery_cp = 0;
4970 mddev->resync_min = 0;
4971 mddev->resync_max = MaxSector;
4972 mddev->reshape_position = MaxSector;
4973 mddev->external = 0;
4974 mddev->persistent = 0;
4975 mddev->level = LEVEL_NONE;
4976 mddev->clevel[0] = 0;
4977 mddev->flags = 0;
4978 mddev->ro = 0;
4979 mddev->metadata_type[0] = 0;
4980 mddev->chunk_sectors = 0;
4981 mddev->ctime = mddev->utime = 0;
4982 mddev->layout = 0;
4983 mddev->max_disks = 0;
4984 mddev->events = 0;
4985 mddev->can_decrease_events = 0;
4986 mddev->delta_disks = 0;
4987 mddev->new_level = LEVEL_NONE;
4988 mddev->new_layout = 0;
4989 mddev->new_chunk_sectors = 0;
4990 mddev->curr_resync = 0;
4991 mddev->resync_mismatches = 0;
4992 mddev->suspend_lo = mddev->suspend_hi = 0;
4993 mddev->sync_speed_min = mddev->sync_speed_max = 0;
4994 mddev->recovery = 0;
4995 mddev->in_sync = 0;
4996 mddev->changed = 0;
4997 mddev->degraded = 0;
4998 mddev->safemode = 0;
4999 mddev->bitmap_info.offset = 0;
5000 mddev->bitmap_info.default_offset = 0;
5001 mddev->bitmap_info.chunksize = 0;
5002 mddev->bitmap_info.daemon_sleep = 0;
5003 mddev->bitmap_info.max_write_behind = 0;
5006 static void __md_stop_writes(mddev_t *mddev)
5008 if (mddev->sync_thread) {
5009 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5010 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
5011 reap_sync_thread(mddev);
5014 del_timer_sync(&mddev->safemode_timer);
5016 bitmap_flush(mddev);
5017 md_super_wait(mddev);
5019 if (!mddev->in_sync || mddev->flags) {
5020 /* mark array as shutdown cleanly */
5021 mddev->in_sync = 1;
5022 md_update_sb(mddev, 1);
5026 void md_stop_writes(mddev_t *mddev)
5028 mddev_lock(mddev);
5029 __md_stop_writes(mddev);
5030 mddev_unlock(mddev);
5032 EXPORT_SYMBOL_GPL(md_stop_writes);
5034 void md_stop(mddev_t *mddev)
5036 mddev->ready = 0;
5037 mddev->pers->stop(mddev);
5038 if (mddev->pers->sync_request && mddev->to_remove == NULL)
5039 mddev->to_remove = &md_redundancy_group;
5040 module_put(mddev->pers->owner);
5041 mddev->pers = NULL;
5042 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5044 EXPORT_SYMBOL_GPL(md_stop);
5046 static int md_set_readonly(mddev_t *mddev, int is_open)
5048 int err = 0;
5049 mutex_lock(&mddev->open_mutex);
5050 if (atomic_read(&mddev->openers) > is_open) {
5051 printk("md: %s still in use.\n",mdname(mddev));
5052 err = -EBUSY;
5053 goto out;
5055 if (mddev->pers) {
5056 __md_stop_writes(mddev);
5058 err = -ENXIO;
5059 if (mddev->ro==1)
5060 goto out;
5061 mddev->ro = 1;
5062 set_disk_ro(mddev->gendisk, 1);
5063 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5064 sysfs_notify_dirent_safe(mddev->sysfs_state);
5065 err = 0;
5067 out:
5068 mutex_unlock(&mddev->open_mutex);
5069 return err;
5072 /* mode:
5073 * 0 - completely stop and dis-assemble array
5074 * 2 - stop but do not disassemble array
5076 static int do_md_stop(mddev_t * mddev, int mode, int is_open)
5078 struct gendisk *disk = mddev->gendisk;
5079 mdk_rdev_t *rdev;
5081 mutex_lock(&mddev->open_mutex);
5082 if (atomic_read(&mddev->openers) > is_open ||
5083 mddev->sysfs_active) {
5084 printk("md: %s still in use.\n",mdname(mddev));
5085 mutex_unlock(&mddev->open_mutex);
5086 return -EBUSY;
5089 if (mddev->pers) {
5090 if (mddev->ro)
5091 set_disk_ro(disk, 0);
5093 __md_stop_writes(mddev);
5094 md_stop(mddev);
5095 mddev->queue->merge_bvec_fn = NULL;
5096 mddev->queue->backing_dev_info.congested_fn = NULL;
5098 /* tell userspace to handle 'inactive' */
5099 sysfs_notify_dirent_safe(mddev->sysfs_state);
5101 list_for_each_entry(rdev, &mddev->disks, same_set)
5102 if (rdev->raid_disk >= 0)
5103 sysfs_unlink_rdev(mddev, rdev);
5105 set_capacity(disk, 0);
5106 mutex_unlock(&mddev->open_mutex);
5107 mddev->changed = 1;
5108 revalidate_disk(disk);
5110 if (mddev->ro)
5111 mddev->ro = 0;
5112 } else
5113 mutex_unlock(&mddev->open_mutex);
5115 * Free resources if final stop
5117 if (mode == 0) {
5118 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
5120 bitmap_destroy(mddev);
5121 if (mddev->bitmap_info.file) {
5122 restore_bitmap_write_access(mddev->bitmap_info.file);
5123 fput(mddev->bitmap_info.file);
5124 mddev->bitmap_info.file = NULL;
5126 mddev->bitmap_info.offset = 0;
5128 export_array(mddev);
5130 md_clean(mddev);
5131 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5132 if (mddev->hold_active == UNTIL_STOP)
5133 mddev->hold_active = 0;
5135 blk_integrity_unregister(disk);
5136 md_new_event(mddev);
5137 sysfs_notify_dirent_safe(mddev->sysfs_state);
5138 return 0;
5141 #ifndef MODULE
5142 static void autorun_array(mddev_t *mddev)
5144 mdk_rdev_t *rdev;
5145 int err;
5147 if (list_empty(&mddev->disks))
5148 return;
5150 printk(KERN_INFO "md: running: ");
5152 list_for_each_entry(rdev, &mddev->disks, same_set) {
5153 char b[BDEVNAME_SIZE];
5154 printk("<%s>", bdevname(rdev->bdev,b));
5156 printk("\n");
5158 err = do_md_run(mddev);
5159 if (err) {
5160 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
5161 do_md_stop(mddev, 0, 0);
5166 * lets try to run arrays based on all disks that have arrived
5167 * until now. (those are in pending_raid_disks)
5169 * the method: pick the first pending disk, collect all disks with
5170 * the same UUID, remove all from the pending list and put them into
5171 * the 'same_array' list. Then order this list based on superblock
5172 * update time (freshest comes first), kick out 'old' disks and
5173 * compare superblocks. If everything's fine then run it.
5175 * If "unit" is allocated, then bump its reference count
5177 static void autorun_devices(int part)
5179 mdk_rdev_t *rdev0, *rdev, *tmp;
5180 mddev_t *mddev;
5181 char b[BDEVNAME_SIZE];
5183 printk(KERN_INFO "md: autorun ...\n");
5184 while (!list_empty(&pending_raid_disks)) {
5185 int unit;
5186 dev_t dev;
5187 LIST_HEAD(candidates);
5188 rdev0 = list_entry(pending_raid_disks.next,
5189 mdk_rdev_t, same_set);
5191 printk(KERN_INFO "md: considering %s ...\n",
5192 bdevname(rdev0->bdev,b));
5193 INIT_LIST_HEAD(&candidates);
5194 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
5195 if (super_90_load(rdev, rdev0, 0) >= 0) {
5196 printk(KERN_INFO "md: adding %s ...\n",
5197 bdevname(rdev->bdev,b));
5198 list_move(&rdev->same_set, &candidates);
5201 * now we have a set of devices, with all of them having
5202 * mostly sane superblocks. It's time to allocate the
5203 * mddev.
5205 if (part) {
5206 dev = MKDEV(mdp_major,
5207 rdev0->preferred_minor << MdpMinorShift);
5208 unit = MINOR(dev) >> MdpMinorShift;
5209 } else {
5210 dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
5211 unit = MINOR(dev);
5213 if (rdev0->preferred_minor != unit) {
5214 printk(KERN_INFO "md: unit number in %s is bad: %d\n",
5215 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
5216 break;
5219 md_probe(dev, NULL, NULL);
5220 mddev = mddev_find(dev);
5221 if (!mddev || !mddev->gendisk) {
5222 if (mddev)
5223 mddev_put(mddev);
5224 printk(KERN_ERR
5225 "md: cannot allocate memory for md drive.\n");
5226 break;
5228 if (mddev_lock(mddev))
5229 printk(KERN_WARNING "md: %s locked, cannot run\n",
5230 mdname(mddev));
5231 else if (mddev->raid_disks || mddev->major_version
5232 || !list_empty(&mddev->disks)) {
5233 printk(KERN_WARNING
5234 "md: %s already running, cannot run %s\n",
5235 mdname(mddev), bdevname(rdev0->bdev,b));
5236 mddev_unlock(mddev);
5237 } else {
5238 printk(KERN_INFO "md: created %s\n", mdname(mddev));
5239 mddev->persistent = 1;
5240 rdev_for_each_list(rdev, tmp, &candidates) {
5241 list_del_init(&rdev->same_set);
5242 if (bind_rdev_to_array(rdev, mddev))
5243 export_rdev(rdev);
5245 autorun_array(mddev);
5246 mddev_unlock(mddev);
5248 /* on success, candidates will be empty, on error
5249 * it won't...
5251 rdev_for_each_list(rdev, tmp, &candidates) {
5252 list_del_init(&rdev->same_set);
5253 export_rdev(rdev);
5255 mddev_put(mddev);
5257 printk(KERN_INFO "md: ... autorun DONE.\n");
5259 #endif /* !MODULE */
5261 static int get_version(void __user * arg)
5263 mdu_version_t ver;
5265 ver.major = MD_MAJOR_VERSION;
5266 ver.minor = MD_MINOR_VERSION;
5267 ver.patchlevel = MD_PATCHLEVEL_VERSION;
5269 if (copy_to_user(arg, &ver, sizeof(ver)))
5270 return -EFAULT;
5272 return 0;
5275 static int get_array_info(mddev_t * mddev, void __user * arg)
5277 mdu_array_info_t info;
5278 int nr,working,insync,failed,spare;
5279 mdk_rdev_t *rdev;
5281 nr=working=insync=failed=spare=0;
5282 list_for_each_entry(rdev, &mddev->disks, same_set) {
5283 nr++;
5284 if (test_bit(Faulty, &rdev->flags))
5285 failed++;
5286 else {
5287 working++;
5288 if (test_bit(In_sync, &rdev->flags))
5289 insync++;
5290 else
5291 spare++;
5295 info.major_version = mddev->major_version;
5296 info.minor_version = mddev->minor_version;
5297 info.patch_version = MD_PATCHLEVEL_VERSION;
5298 info.ctime = mddev->ctime;
5299 info.level = mddev->level;
5300 info.size = mddev->dev_sectors / 2;
5301 if (info.size != mddev->dev_sectors / 2) /* overflow */
5302 info.size = -1;
5303 info.nr_disks = nr;
5304 info.raid_disks = mddev->raid_disks;
5305 info.md_minor = mddev->md_minor;
5306 info.not_persistent= !mddev->persistent;
5308 info.utime = mddev->utime;
5309 info.state = 0;
5310 if (mddev->in_sync)
5311 info.state = (1<<MD_SB_CLEAN);
5312 if (mddev->bitmap && mddev->bitmap_info.offset)
5313 info.state = (1<<MD_SB_BITMAP_PRESENT);
5314 info.active_disks = insync;
5315 info.working_disks = working;
5316 info.failed_disks = failed;
5317 info.spare_disks = spare;
5319 info.layout = mddev->layout;
5320 info.chunk_size = mddev->chunk_sectors << 9;
5322 if (copy_to_user(arg, &info, sizeof(info)))
5323 return -EFAULT;
5325 return 0;
5328 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
5330 mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5331 char *ptr, *buf = NULL;
5332 int err = -ENOMEM;
5334 if (md_allow_write(mddev))
5335 file = kmalloc(sizeof(*file), GFP_NOIO);
5336 else
5337 file = kmalloc(sizeof(*file), GFP_KERNEL);
5339 if (!file)
5340 goto out;
5342 /* bitmap disabled, zero the first byte and copy out */
5343 if (!mddev->bitmap || !mddev->bitmap->file) {
5344 file->pathname[0] = '\0';
5345 goto copy_out;
5348 buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
5349 if (!buf)
5350 goto out;
5352 ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
5353 if (IS_ERR(ptr))
5354 goto out;
5356 strcpy(file->pathname, ptr);
5358 copy_out:
5359 err = 0;
5360 if (copy_to_user(arg, file, sizeof(*file)))
5361 err = -EFAULT;
5362 out:
5363 kfree(buf);
5364 kfree(file);
5365 return err;
5368 static int get_disk_info(mddev_t * mddev, void __user * arg)
5370 mdu_disk_info_t info;
5371 mdk_rdev_t *rdev;
5373 if (copy_from_user(&info, arg, sizeof(info)))
5374 return -EFAULT;
5376 rdev = find_rdev_nr(mddev, info.number);
5377 if (rdev) {
5378 info.major = MAJOR(rdev->bdev->bd_dev);
5379 info.minor = MINOR(rdev->bdev->bd_dev);
5380 info.raid_disk = rdev->raid_disk;
5381 info.state = 0;
5382 if (test_bit(Faulty, &rdev->flags))
5383 info.state |= (1<<MD_DISK_FAULTY);
5384 else if (test_bit(In_sync, &rdev->flags)) {
5385 info.state |= (1<<MD_DISK_ACTIVE);
5386 info.state |= (1<<MD_DISK_SYNC);
5388 if (test_bit(WriteMostly, &rdev->flags))
5389 info.state |= (1<<MD_DISK_WRITEMOSTLY);
5390 } else {
5391 info.major = info.minor = 0;
5392 info.raid_disk = -1;
5393 info.state = (1<<MD_DISK_REMOVED);
5396 if (copy_to_user(arg, &info, sizeof(info)))
5397 return -EFAULT;
5399 return 0;
5402 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
5404 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5405 mdk_rdev_t *rdev;
5406 dev_t dev = MKDEV(info->major,info->minor);
5408 if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5409 return -EOVERFLOW;
5411 if (!mddev->raid_disks) {
5412 int err;
5413 /* expecting a device which has a superblock */
5414 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5415 if (IS_ERR(rdev)) {
5416 printk(KERN_WARNING
5417 "md: md_import_device returned %ld\n",
5418 PTR_ERR(rdev));
5419 return PTR_ERR(rdev);
5421 if (!list_empty(&mddev->disks)) {
5422 mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
5423 mdk_rdev_t, same_set);
5424 err = super_types[mddev->major_version]
5425 .load_super(rdev, rdev0, mddev->minor_version);
5426 if (err < 0) {
5427 printk(KERN_WARNING
5428 "md: %s has different UUID to %s\n",
5429 bdevname(rdev->bdev,b),
5430 bdevname(rdev0->bdev,b2));
5431 export_rdev(rdev);
5432 return -EINVAL;
5435 err = bind_rdev_to_array(rdev, mddev);
5436 if (err)
5437 export_rdev(rdev);
5438 return err;
5442 * add_new_disk can be used once the array is assembled
5443 * to add "hot spares". They must already have a superblock
5444 * written
5446 if (mddev->pers) {
5447 int err;
5448 if (!mddev->pers->hot_add_disk) {
5449 printk(KERN_WARNING
5450 "%s: personality does not support diskops!\n",
5451 mdname(mddev));
5452 return -EINVAL;
5454 if (mddev->persistent)
5455 rdev = md_import_device(dev, mddev->major_version,
5456 mddev->minor_version);
5457 else
5458 rdev = md_import_device(dev, -1, -1);
5459 if (IS_ERR(rdev)) {
5460 printk(KERN_WARNING
5461 "md: md_import_device returned %ld\n",
5462 PTR_ERR(rdev));
5463 return PTR_ERR(rdev);
5465 /* set saved_raid_disk if appropriate */
5466 if (!mddev->persistent) {
5467 if (info->state & (1<<MD_DISK_SYNC) &&
5468 info->raid_disk < mddev->raid_disks) {
5469 rdev->raid_disk = info->raid_disk;
5470 set_bit(In_sync, &rdev->flags);
5471 } else
5472 rdev->raid_disk = -1;
5473 } else
5474 super_types[mddev->major_version].
5475 validate_super(mddev, rdev);
5476 if ((info->state & (1<<MD_DISK_SYNC)) &&
5477 (!test_bit(In_sync, &rdev->flags) ||
5478 rdev->raid_disk != info->raid_disk)) {
5479 /* This was a hot-add request, but events doesn't
5480 * match, so reject it.
5482 export_rdev(rdev);
5483 return -EINVAL;
5486 if (test_bit(In_sync, &rdev->flags))
5487 rdev->saved_raid_disk = rdev->raid_disk;
5488 else
5489 rdev->saved_raid_disk = -1;
5491 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5492 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5493 set_bit(WriteMostly, &rdev->flags);
5494 else
5495 clear_bit(WriteMostly, &rdev->flags);
5497 rdev->raid_disk = -1;
5498 err = bind_rdev_to_array(rdev, mddev);
5499 if (!err && !mddev->pers->hot_remove_disk) {
5500 /* If there is hot_add_disk but no hot_remove_disk
5501 * then added disks for geometry changes,
5502 * and should be added immediately.
5504 super_types[mddev->major_version].
5505 validate_super(mddev, rdev);
5506 err = mddev->pers->hot_add_disk(mddev, rdev);
5507 if (err)
5508 unbind_rdev_from_array(rdev);
5510 if (err)
5511 export_rdev(rdev);
5512 else
5513 sysfs_notify_dirent_safe(rdev->sysfs_state);
5515 md_update_sb(mddev, 1);
5516 if (mddev->degraded)
5517 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5518 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5519 if (!err)
5520 md_new_event(mddev);
5521 md_wakeup_thread(mddev->thread);
5522 return err;
5525 /* otherwise, add_new_disk is only allowed
5526 * for major_version==0 superblocks
5528 if (mddev->major_version != 0) {
5529 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5530 mdname(mddev));
5531 return -EINVAL;
5534 if (!(info->state & (1<<MD_DISK_FAULTY))) {
5535 int err;
5536 rdev = md_import_device(dev, -1, 0);
5537 if (IS_ERR(rdev)) {
5538 printk(KERN_WARNING
5539 "md: error, md_import_device() returned %ld\n",
5540 PTR_ERR(rdev));
5541 return PTR_ERR(rdev);
5543 rdev->desc_nr = info->number;
5544 if (info->raid_disk < mddev->raid_disks)
5545 rdev->raid_disk = info->raid_disk;
5546 else
5547 rdev->raid_disk = -1;
5549 if (rdev->raid_disk < mddev->raid_disks)
5550 if (info->state & (1<<MD_DISK_SYNC))
5551 set_bit(In_sync, &rdev->flags);
5553 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5554 set_bit(WriteMostly, &rdev->flags);
5556 if (!mddev->persistent) {
5557 printk(KERN_INFO "md: nonpersistent superblock ...\n");
5558 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5559 } else
5560 rdev->sb_start = calc_dev_sboffset(rdev);
5561 rdev->sectors = rdev->sb_start;
5563 err = bind_rdev_to_array(rdev, mddev);
5564 if (err) {
5565 export_rdev(rdev);
5566 return err;
5570 return 0;
5573 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
5575 char b[BDEVNAME_SIZE];
5576 mdk_rdev_t *rdev;
5578 rdev = find_rdev(mddev, dev);
5579 if (!rdev)
5580 return -ENXIO;
5582 if (rdev->raid_disk >= 0)
5583 goto busy;
5585 kick_rdev_from_array(rdev);
5586 md_update_sb(mddev, 1);
5587 md_new_event(mddev);
5589 return 0;
5590 busy:
5591 printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
5592 bdevname(rdev->bdev,b), mdname(mddev));
5593 return -EBUSY;
5596 static int hot_add_disk(mddev_t * mddev, dev_t dev)
5598 char b[BDEVNAME_SIZE];
5599 int err;
5600 mdk_rdev_t *rdev;
5602 if (!mddev->pers)
5603 return -ENODEV;
5605 if (mddev->major_version != 0) {
5606 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
5607 " version-0 superblocks.\n",
5608 mdname(mddev));
5609 return -EINVAL;
5611 if (!mddev->pers->hot_add_disk) {
5612 printk(KERN_WARNING
5613 "%s: personality does not support diskops!\n",
5614 mdname(mddev));
5615 return -EINVAL;
5618 rdev = md_import_device(dev, -1, 0);
5619 if (IS_ERR(rdev)) {
5620 printk(KERN_WARNING
5621 "md: error, md_import_device() returned %ld\n",
5622 PTR_ERR(rdev));
5623 return -EINVAL;
5626 if (mddev->persistent)
5627 rdev->sb_start = calc_dev_sboffset(rdev);
5628 else
5629 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5631 rdev->sectors = rdev->sb_start;
5633 if (test_bit(Faulty, &rdev->flags)) {
5634 printk(KERN_WARNING
5635 "md: can not hot-add faulty %s disk to %s!\n",
5636 bdevname(rdev->bdev,b), mdname(mddev));
5637 err = -EINVAL;
5638 goto abort_export;
5640 clear_bit(In_sync, &rdev->flags);
5641 rdev->desc_nr = -1;
5642 rdev->saved_raid_disk = -1;
5643 err = bind_rdev_to_array(rdev, mddev);
5644 if (err)
5645 goto abort_export;
5648 * The rest should better be atomic, we can have disk failures
5649 * noticed in interrupt contexts ...
5652 rdev->raid_disk = -1;
5654 md_update_sb(mddev, 1);
5657 * Kick recovery, maybe this spare has to be added to the
5658 * array immediately.
5660 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5661 md_wakeup_thread(mddev->thread);
5662 md_new_event(mddev);
5663 return 0;
5665 abort_export:
5666 export_rdev(rdev);
5667 return err;
5670 static int set_bitmap_file(mddev_t *mddev, int fd)
5672 int err;
5674 if (mddev->pers) {
5675 if (!mddev->pers->quiesce)
5676 return -EBUSY;
5677 if (mddev->recovery || mddev->sync_thread)
5678 return -EBUSY;
5679 /* we should be able to change the bitmap.. */
5683 if (fd >= 0) {
5684 if (mddev->bitmap)
5685 return -EEXIST; /* cannot add when bitmap is present */
5686 mddev->bitmap_info.file = fget(fd);
5688 if (mddev->bitmap_info.file == NULL) {
5689 printk(KERN_ERR "%s: error: failed to get bitmap file\n",
5690 mdname(mddev));
5691 return -EBADF;
5694 err = deny_bitmap_write_access(mddev->bitmap_info.file);
5695 if (err) {
5696 printk(KERN_ERR "%s: error: bitmap file is already in use\n",
5697 mdname(mddev));
5698 fput(mddev->bitmap_info.file);
5699 mddev->bitmap_info.file = NULL;
5700 return err;
5702 mddev->bitmap_info.offset = 0; /* file overrides offset */
5703 } else if (mddev->bitmap == NULL)
5704 return -ENOENT; /* cannot remove what isn't there */
5705 err = 0;
5706 if (mddev->pers) {
5707 mddev->pers->quiesce(mddev, 1);
5708 if (fd >= 0) {
5709 err = bitmap_create(mddev);
5710 if (!err)
5711 err = bitmap_load(mddev);
5713 if (fd < 0 || err) {
5714 bitmap_destroy(mddev);
5715 fd = -1; /* make sure to put the file */
5717 mddev->pers->quiesce(mddev, 0);
5719 if (fd < 0) {
5720 if (mddev->bitmap_info.file) {
5721 restore_bitmap_write_access(mddev->bitmap_info.file);
5722 fput(mddev->bitmap_info.file);
5724 mddev->bitmap_info.file = NULL;
5727 return err;
5731 * set_array_info is used two different ways
5732 * The original usage is when creating a new array.
5733 * In this usage, raid_disks is > 0 and it together with
5734 * level, size, not_persistent,layout,chunksize determine the
5735 * shape of the array.
5736 * This will always create an array with a type-0.90.0 superblock.
5737 * The newer usage is when assembling an array.
5738 * In this case raid_disks will be 0, and the major_version field is
5739 * use to determine which style super-blocks are to be found on the devices.
5740 * The minor and patch _version numbers are also kept incase the
5741 * super_block handler wishes to interpret them.
5743 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
5746 if (info->raid_disks == 0) {
5747 /* just setting version number for superblock loading */
5748 if (info->major_version < 0 ||
5749 info->major_version >= ARRAY_SIZE(super_types) ||
5750 super_types[info->major_version].name == NULL) {
5751 /* maybe try to auto-load a module? */
5752 printk(KERN_INFO
5753 "md: superblock version %d not known\n",
5754 info->major_version);
5755 return -EINVAL;
5757 mddev->major_version = info->major_version;
5758 mddev->minor_version = info->minor_version;
5759 mddev->patch_version = info->patch_version;
5760 mddev->persistent = !info->not_persistent;
5761 /* ensure mddev_put doesn't delete this now that there
5762 * is some minimal configuration.
5764 mddev->ctime = get_seconds();
5765 return 0;
5767 mddev->major_version = MD_MAJOR_VERSION;
5768 mddev->minor_version = MD_MINOR_VERSION;
5769 mddev->patch_version = MD_PATCHLEVEL_VERSION;
5770 mddev->ctime = get_seconds();
5772 mddev->level = info->level;
5773 mddev->clevel[0] = 0;
5774 mddev->dev_sectors = 2 * (sector_t)info->size;
5775 mddev->raid_disks = info->raid_disks;
5776 /* don't set md_minor, it is determined by which /dev/md* was
5777 * openned
5779 if (info->state & (1<<MD_SB_CLEAN))
5780 mddev->recovery_cp = MaxSector;
5781 else
5782 mddev->recovery_cp = 0;
5783 mddev->persistent = ! info->not_persistent;
5784 mddev->external = 0;
5786 mddev->layout = info->layout;
5787 mddev->chunk_sectors = info->chunk_size >> 9;
5789 mddev->max_disks = MD_SB_DISKS;
5791 if (mddev->persistent)
5792 mddev->flags = 0;
5793 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5795 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
5796 mddev->bitmap_info.offset = 0;
5798 mddev->reshape_position = MaxSector;
5801 * Generate a 128 bit UUID
5803 get_random_bytes(mddev->uuid, 16);
5805 mddev->new_level = mddev->level;
5806 mddev->new_chunk_sectors = mddev->chunk_sectors;
5807 mddev->new_layout = mddev->layout;
5808 mddev->delta_disks = 0;
5810 return 0;
5813 void md_set_array_sectors(mddev_t *mddev, sector_t array_sectors)
5815 WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
5817 if (mddev->external_size)
5818 return;
5820 mddev->array_sectors = array_sectors;
5822 EXPORT_SYMBOL(md_set_array_sectors);
5824 static int update_size(mddev_t *mddev, sector_t num_sectors)
5826 mdk_rdev_t *rdev;
5827 int rv;
5828 int fit = (num_sectors == 0);
5830 if (mddev->pers->resize == NULL)
5831 return -EINVAL;
5832 /* The "num_sectors" is the number of sectors of each device that
5833 * is used. This can only make sense for arrays with redundancy.
5834 * linear and raid0 always use whatever space is available. We can only
5835 * consider changing this number if no resync or reconstruction is
5836 * happening, and if the new size is acceptable. It must fit before the
5837 * sb_start or, if that is <data_offset, it must fit before the size
5838 * of each device. If num_sectors is zero, we find the largest size
5839 * that fits.
5841 if (mddev->sync_thread)
5842 return -EBUSY;
5843 if (mddev->bitmap)
5844 /* Sorry, cannot grow a bitmap yet, just remove it,
5845 * grow, and re-add.
5847 return -EBUSY;
5848 list_for_each_entry(rdev, &mddev->disks, same_set) {
5849 sector_t avail = rdev->sectors;
5851 if (fit && (num_sectors == 0 || num_sectors > avail))
5852 num_sectors = avail;
5853 if (avail < num_sectors)
5854 return -ENOSPC;
5856 rv = mddev->pers->resize(mddev, num_sectors);
5857 if (!rv)
5858 revalidate_disk(mddev->gendisk);
5859 return rv;
5862 static int update_raid_disks(mddev_t *mddev, int raid_disks)
5864 int rv;
5865 /* change the number of raid disks */
5866 if (mddev->pers->check_reshape == NULL)
5867 return -EINVAL;
5868 if (raid_disks <= 0 ||
5869 (mddev->max_disks && raid_disks >= mddev->max_disks))
5870 return -EINVAL;
5871 if (mddev->sync_thread || mddev->reshape_position != MaxSector)
5872 return -EBUSY;
5873 mddev->delta_disks = raid_disks - mddev->raid_disks;
5875 rv = mddev->pers->check_reshape(mddev);
5876 if (rv < 0)
5877 mddev->delta_disks = 0;
5878 return rv;
5883 * update_array_info is used to change the configuration of an
5884 * on-line array.
5885 * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
5886 * fields in the info are checked against the array.
5887 * Any differences that cannot be handled will cause an error.
5888 * Normally, only one change can be managed at a time.
5890 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
5892 int rv = 0;
5893 int cnt = 0;
5894 int state = 0;
5896 /* calculate expected state,ignoring low bits */
5897 if (mddev->bitmap && mddev->bitmap_info.offset)
5898 state |= (1 << MD_SB_BITMAP_PRESENT);
5900 if (mddev->major_version != info->major_version ||
5901 mddev->minor_version != info->minor_version ||
5902 /* mddev->patch_version != info->patch_version || */
5903 mddev->ctime != info->ctime ||
5904 mddev->level != info->level ||
5905 /* mddev->layout != info->layout || */
5906 !mddev->persistent != info->not_persistent||
5907 mddev->chunk_sectors != info->chunk_size >> 9 ||
5908 /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
5909 ((state^info->state) & 0xfffffe00)
5911 return -EINVAL;
5912 /* Check there is only one change */
5913 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5914 cnt++;
5915 if (mddev->raid_disks != info->raid_disks)
5916 cnt++;
5917 if (mddev->layout != info->layout)
5918 cnt++;
5919 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
5920 cnt++;
5921 if (cnt == 0)
5922 return 0;
5923 if (cnt > 1)
5924 return -EINVAL;
5926 if (mddev->layout != info->layout) {
5927 /* Change layout
5928 * we don't need to do anything at the md level, the
5929 * personality will take care of it all.
5931 if (mddev->pers->check_reshape == NULL)
5932 return -EINVAL;
5933 else {
5934 mddev->new_layout = info->layout;
5935 rv = mddev->pers->check_reshape(mddev);
5936 if (rv)
5937 mddev->new_layout = mddev->layout;
5938 return rv;
5941 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5942 rv = update_size(mddev, (sector_t)info->size * 2);
5944 if (mddev->raid_disks != info->raid_disks)
5945 rv = update_raid_disks(mddev, info->raid_disks);
5947 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
5948 if (mddev->pers->quiesce == NULL)
5949 return -EINVAL;
5950 if (mddev->recovery || mddev->sync_thread)
5951 return -EBUSY;
5952 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
5953 /* add the bitmap */
5954 if (mddev->bitmap)
5955 return -EEXIST;
5956 if (mddev->bitmap_info.default_offset == 0)
5957 return -EINVAL;
5958 mddev->bitmap_info.offset =
5959 mddev->bitmap_info.default_offset;
5960 mddev->pers->quiesce(mddev, 1);
5961 rv = bitmap_create(mddev);
5962 if (!rv)
5963 rv = bitmap_load(mddev);
5964 if (rv)
5965 bitmap_destroy(mddev);
5966 mddev->pers->quiesce(mddev, 0);
5967 } else {
5968 /* remove the bitmap */
5969 if (!mddev->bitmap)
5970 return -ENOENT;
5971 if (mddev->bitmap->file)
5972 return -EINVAL;
5973 mddev->pers->quiesce(mddev, 1);
5974 bitmap_destroy(mddev);
5975 mddev->pers->quiesce(mddev, 0);
5976 mddev->bitmap_info.offset = 0;
5979 md_update_sb(mddev, 1);
5980 return rv;
5983 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
5985 mdk_rdev_t *rdev;
5987 if (mddev->pers == NULL)
5988 return -ENODEV;
5990 rdev = find_rdev(mddev, dev);
5991 if (!rdev)
5992 return -ENODEV;
5994 md_error(mddev, rdev);
5995 if (!test_bit(Faulty, &rdev->flags))
5996 return -EBUSY;
5997 return 0;
6001 * We have a problem here : there is no easy way to give a CHS
6002 * virtual geometry. We currently pretend that we have a 2 heads
6003 * 4 sectors (with a BIG number of cylinders...). This drives
6004 * dosfs just mad... ;-)
6006 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
6008 mddev_t *mddev = bdev->bd_disk->private_data;
6010 geo->heads = 2;
6011 geo->sectors = 4;
6012 geo->cylinders = mddev->array_sectors / 8;
6013 return 0;
6016 static int md_ioctl(struct block_device *bdev, fmode_t mode,
6017 unsigned int cmd, unsigned long arg)
6019 int err = 0;
6020 void __user *argp = (void __user *)arg;
6021 mddev_t *mddev = NULL;
6022 int ro;
6024 if (!capable(CAP_SYS_ADMIN))
6025 return -EACCES;
6028 * Commands dealing with the RAID driver but not any
6029 * particular array:
6031 switch (cmd)
6033 case RAID_VERSION:
6034 err = get_version(argp);
6035 goto done;
6037 case PRINT_RAID_DEBUG:
6038 err = 0;
6039 md_print_devices();
6040 goto done;
6042 #ifndef MODULE
6043 case RAID_AUTORUN:
6044 err = 0;
6045 autostart_arrays(arg);
6046 goto done;
6047 #endif
6048 default:;
6052 * Commands creating/starting a new array:
6055 mddev = bdev->bd_disk->private_data;
6057 if (!mddev) {
6058 BUG();
6059 goto abort;
6062 err = mddev_lock(mddev);
6063 if (err) {
6064 printk(KERN_INFO
6065 "md: ioctl lock interrupted, reason %d, cmd %d\n",
6066 err, cmd);
6067 goto abort;
6070 switch (cmd)
6072 case SET_ARRAY_INFO:
6074 mdu_array_info_t info;
6075 if (!arg)
6076 memset(&info, 0, sizeof(info));
6077 else if (copy_from_user(&info, argp, sizeof(info))) {
6078 err = -EFAULT;
6079 goto abort_unlock;
6081 if (mddev->pers) {
6082 err = update_array_info(mddev, &info);
6083 if (err) {
6084 printk(KERN_WARNING "md: couldn't update"
6085 " array info. %d\n", err);
6086 goto abort_unlock;
6088 goto done_unlock;
6090 if (!list_empty(&mddev->disks)) {
6091 printk(KERN_WARNING
6092 "md: array %s already has disks!\n",
6093 mdname(mddev));
6094 err = -EBUSY;
6095 goto abort_unlock;
6097 if (mddev->raid_disks) {
6098 printk(KERN_WARNING
6099 "md: array %s already initialised!\n",
6100 mdname(mddev));
6101 err = -EBUSY;
6102 goto abort_unlock;
6104 err = set_array_info(mddev, &info);
6105 if (err) {
6106 printk(KERN_WARNING "md: couldn't set"
6107 " array info. %d\n", err);
6108 goto abort_unlock;
6111 goto done_unlock;
6113 default:;
6117 * Commands querying/configuring an existing array:
6119 /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
6120 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
6121 if ((!mddev->raid_disks && !mddev->external)
6122 && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
6123 && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
6124 && cmd != GET_BITMAP_FILE) {
6125 err = -ENODEV;
6126 goto abort_unlock;
6130 * Commands even a read-only array can execute:
6132 switch (cmd)
6134 case GET_ARRAY_INFO:
6135 err = get_array_info(mddev, argp);
6136 goto done_unlock;
6138 case GET_BITMAP_FILE:
6139 err = get_bitmap_file(mddev, argp);
6140 goto done_unlock;
6142 case GET_DISK_INFO:
6143 err = get_disk_info(mddev, argp);
6144 goto done_unlock;
6146 case RESTART_ARRAY_RW:
6147 err = restart_array(mddev);
6148 goto done_unlock;
6150 case STOP_ARRAY:
6151 err = do_md_stop(mddev, 0, 1);
6152 goto done_unlock;
6154 case STOP_ARRAY_RO:
6155 err = md_set_readonly(mddev, 1);
6156 goto done_unlock;
6158 case BLKROSET:
6159 if (get_user(ro, (int __user *)(arg))) {
6160 err = -EFAULT;
6161 goto done_unlock;
6163 err = -EINVAL;
6165 /* if the bdev is going readonly the value of mddev->ro
6166 * does not matter, no writes are coming
6168 if (ro)
6169 goto done_unlock;
6171 /* are we are already prepared for writes? */
6172 if (mddev->ro != 1)
6173 goto done_unlock;
6175 /* transitioning to readauto need only happen for
6176 * arrays that call md_write_start
6178 if (mddev->pers) {
6179 err = restart_array(mddev);
6180 if (err == 0) {
6181 mddev->ro = 2;
6182 set_disk_ro(mddev->gendisk, 0);
6185 goto done_unlock;
6189 * The remaining ioctls are changing the state of the
6190 * superblock, so we do not allow them on read-only arrays.
6191 * However non-MD ioctls (e.g. get-size) will still come through
6192 * here and hit the 'default' below, so only disallow
6193 * 'md' ioctls, and switch to rw mode if started auto-readonly.
6195 if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
6196 if (mddev->ro == 2) {
6197 mddev->ro = 0;
6198 sysfs_notify_dirent_safe(mddev->sysfs_state);
6199 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6200 md_wakeup_thread(mddev->thread);
6201 } else {
6202 err = -EROFS;
6203 goto abort_unlock;
6207 switch (cmd)
6209 case ADD_NEW_DISK:
6211 mdu_disk_info_t info;
6212 if (copy_from_user(&info, argp, sizeof(info)))
6213 err = -EFAULT;
6214 else
6215 err = add_new_disk(mddev, &info);
6216 goto done_unlock;
6219 case HOT_REMOVE_DISK:
6220 err = hot_remove_disk(mddev, new_decode_dev(arg));
6221 goto done_unlock;
6223 case HOT_ADD_DISK:
6224 err = hot_add_disk(mddev, new_decode_dev(arg));
6225 goto done_unlock;
6227 case SET_DISK_FAULTY:
6228 err = set_disk_faulty(mddev, new_decode_dev(arg));
6229 goto done_unlock;
6231 case RUN_ARRAY:
6232 err = do_md_run(mddev);
6233 goto done_unlock;
6235 case SET_BITMAP_FILE:
6236 err = set_bitmap_file(mddev, (int)arg);
6237 goto done_unlock;
6239 default:
6240 err = -EINVAL;
6241 goto abort_unlock;
6244 done_unlock:
6245 abort_unlock:
6246 if (mddev->hold_active == UNTIL_IOCTL &&
6247 err != -EINVAL)
6248 mddev->hold_active = 0;
6249 mddev_unlock(mddev);
6251 return err;
6252 done:
6253 if (err)
6254 MD_BUG();
6255 abort:
6256 return err;
6258 #ifdef CONFIG_COMPAT
6259 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
6260 unsigned int cmd, unsigned long arg)
6262 switch (cmd) {
6263 case HOT_REMOVE_DISK:
6264 case HOT_ADD_DISK:
6265 case SET_DISK_FAULTY:
6266 case SET_BITMAP_FILE:
6267 /* These take in integer arg, do not convert */
6268 break;
6269 default:
6270 arg = (unsigned long)compat_ptr(arg);
6271 break;
6274 return md_ioctl(bdev, mode, cmd, arg);
6276 #endif /* CONFIG_COMPAT */
6278 static int md_open(struct block_device *bdev, fmode_t mode)
6281 * Succeed if we can lock the mddev, which confirms that
6282 * it isn't being stopped right now.
6284 mddev_t *mddev = mddev_find(bdev->bd_dev);
6285 int err;
6287 if (mddev->gendisk != bdev->bd_disk) {
6288 /* we are racing with mddev_put which is discarding this
6289 * bd_disk.
6291 mddev_put(mddev);
6292 /* Wait until bdev->bd_disk is definitely gone */
6293 flush_workqueue(md_misc_wq);
6294 /* Then retry the open from the top */
6295 return -ERESTARTSYS;
6297 BUG_ON(mddev != bdev->bd_disk->private_data);
6299 if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
6300 goto out;
6302 err = 0;
6303 atomic_inc(&mddev->openers);
6304 mutex_unlock(&mddev->open_mutex);
6306 check_disk_change(bdev);
6307 out:
6308 return err;
6311 static int md_release(struct gendisk *disk, fmode_t mode)
6313 mddev_t *mddev = disk->private_data;
6315 BUG_ON(!mddev);
6316 atomic_dec(&mddev->openers);
6317 mddev_put(mddev);
6319 return 0;
6322 static int md_media_changed(struct gendisk *disk)
6324 mddev_t *mddev = disk->private_data;
6326 return mddev->changed;
6329 static int md_revalidate(struct gendisk *disk)
6331 mddev_t *mddev = disk->private_data;
6333 mddev->changed = 0;
6334 return 0;
6336 static const struct block_device_operations md_fops =
6338 .owner = THIS_MODULE,
6339 .open = md_open,
6340 .release = md_release,
6341 .ioctl = md_ioctl,
6342 #ifdef CONFIG_COMPAT
6343 .compat_ioctl = md_compat_ioctl,
6344 #endif
6345 .getgeo = md_getgeo,
6346 .media_changed = md_media_changed,
6347 .revalidate_disk= md_revalidate,
6350 static int md_thread(void * arg)
6352 mdk_thread_t *thread = arg;
6355 * md_thread is a 'system-thread', it's priority should be very
6356 * high. We avoid resource deadlocks individually in each
6357 * raid personality. (RAID5 does preallocation) We also use RR and
6358 * the very same RT priority as kswapd, thus we will never get
6359 * into a priority inversion deadlock.
6361 * we definitely have to have equal or higher priority than
6362 * bdflush, otherwise bdflush will deadlock if there are too
6363 * many dirty RAID5 blocks.
6366 allow_signal(SIGKILL);
6367 while (!kthread_should_stop()) {
6369 /* We need to wait INTERRUPTIBLE so that
6370 * we don't add to the load-average.
6371 * That means we need to be sure no signals are
6372 * pending
6374 if (signal_pending(current))
6375 flush_signals(current);
6377 wait_event_interruptible_timeout
6378 (thread->wqueue,
6379 test_bit(THREAD_WAKEUP, &thread->flags)
6380 || kthread_should_stop(),
6381 thread->timeout);
6383 clear_bit(THREAD_WAKEUP, &thread->flags);
6384 if (!kthread_should_stop())
6385 thread->run(thread->mddev);
6388 return 0;
6391 void md_wakeup_thread(mdk_thread_t *thread)
6393 if (thread) {
6394 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
6395 set_bit(THREAD_WAKEUP, &thread->flags);
6396 wake_up(&thread->wqueue);
6400 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
6401 const char *name)
6403 mdk_thread_t *thread;
6405 thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
6406 if (!thread)
6407 return NULL;
6409 init_waitqueue_head(&thread->wqueue);
6411 thread->run = run;
6412 thread->mddev = mddev;
6413 thread->timeout = MAX_SCHEDULE_TIMEOUT;
6414 thread->tsk = kthread_run(md_thread, thread,
6415 "%s_%s",
6416 mdname(thread->mddev),
6417 name ?: mddev->pers->name);
6418 if (IS_ERR(thread->tsk)) {
6419 kfree(thread);
6420 return NULL;
6422 return thread;
6425 void md_unregister_thread(mdk_thread_t *thread)
6427 if (!thread)
6428 return;
6429 dprintk("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
6431 kthread_stop(thread->tsk);
6432 kfree(thread);
6435 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
6437 if (!mddev) {
6438 MD_BUG();
6439 return;
6442 if (!rdev || test_bit(Faulty, &rdev->flags))
6443 return;
6445 if (!mddev->pers || !mddev->pers->error_handler)
6446 return;
6447 mddev->pers->error_handler(mddev,rdev);
6448 if (mddev->degraded)
6449 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6450 sysfs_notify_dirent_safe(rdev->sysfs_state);
6451 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6452 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6453 md_wakeup_thread(mddev->thread);
6454 if (mddev->event_work.func)
6455 queue_work(md_misc_wq, &mddev->event_work);
6456 md_new_event_inintr(mddev);
6459 /* seq_file implementation /proc/mdstat */
6461 static void status_unused(struct seq_file *seq)
6463 int i = 0;
6464 mdk_rdev_t *rdev;
6466 seq_printf(seq, "unused devices: ");
6468 list_for_each_entry(rdev, &pending_raid_disks, same_set) {
6469 char b[BDEVNAME_SIZE];
6470 i++;
6471 seq_printf(seq, "%s ",
6472 bdevname(rdev->bdev,b));
6474 if (!i)
6475 seq_printf(seq, "<none>");
6477 seq_printf(seq, "\n");
6481 static void status_resync(struct seq_file *seq, mddev_t * mddev)
6483 sector_t max_sectors, resync, res;
6484 unsigned long dt, db;
6485 sector_t rt;
6486 int scale;
6487 unsigned int per_milli;
6489 resync = mddev->curr_resync - atomic_read(&mddev->recovery_active);
6491 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
6492 max_sectors = mddev->resync_max_sectors;
6493 else
6494 max_sectors = mddev->dev_sectors;
6497 * Should not happen.
6499 if (!max_sectors) {
6500 MD_BUG();
6501 return;
6503 /* Pick 'scale' such that (resync>>scale)*1000 will fit
6504 * in a sector_t, and (max_sectors>>scale) will fit in a
6505 * u32, as those are the requirements for sector_div.
6506 * Thus 'scale' must be at least 10
6508 scale = 10;
6509 if (sizeof(sector_t) > sizeof(unsigned long)) {
6510 while ( max_sectors/2 > (1ULL<<(scale+32)))
6511 scale++;
6513 res = (resync>>scale)*1000;
6514 sector_div(res, (u32)((max_sectors>>scale)+1));
6516 per_milli = res;
6518 int i, x = per_milli/50, y = 20-x;
6519 seq_printf(seq, "[");
6520 for (i = 0; i < x; i++)
6521 seq_printf(seq, "=");
6522 seq_printf(seq, ">");
6523 for (i = 0; i < y; i++)
6524 seq_printf(seq, ".");
6525 seq_printf(seq, "] ");
6527 seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
6528 (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
6529 "reshape" :
6530 (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
6531 "check" :
6532 (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
6533 "resync" : "recovery"))),
6534 per_milli/10, per_milli % 10,
6535 (unsigned long long) resync/2,
6536 (unsigned long long) max_sectors/2);
6539 * dt: time from mark until now
6540 * db: blocks written from mark until now
6541 * rt: remaining time
6543 * rt is a sector_t, so could be 32bit or 64bit.
6544 * So we divide before multiply in case it is 32bit and close
6545 * to the limit.
6546 * We scale the divisor (db) by 32 to avoid losing precision
6547 * near the end of resync when the number of remaining sectors
6548 * is close to 'db'.
6549 * We then divide rt by 32 after multiplying by db to compensate.
6550 * The '+1' avoids division by zero if db is very small.
6552 dt = ((jiffies - mddev->resync_mark) / HZ);
6553 if (!dt) dt++;
6554 db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
6555 - mddev->resync_mark_cnt;
6557 rt = max_sectors - resync; /* number of remaining sectors */
6558 sector_div(rt, db/32+1);
6559 rt *= dt;
6560 rt >>= 5;
6562 seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
6563 ((unsigned long)rt % 60)/6);
6565 seq_printf(seq, " speed=%ldK/sec", db/2/dt);
6568 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
6570 struct list_head *tmp;
6571 loff_t l = *pos;
6572 mddev_t *mddev;
6574 if (l >= 0x10000)
6575 return NULL;
6576 if (!l--)
6577 /* header */
6578 return (void*)1;
6580 spin_lock(&all_mddevs_lock);
6581 list_for_each(tmp,&all_mddevs)
6582 if (!l--) {
6583 mddev = list_entry(tmp, mddev_t, all_mddevs);
6584 mddev_get(mddev);
6585 spin_unlock(&all_mddevs_lock);
6586 return mddev;
6588 spin_unlock(&all_mddevs_lock);
6589 if (!l--)
6590 return (void*)2;/* tail */
6591 return NULL;
6594 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
6596 struct list_head *tmp;
6597 mddev_t *next_mddev, *mddev = v;
6599 ++*pos;
6600 if (v == (void*)2)
6601 return NULL;
6603 spin_lock(&all_mddevs_lock);
6604 if (v == (void*)1)
6605 tmp = all_mddevs.next;
6606 else
6607 tmp = mddev->all_mddevs.next;
6608 if (tmp != &all_mddevs)
6609 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
6610 else {
6611 next_mddev = (void*)2;
6612 *pos = 0x10000;
6614 spin_unlock(&all_mddevs_lock);
6616 if (v != (void*)1)
6617 mddev_put(mddev);
6618 return next_mddev;
6622 static void md_seq_stop(struct seq_file *seq, void *v)
6624 mddev_t *mddev = v;
6626 if (mddev && v != (void*)1 && v != (void*)2)
6627 mddev_put(mddev);
6630 static int md_seq_show(struct seq_file *seq, void *v)
6632 mddev_t *mddev = v;
6633 sector_t sectors;
6634 mdk_rdev_t *rdev;
6635 struct bitmap *bitmap;
6637 if (v == (void*)1) {
6638 struct mdk_personality *pers;
6639 seq_printf(seq, "Personalities : ");
6640 spin_lock(&pers_lock);
6641 list_for_each_entry(pers, &pers_list, list)
6642 seq_printf(seq, "[%s] ", pers->name);
6644 spin_unlock(&pers_lock);
6645 seq_printf(seq, "\n");
6646 seq->poll_event = atomic_read(&md_event_count);
6647 return 0;
6649 if (v == (void*)2) {
6650 status_unused(seq);
6651 return 0;
6654 if (mddev_lock(mddev) < 0)
6655 return -EINTR;
6657 if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
6658 seq_printf(seq, "%s : %sactive", mdname(mddev),
6659 mddev->pers ? "" : "in");
6660 if (mddev->pers) {
6661 if (mddev->ro==1)
6662 seq_printf(seq, " (read-only)");
6663 if (mddev->ro==2)
6664 seq_printf(seq, " (auto-read-only)");
6665 seq_printf(seq, " %s", mddev->pers->name);
6668 sectors = 0;
6669 list_for_each_entry(rdev, &mddev->disks, same_set) {
6670 char b[BDEVNAME_SIZE];
6671 seq_printf(seq, " %s[%d]",
6672 bdevname(rdev->bdev,b), rdev->desc_nr);
6673 if (test_bit(WriteMostly, &rdev->flags))
6674 seq_printf(seq, "(W)");
6675 if (test_bit(Faulty, &rdev->flags)) {
6676 seq_printf(seq, "(F)");
6677 continue;
6678 } else if (rdev->raid_disk < 0)
6679 seq_printf(seq, "(S)"); /* spare */
6680 sectors += rdev->sectors;
6683 if (!list_empty(&mddev->disks)) {
6684 if (mddev->pers)
6685 seq_printf(seq, "\n %llu blocks",
6686 (unsigned long long)
6687 mddev->array_sectors / 2);
6688 else
6689 seq_printf(seq, "\n %llu blocks",
6690 (unsigned long long)sectors / 2);
6692 if (mddev->persistent) {
6693 if (mddev->major_version != 0 ||
6694 mddev->minor_version != 90) {
6695 seq_printf(seq," super %d.%d",
6696 mddev->major_version,
6697 mddev->minor_version);
6699 } else if (mddev->external)
6700 seq_printf(seq, " super external:%s",
6701 mddev->metadata_type);
6702 else
6703 seq_printf(seq, " super non-persistent");
6705 if (mddev->pers) {
6706 mddev->pers->status(seq, mddev);
6707 seq_printf(seq, "\n ");
6708 if (mddev->pers->sync_request) {
6709 if (mddev->curr_resync > 2) {
6710 status_resync(seq, mddev);
6711 seq_printf(seq, "\n ");
6712 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
6713 seq_printf(seq, "\tresync=DELAYED\n ");
6714 else if (mddev->recovery_cp < MaxSector)
6715 seq_printf(seq, "\tresync=PENDING\n ");
6717 } else
6718 seq_printf(seq, "\n ");
6720 if ((bitmap = mddev->bitmap)) {
6721 unsigned long chunk_kb;
6722 unsigned long flags;
6723 spin_lock_irqsave(&bitmap->lock, flags);
6724 chunk_kb = mddev->bitmap_info.chunksize >> 10;
6725 seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
6726 "%lu%s chunk",
6727 bitmap->pages - bitmap->missing_pages,
6728 bitmap->pages,
6729 (bitmap->pages - bitmap->missing_pages)
6730 << (PAGE_SHIFT - 10),
6731 chunk_kb ? chunk_kb : mddev->bitmap_info.chunksize,
6732 chunk_kb ? "KB" : "B");
6733 if (bitmap->file) {
6734 seq_printf(seq, ", file: ");
6735 seq_path(seq, &bitmap->file->f_path, " \t\n");
6738 seq_printf(seq, "\n");
6739 spin_unlock_irqrestore(&bitmap->lock, flags);
6742 seq_printf(seq, "\n");
6744 mddev_unlock(mddev);
6746 return 0;
6749 static const struct seq_operations md_seq_ops = {
6750 .start = md_seq_start,
6751 .next = md_seq_next,
6752 .stop = md_seq_stop,
6753 .show = md_seq_show,
6756 static int md_seq_open(struct inode *inode, struct file *file)
6758 struct seq_file *seq;
6759 int error;
6761 error = seq_open(file, &md_seq_ops);
6762 if (error)
6763 return error;
6765 seq = file->private_data;
6766 seq->poll_event = atomic_read(&md_event_count);
6767 return error;
6770 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
6772 struct seq_file *seq = filp->private_data;
6773 int mask;
6775 poll_wait(filp, &md_event_waiters, wait);
6777 /* always allow read */
6778 mask = POLLIN | POLLRDNORM;
6780 if (seq->poll_event != atomic_read(&md_event_count))
6781 mask |= POLLERR | POLLPRI;
6782 return mask;
6785 static const struct file_operations md_seq_fops = {
6786 .owner = THIS_MODULE,
6787 .open = md_seq_open,
6788 .read = seq_read,
6789 .llseek = seq_lseek,
6790 .release = seq_release_private,
6791 .poll = mdstat_poll,
6794 int register_md_personality(struct mdk_personality *p)
6796 spin_lock(&pers_lock);
6797 list_add_tail(&p->list, &pers_list);
6798 printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
6799 spin_unlock(&pers_lock);
6800 return 0;
6803 int unregister_md_personality(struct mdk_personality *p)
6805 printk(KERN_INFO "md: %s personality unregistered\n", p->name);
6806 spin_lock(&pers_lock);
6807 list_del_init(&p->list);
6808 spin_unlock(&pers_lock);
6809 return 0;
6812 static int is_mddev_idle(mddev_t *mddev, int init)
6814 mdk_rdev_t * rdev;
6815 int idle;
6816 int curr_events;
6818 idle = 1;
6819 rcu_read_lock();
6820 rdev_for_each_rcu(rdev, mddev) {
6821 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
6822 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
6823 (int)part_stat_read(&disk->part0, sectors[1]) -
6824 atomic_read(&disk->sync_io);
6825 /* sync IO will cause sync_io to increase before the disk_stats
6826 * as sync_io is counted when a request starts, and
6827 * disk_stats is counted when it completes.
6828 * So resync activity will cause curr_events to be smaller than
6829 * when there was no such activity.
6830 * non-sync IO will cause disk_stat to increase without
6831 * increasing sync_io so curr_events will (eventually)
6832 * be larger than it was before. Once it becomes
6833 * substantially larger, the test below will cause
6834 * the array to appear non-idle, and resync will slow
6835 * down.
6836 * If there is a lot of outstanding resync activity when
6837 * we set last_event to curr_events, then all that activity
6838 * completing might cause the array to appear non-idle
6839 * and resync will be slowed down even though there might
6840 * not have been non-resync activity. This will only
6841 * happen once though. 'last_events' will soon reflect
6842 * the state where there is little or no outstanding
6843 * resync requests, and further resync activity will
6844 * always make curr_events less than last_events.
6847 if (init || curr_events - rdev->last_events > 64) {
6848 rdev->last_events = curr_events;
6849 idle = 0;
6852 rcu_read_unlock();
6853 return idle;
6856 void md_done_sync(mddev_t *mddev, int blocks, int ok)
6858 /* another "blocks" (512byte) blocks have been synced */
6859 atomic_sub(blocks, &mddev->recovery_active);
6860 wake_up(&mddev->recovery_wait);
6861 if (!ok) {
6862 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6863 md_wakeup_thread(mddev->thread);
6864 // stop recovery, signal do_sync ....
6869 /* md_write_start(mddev, bi)
6870 * If we need to update some array metadata (e.g. 'active' flag
6871 * in superblock) before writing, schedule a superblock update
6872 * and wait for it to complete.
6874 void md_write_start(mddev_t *mddev, struct bio *bi)
6876 int did_change = 0;
6877 if (bio_data_dir(bi) != WRITE)
6878 return;
6880 BUG_ON(mddev->ro == 1);
6881 if (mddev->ro == 2) {
6882 /* need to switch to read/write */
6883 mddev->ro = 0;
6884 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6885 md_wakeup_thread(mddev->thread);
6886 md_wakeup_thread(mddev->sync_thread);
6887 did_change = 1;
6889 atomic_inc(&mddev->writes_pending);
6890 if (mddev->safemode == 1)
6891 mddev->safemode = 0;
6892 if (mddev->in_sync) {
6893 spin_lock_irq(&mddev->write_lock);
6894 if (mddev->in_sync) {
6895 mddev->in_sync = 0;
6896 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
6897 set_bit(MD_CHANGE_PENDING, &mddev->flags);
6898 md_wakeup_thread(mddev->thread);
6899 did_change = 1;
6901 spin_unlock_irq(&mddev->write_lock);
6903 if (did_change)
6904 sysfs_notify_dirent_safe(mddev->sysfs_state);
6905 wait_event(mddev->sb_wait,
6906 !test_bit(MD_CHANGE_PENDING, &mddev->flags));
6909 void md_write_end(mddev_t *mddev)
6911 if (atomic_dec_and_test(&mddev->writes_pending)) {
6912 if (mddev->safemode == 2)
6913 md_wakeup_thread(mddev->thread);
6914 else if (mddev->safemode_delay)
6915 mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
6919 /* md_allow_write(mddev)
6920 * Calling this ensures that the array is marked 'active' so that writes
6921 * may proceed without blocking. It is important to call this before
6922 * attempting a GFP_KERNEL allocation while holding the mddev lock.
6923 * Must be called with mddev_lock held.
6925 * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
6926 * is dropped, so return -EAGAIN after notifying userspace.
6928 int md_allow_write(mddev_t *mddev)
6930 if (!mddev->pers)
6931 return 0;
6932 if (mddev->ro)
6933 return 0;
6934 if (!mddev->pers->sync_request)
6935 return 0;
6937 spin_lock_irq(&mddev->write_lock);
6938 if (mddev->in_sync) {
6939 mddev->in_sync = 0;
6940 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
6941 set_bit(MD_CHANGE_PENDING, &mddev->flags);
6942 if (mddev->safemode_delay &&
6943 mddev->safemode == 0)
6944 mddev->safemode = 1;
6945 spin_unlock_irq(&mddev->write_lock);
6946 md_update_sb(mddev, 0);
6947 sysfs_notify_dirent_safe(mddev->sysfs_state);
6948 } else
6949 spin_unlock_irq(&mddev->write_lock);
6951 if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
6952 return -EAGAIN;
6953 else
6954 return 0;
6956 EXPORT_SYMBOL_GPL(md_allow_write);
6958 #define SYNC_MARKS 10
6959 #define SYNC_MARK_STEP (3*HZ)
6960 void md_do_sync(mddev_t *mddev)
6962 mddev_t *mddev2;
6963 unsigned int currspeed = 0,
6964 window;
6965 sector_t max_sectors,j, io_sectors;
6966 unsigned long mark[SYNC_MARKS];
6967 sector_t mark_cnt[SYNC_MARKS];
6968 int last_mark,m;
6969 struct list_head *tmp;
6970 sector_t last_check;
6971 int skipped = 0;
6972 mdk_rdev_t *rdev;
6973 char *desc;
6975 /* just incase thread restarts... */
6976 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
6977 return;
6978 if (mddev->ro) /* never try to sync a read-only array */
6979 return;
6981 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6982 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
6983 desc = "data-check";
6984 else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
6985 desc = "requested-resync";
6986 else
6987 desc = "resync";
6988 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6989 desc = "reshape";
6990 else
6991 desc = "recovery";
6993 /* we overload curr_resync somewhat here.
6994 * 0 == not engaged in resync at all
6995 * 2 == checking that there is no conflict with another sync
6996 * 1 == like 2, but have yielded to allow conflicting resync to
6997 * commense
6998 * other == active in resync - this many blocks
7000 * Before starting a resync we must have set curr_resync to
7001 * 2, and then checked that every "conflicting" array has curr_resync
7002 * less than ours. When we find one that is the same or higher
7003 * we wait on resync_wait. To avoid deadlock, we reduce curr_resync
7004 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
7005 * This will mean we have to start checking from the beginning again.
7009 do {
7010 mddev->curr_resync = 2;
7012 try_again:
7013 if (kthread_should_stop())
7014 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7016 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7017 goto skip;
7018 for_each_mddev(mddev2, tmp) {
7019 if (mddev2 == mddev)
7020 continue;
7021 if (!mddev->parallel_resync
7022 && mddev2->curr_resync
7023 && match_mddev_units(mddev, mddev2)) {
7024 DEFINE_WAIT(wq);
7025 if (mddev < mddev2 && mddev->curr_resync == 2) {
7026 /* arbitrarily yield */
7027 mddev->curr_resync = 1;
7028 wake_up(&resync_wait);
7030 if (mddev > mddev2 && mddev->curr_resync == 1)
7031 /* no need to wait here, we can wait the next
7032 * time 'round when curr_resync == 2
7034 continue;
7035 /* We need to wait 'interruptible' so as not to
7036 * contribute to the load average, and not to
7037 * be caught by 'softlockup'
7039 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
7040 if (!kthread_should_stop() &&
7041 mddev2->curr_resync >= mddev->curr_resync) {
7042 printk(KERN_INFO "md: delaying %s of %s"
7043 " until %s has finished (they"
7044 " share one or more physical units)\n",
7045 desc, mdname(mddev), mdname(mddev2));
7046 mddev_put(mddev2);
7047 if (signal_pending(current))
7048 flush_signals(current);
7049 schedule();
7050 finish_wait(&resync_wait, &wq);
7051 goto try_again;
7053 finish_wait(&resync_wait, &wq);
7056 } while (mddev->curr_resync < 2);
7058 j = 0;
7059 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7060 /* resync follows the size requested by the personality,
7061 * which defaults to physical size, but can be virtual size
7063 max_sectors = mddev->resync_max_sectors;
7064 mddev->resync_mismatches = 0;
7065 /* we don't use the checkpoint if there's a bitmap */
7066 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7067 j = mddev->resync_min;
7068 else if (!mddev->bitmap)
7069 j = mddev->recovery_cp;
7071 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7072 max_sectors = mddev->dev_sectors;
7073 else {
7074 /* recovery follows the physical size of devices */
7075 max_sectors = mddev->dev_sectors;
7076 j = MaxSector;
7077 rcu_read_lock();
7078 list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
7079 if (rdev->raid_disk >= 0 &&
7080 !test_bit(Faulty, &rdev->flags) &&
7081 !test_bit(In_sync, &rdev->flags) &&
7082 rdev->recovery_offset < j)
7083 j = rdev->recovery_offset;
7084 rcu_read_unlock();
7087 printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
7088 printk(KERN_INFO "md: minimum _guaranteed_ speed:"
7089 " %d KB/sec/disk.\n", speed_min(mddev));
7090 printk(KERN_INFO "md: using maximum available idle IO bandwidth "
7091 "(but not more than %d KB/sec) for %s.\n",
7092 speed_max(mddev), desc);
7094 is_mddev_idle(mddev, 1); /* this initializes IO event counters */
7096 io_sectors = 0;
7097 for (m = 0; m < SYNC_MARKS; m++) {
7098 mark[m] = jiffies;
7099 mark_cnt[m] = io_sectors;
7101 last_mark = 0;
7102 mddev->resync_mark = mark[last_mark];
7103 mddev->resync_mark_cnt = mark_cnt[last_mark];
7106 * Tune reconstruction:
7108 window = 32*(PAGE_SIZE/512);
7109 printk(KERN_INFO "md: using %dk window, over a total of %lluk.\n",
7110 window/2, (unsigned long long)max_sectors/2);
7112 atomic_set(&mddev->recovery_active, 0);
7113 last_check = 0;
7115 if (j>2) {
7116 printk(KERN_INFO
7117 "md: resuming %s of %s from checkpoint.\n",
7118 desc, mdname(mddev));
7119 mddev->curr_resync = j;
7121 mddev->curr_resync_completed = j;
7123 while (j < max_sectors) {
7124 sector_t sectors;
7126 skipped = 0;
7128 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7129 ((mddev->curr_resync > mddev->curr_resync_completed &&
7130 (mddev->curr_resync - mddev->curr_resync_completed)
7131 > (max_sectors >> 4)) ||
7132 (j - mddev->curr_resync_completed)*2
7133 >= mddev->resync_max - mddev->curr_resync_completed
7134 )) {
7135 /* time to update curr_resync_completed */
7136 wait_event(mddev->recovery_wait,
7137 atomic_read(&mddev->recovery_active) == 0);
7138 mddev->curr_resync_completed = j;
7139 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7140 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7143 while (j >= mddev->resync_max && !kthread_should_stop()) {
7144 /* As this condition is controlled by user-space,
7145 * we can block indefinitely, so use '_interruptible'
7146 * to avoid triggering warnings.
7148 flush_signals(current); /* just in case */
7149 wait_event_interruptible(mddev->recovery_wait,
7150 mddev->resync_max > j
7151 || kthread_should_stop());
7154 if (kthread_should_stop())
7155 goto interrupted;
7157 sectors = mddev->pers->sync_request(mddev, j, &skipped,
7158 currspeed < speed_min(mddev));
7159 if (sectors == 0) {
7160 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7161 goto out;
7164 if (!skipped) { /* actual IO requested */
7165 io_sectors += sectors;
7166 atomic_add(sectors, &mddev->recovery_active);
7169 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7170 break;
7172 j += sectors;
7173 if (j>1) mddev->curr_resync = j;
7174 mddev->curr_mark_cnt = io_sectors;
7175 if (last_check == 0)
7176 /* this is the earliest that rebuild will be
7177 * visible in /proc/mdstat
7179 md_new_event(mddev);
7181 if (last_check + window > io_sectors || j == max_sectors)
7182 continue;
7184 last_check = io_sectors;
7185 repeat:
7186 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
7187 /* step marks */
7188 int next = (last_mark+1) % SYNC_MARKS;
7190 mddev->resync_mark = mark[next];
7191 mddev->resync_mark_cnt = mark_cnt[next];
7192 mark[next] = jiffies;
7193 mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
7194 last_mark = next;
7198 if (kthread_should_stop())
7199 goto interrupted;
7203 * this loop exits only if either when we are slower than
7204 * the 'hard' speed limit, or the system was IO-idle for
7205 * a jiffy.
7206 * the system might be non-idle CPU-wise, but we only care
7207 * about not overloading the IO subsystem. (things like an
7208 * e2fsck being done on the RAID array should execute fast)
7210 cond_resched();
7212 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
7213 /((jiffies-mddev->resync_mark)/HZ +1) +1;
7215 if (currspeed > speed_min(mddev)) {
7216 if ((currspeed > speed_max(mddev)) ||
7217 !is_mddev_idle(mddev, 0)) {
7218 msleep(500);
7219 goto repeat;
7223 printk(KERN_INFO "md: %s: %s done.\n",mdname(mddev), desc);
7225 * this also signals 'finished resyncing' to md_stop
7227 out:
7228 wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
7230 /* tell personality that we are finished */
7231 mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
7233 if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
7234 mddev->curr_resync > 2) {
7235 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7236 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7237 if (mddev->curr_resync >= mddev->recovery_cp) {
7238 printk(KERN_INFO
7239 "md: checkpointing %s of %s.\n",
7240 desc, mdname(mddev));
7241 mddev->recovery_cp = mddev->curr_resync;
7243 } else
7244 mddev->recovery_cp = MaxSector;
7245 } else {
7246 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7247 mddev->curr_resync = MaxSector;
7248 rcu_read_lock();
7249 list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
7250 if (rdev->raid_disk >= 0 &&
7251 mddev->delta_disks >= 0 &&
7252 !test_bit(Faulty, &rdev->flags) &&
7253 !test_bit(In_sync, &rdev->flags) &&
7254 rdev->recovery_offset < mddev->curr_resync)
7255 rdev->recovery_offset = mddev->curr_resync;
7256 rcu_read_unlock();
7259 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7261 skip:
7262 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7263 /* We completed so min/max setting can be forgotten if used. */
7264 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7265 mddev->resync_min = 0;
7266 mddev->resync_max = MaxSector;
7267 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7268 mddev->resync_min = mddev->curr_resync_completed;
7269 mddev->curr_resync = 0;
7270 wake_up(&resync_wait);
7271 set_bit(MD_RECOVERY_DONE, &mddev->recovery);
7272 md_wakeup_thread(mddev->thread);
7273 return;
7275 interrupted:
7277 * got a signal, exit.
7279 printk(KERN_INFO
7280 "md: md_do_sync() got signal ... exiting\n");
7281 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7282 goto out;
7285 EXPORT_SYMBOL_GPL(md_do_sync);
7287 static int remove_and_add_spares(mddev_t *mddev)
7289 mdk_rdev_t *rdev;
7290 int spares = 0;
7292 mddev->curr_resync_completed = 0;
7294 list_for_each_entry(rdev, &mddev->disks, same_set)
7295 if (rdev->raid_disk >= 0 &&
7296 !test_bit(Blocked, &rdev->flags) &&
7297 (test_bit(Faulty, &rdev->flags) ||
7298 ! test_bit(In_sync, &rdev->flags)) &&
7299 atomic_read(&rdev->nr_pending)==0) {
7300 if (mddev->pers->hot_remove_disk(
7301 mddev, rdev->raid_disk)==0) {
7302 sysfs_unlink_rdev(mddev, rdev);
7303 rdev->raid_disk = -1;
7307 if (mddev->degraded) {
7308 list_for_each_entry(rdev, &mddev->disks, same_set) {
7309 if (rdev->raid_disk >= 0 &&
7310 !test_bit(In_sync, &rdev->flags) &&
7311 !test_bit(Faulty, &rdev->flags))
7312 spares++;
7313 if (rdev->raid_disk < 0
7314 && !test_bit(Faulty, &rdev->flags)) {
7315 rdev->recovery_offset = 0;
7316 if (mddev->pers->
7317 hot_add_disk(mddev, rdev) == 0) {
7318 if (sysfs_link_rdev(mddev, rdev))
7319 /* failure here is OK */;
7320 spares++;
7321 md_new_event(mddev);
7322 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7323 } else
7324 break;
7328 return spares;
7331 static void reap_sync_thread(mddev_t *mddev)
7333 mdk_rdev_t *rdev;
7335 /* resync has finished, collect result */
7336 md_unregister_thread(mddev->sync_thread);
7337 mddev->sync_thread = NULL;
7338 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
7339 !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
7340 /* success...*/
7341 /* activate any spares */
7342 if (mddev->pers->spare_active(mddev))
7343 sysfs_notify(&mddev->kobj, NULL,
7344 "degraded");
7346 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7347 mddev->pers->finish_reshape)
7348 mddev->pers->finish_reshape(mddev);
7349 md_update_sb(mddev, 1);
7351 /* if array is no-longer degraded, then any saved_raid_disk
7352 * information must be scrapped
7354 if (!mddev->degraded)
7355 list_for_each_entry(rdev, &mddev->disks, same_set)
7356 rdev->saved_raid_disk = -1;
7358 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7359 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7360 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7361 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7362 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7363 /* flag recovery needed just to double check */
7364 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7365 sysfs_notify_dirent_safe(mddev->sysfs_action);
7366 md_new_event(mddev);
7367 if (mddev->event_work.func)
7368 queue_work(md_misc_wq, &mddev->event_work);
7372 * This routine is regularly called by all per-raid-array threads to
7373 * deal with generic issues like resync and super-block update.
7374 * Raid personalities that don't have a thread (linear/raid0) do not
7375 * need this as they never do any recovery or update the superblock.
7377 * It does not do any resync itself, but rather "forks" off other threads
7378 * to do that as needed.
7379 * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
7380 * "->recovery" and create a thread at ->sync_thread.
7381 * When the thread finishes it sets MD_RECOVERY_DONE
7382 * and wakeups up this thread which will reap the thread and finish up.
7383 * This thread also removes any faulty devices (with nr_pending == 0).
7385 * The overall approach is:
7386 * 1/ if the superblock needs updating, update it.
7387 * 2/ If a recovery thread is running, don't do anything else.
7388 * 3/ If recovery has finished, clean up, possibly marking spares active.
7389 * 4/ If there are any faulty devices, remove them.
7390 * 5/ If array is degraded, try to add spares devices
7391 * 6/ If array has spares or is not in-sync, start a resync thread.
7393 void md_check_recovery(mddev_t *mddev)
7395 if (mddev->suspended)
7396 return;
7398 if (mddev->bitmap)
7399 bitmap_daemon_work(mddev);
7401 if (signal_pending(current)) {
7402 if (mddev->pers->sync_request && !mddev->external) {
7403 printk(KERN_INFO "md: %s in immediate safe mode\n",
7404 mdname(mddev));
7405 mddev->safemode = 2;
7407 flush_signals(current);
7410 if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
7411 return;
7412 if ( ! (
7413 (mddev->flags & ~ (1<<MD_CHANGE_PENDING)) ||
7414 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7415 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
7416 (mddev->external == 0 && mddev->safemode == 1) ||
7417 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
7418 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
7420 return;
7422 if (mddev_trylock(mddev)) {
7423 int spares = 0;
7425 if (mddev->ro) {
7426 /* Only thing we do on a ro array is remove
7427 * failed devices.
7429 mdk_rdev_t *rdev;
7430 list_for_each_entry(rdev, &mddev->disks, same_set)
7431 if (rdev->raid_disk >= 0 &&
7432 !test_bit(Blocked, &rdev->flags) &&
7433 test_bit(Faulty, &rdev->flags) &&
7434 atomic_read(&rdev->nr_pending)==0) {
7435 if (mddev->pers->hot_remove_disk(
7436 mddev, rdev->raid_disk)==0) {
7437 sysfs_unlink_rdev(mddev, rdev);
7438 rdev->raid_disk = -1;
7441 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7442 goto unlock;
7445 if (!mddev->external) {
7446 int did_change = 0;
7447 spin_lock_irq(&mddev->write_lock);
7448 if (mddev->safemode &&
7449 !atomic_read(&mddev->writes_pending) &&
7450 !mddev->in_sync &&
7451 mddev->recovery_cp == MaxSector) {
7452 mddev->in_sync = 1;
7453 did_change = 1;
7454 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7456 if (mddev->safemode == 1)
7457 mddev->safemode = 0;
7458 spin_unlock_irq(&mddev->write_lock);
7459 if (did_change)
7460 sysfs_notify_dirent_safe(mddev->sysfs_state);
7463 if (mddev->flags)
7464 md_update_sb(mddev, 0);
7466 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
7467 !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
7468 /* resync/recovery still happening */
7469 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7470 goto unlock;
7472 if (mddev->sync_thread) {
7473 reap_sync_thread(mddev);
7474 goto unlock;
7476 /* Set RUNNING before clearing NEEDED to avoid
7477 * any transients in the value of "sync_action".
7479 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7480 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7481 /* Clear some bits that don't mean anything, but
7482 * might be left set
7484 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
7485 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7487 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
7488 goto unlock;
7489 /* no recovery is running.
7490 * remove any failed drives, then
7491 * add spares if possible.
7492 * Spare are also removed and re-added, to allow
7493 * the personality to fail the re-add.
7496 if (mddev->reshape_position != MaxSector) {
7497 if (mddev->pers->check_reshape == NULL ||
7498 mddev->pers->check_reshape(mddev) != 0)
7499 /* Cannot proceed */
7500 goto unlock;
7501 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7502 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7503 } else if ((spares = remove_and_add_spares(mddev))) {
7504 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7505 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7506 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7507 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7508 } else if (mddev->recovery_cp < MaxSector) {
7509 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7510 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7511 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
7512 /* nothing to be done ... */
7513 goto unlock;
7515 if (mddev->pers->sync_request) {
7516 if (spares && mddev->bitmap && ! mddev->bitmap->file) {
7517 /* We are adding a device or devices to an array
7518 * which has the bitmap stored on all devices.
7519 * So make sure all bitmap pages get written
7521 bitmap_write_all(mddev->bitmap);
7523 mddev->sync_thread = md_register_thread(md_do_sync,
7524 mddev,
7525 "resync");
7526 if (!mddev->sync_thread) {
7527 printk(KERN_ERR "%s: could not start resync"
7528 " thread...\n",
7529 mdname(mddev));
7530 /* leave the spares where they are, it shouldn't hurt */
7531 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7532 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7533 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7534 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7535 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7536 } else
7537 md_wakeup_thread(mddev->sync_thread);
7538 sysfs_notify_dirent_safe(mddev->sysfs_action);
7539 md_new_event(mddev);
7541 unlock:
7542 if (!mddev->sync_thread) {
7543 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7544 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
7545 &mddev->recovery))
7546 if (mddev->sysfs_action)
7547 sysfs_notify_dirent_safe(mddev->sysfs_action);
7549 mddev_unlock(mddev);
7553 void md_wait_for_blocked_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
7555 sysfs_notify_dirent_safe(rdev->sysfs_state);
7556 wait_event_timeout(rdev->blocked_wait,
7557 !test_bit(Blocked, &rdev->flags) &&
7558 !test_bit(BlockedBadBlocks, &rdev->flags),
7559 msecs_to_jiffies(5000));
7560 rdev_dec_pending(rdev, mddev);
7562 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
7565 /* Bad block management.
7566 * We can record which blocks on each device are 'bad' and so just
7567 * fail those blocks, or that stripe, rather than the whole device.
7568 * Entries in the bad-block table are 64bits wide. This comprises:
7569 * Length of bad-range, in sectors: 0-511 for lengths 1-512
7570 * Start of bad-range, sector offset, 54 bits (allows 8 exbibytes)
7571 * A 'shift' can be set so that larger blocks are tracked and
7572 * consequently larger devices can be covered.
7573 * 'Acknowledged' flag - 1 bit. - the most significant bit.
7575 * Locking of the bad-block table uses a seqlock so md_is_badblock
7576 * might need to retry if it is very unlucky.
7577 * We will sometimes want to check for bad blocks in a bi_end_io function,
7578 * so we use the write_seqlock_irq variant.
7580 * When looking for a bad block we specify a range and want to
7581 * know if any block in the range is bad. So we binary-search
7582 * to the last range that starts at-or-before the given endpoint,
7583 * (or "before the sector after the target range")
7584 * then see if it ends after the given start.
7585 * We return
7586 * 0 if there are no known bad blocks in the range
7587 * 1 if there are known bad block which are all acknowledged
7588 * -1 if there are bad blocks which have not yet been acknowledged in metadata.
7589 * plus the start/length of the first bad section we overlap.
7591 int md_is_badblock(struct badblocks *bb, sector_t s, int sectors,
7592 sector_t *first_bad, int *bad_sectors)
7594 int hi;
7595 int lo = 0;
7596 u64 *p = bb->page;
7597 int rv = 0;
7598 sector_t target = s + sectors;
7599 unsigned seq;
7601 if (bb->shift > 0) {
7602 /* round the start down, and the end up */
7603 s >>= bb->shift;
7604 target += (1<<bb->shift) - 1;
7605 target >>= bb->shift;
7606 sectors = target - s;
7608 /* 'target' is now the first block after the bad range */
7610 retry:
7611 seq = read_seqbegin(&bb->lock);
7613 hi = bb->count;
7615 /* Binary search between lo and hi for 'target'
7616 * i.e. for the last range that starts before 'target'
7618 /* INVARIANT: ranges before 'lo' and at-or-after 'hi'
7619 * are known not to be the last range before target.
7620 * VARIANT: hi-lo is the number of possible
7621 * ranges, and decreases until it reaches 1
7623 while (hi - lo > 1) {
7624 int mid = (lo + hi) / 2;
7625 sector_t a = BB_OFFSET(p[mid]);
7626 if (a < target)
7627 /* This could still be the one, earlier ranges
7628 * could not. */
7629 lo = mid;
7630 else
7631 /* This and later ranges are definitely out. */
7632 hi = mid;
7634 /* 'lo' might be the last that started before target, but 'hi' isn't */
7635 if (hi > lo) {
7636 /* need to check all range that end after 's' to see if
7637 * any are unacknowledged.
7639 while (lo >= 0 &&
7640 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
7641 if (BB_OFFSET(p[lo]) < target) {
7642 /* starts before the end, and finishes after
7643 * the start, so they must overlap
7645 if (rv != -1 && BB_ACK(p[lo]))
7646 rv = 1;
7647 else
7648 rv = -1;
7649 *first_bad = BB_OFFSET(p[lo]);
7650 *bad_sectors = BB_LEN(p[lo]);
7652 lo--;
7656 if (read_seqretry(&bb->lock, seq))
7657 goto retry;
7659 return rv;
7661 EXPORT_SYMBOL_GPL(md_is_badblock);
7664 * Add a range of bad blocks to the table.
7665 * This might extend the table, or might contract it
7666 * if two adjacent ranges can be merged.
7667 * We binary-search to find the 'insertion' point, then
7668 * decide how best to handle it.
7670 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
7671 int acknowledged)
7673 u64 *p;
7674 int lo, hi;
7675 int rv = 1;
7677 if (bb->shift < 0)
7678 /* badblocks are disabled */
7679 return 0;
7681 if (bb->shift) {
7682 /* round the start down, and the end up */
7683 sector_t next = s + sectors;
7684 s >>= bb->shift;
7685 next += (1<<bb->shift) - 1;
7686 next >>= bb->shift;
7687 sectors = next - s;
7690 write_seqlock_irq(&bb->lock);
7692 p = bb->page;
7693 lo = 0;
7694 hi = bb->count;
7695 /* Find the last range that starts at-or-before 's' */
7696 while (hi - lo > 1) {
7697 int mid = (lo + hi) / 2;
7698 sector_t a = BB_OFFSET(p[mid]);
7699 if (a <= s)
7700 lo = mid;
7701 else
7702 hi = mid;
7704 if (hi > lo && BB_OFFSET(p[lo]) > s)
7705 hi = lo;
7707 if (hi > lo) {
7708 /* we found a range that might merge with the start
7709 * of our new range
7711 sector_t a = BB_OFFSET(p[lo]);
7712 sector_t e = a + BB_LEN(p[lo]);
7713 int ack = BB_ACK(p[lo]);
7714 if (e >= s) {
7715 /* Yes, we can merge with a previous range */
7716 if (s == a && s + sectors >= e)
7717 /* new range covers old */
7718 ack = acknowledged;
7719 else
7720 ack = ack && acknowledged;
7722 if (e < s + sectors)
7723 e = s + sectors;
7724 if (e - a <= BB_MAX_LEN) {
7725 p[lo] = BB_MAKE(a, e-a, ack);
7726 s = e;
7727 } else {
7728 /* does not all fit in one range,
7729 * make p[lo] maximal
7731 if (BB_LEN(p[lo]) != BB_MAX_LEN)
7732 p[lo] = BB_MAKE(a, BB_MAX_LEN, ack);
7733 s = a + BB_MAX_LEN;
7735 sectors = e - s;
7738 if (sectors && hi < bb->count) {
7739 /* 'hi' points to the first range that starts after 's'.
7740 * Maybe we can merge with the start of that range */
7741 sector_t a = BB_OFFSET(p[hi]);
7742 sector_t e = a + BB_LEN(p[hi]);
7743 int ack = BB_ACK(p[hi]);
7744 if (a <= s + sectors) {
7745 /* merging is possible */
7746 if (e <= s + sectors) {
7747 /* full overlap */
7748 e = s + sectors;
7749 ack = acknowledged;
7750 } else
7751 ack = ack && acknowledged;
7753 a = s;
7754 if (e - a <= BB_MAX_LEN) {
7755 p[hi] = BB_MAKE(a, e-a, ack);
7756 s = e;
7757 } else {
7758 p[hi] = BB_MAKE(a, BB_MAX_LEN, ack);
7759 s = a + BB_MAX_LEN;
7761 sectors = e - s;
7762 lo = hi;
7763 hi++;
7766 if (sectors == 0 && hi < bb->count) {
7767 /* we might be able to combine lo and hi */
7768 /* Note: 's' is at the end of 'lo' */
7769 sector_t a = BB_OFFSET(p[hi]);
7770 int lolen = BB_LEN(p[lo]);
7771 int hilen = BB_LEN(p[hi]);
7772 int newlen = lolen + hilen - (s - a);
7773 if (s >= a && newlen < BB_MAX_LEN) {
7774 /* yes, we can combine them */
7775 int ack = BB_ACK(p[lo]) && BB_ACK(p[hi]);
7776 p[lo] = BB_MAKE(BB_OFFSET(p[lo]), newlen, ack);
7777 memmove(p + hi, p + hi + 1,
7778 (bb->count - hi - 1) * 8);
7779 bb->count--;
7782 while (sectors) {
7783 /* didn't merge (it all).
7784 * Need to add a range just before 'hi' */
7785 if (bb->count >= MD_MAX_BADBLOCKS) {
7786 /* No room for more */
7787 rv = 0;
7788 break;
7789 } else {
7790 int this_sectors = sectors;
7791 memmove(p + hi + 1, p + hi,
7792 (bb->count - hi) * 8);
7793 bb->count++;
7795 if (this_sectors > BB_MAX_LEN)
7796 this_sectors = BB_MAX_LEN;
7797 p[hi] = BB_MAKE(s, this_sectors, acknowledged);
7798 sectors -= this_sectors;
7799 s += this_sectors;
7803 bb->changed = 1;
7804 if (!acknowledged)
7805 bb->unacked_exist = 1;
7806 write_sequnlock_irq(&bb->lock);
7808 return rv;
7811 int rdev_set_badblocks(mdk_rdev_t *rdev, sector_t s, int sectors,
7812 int acknowledged)
7814 int rv = md_set_badblocks(&rdev->badblocks,
7815 s + rdev->data_offset, sectors, acknowledged);
7816 if (rv) {
7817 /* Make sure they get written out promptly */
7818 set_bit(MD_CHANGE_CLEAN, &rdev->mddev->flags);
7819 md_wakeup_thread(rdev->mddev->thread);
7821 return rv;
7823 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
7826 * Remove a range of bad blocks from the table.
7827 * This may involve extending the table if we spilt a region,
7828 * but it must not fail. So if the table becomes full, we just
7829 * drop the remove request.
7831 static int md_clear_badblocks(struct badblocks *bb, sector_t s, int sectors)
7833 u64 *p;
7834 int lo, hi;
7835 sector_t target = s + sectors;
7836 int rv = 0;
7838 if (bb->shift > 0) {
7839 /* When clearing we round the start up and the end down.
7840 * This should not matter as the shift should align with
7841 * the block size and no rounding should ever be needed.
7842 * However it is better the think a block is bad when it
7843 * isn't than to think a block is not bad when it is.
7845 s += (1<<bb->shift) - 1;
7846 s >>= bb->shift;
7847 target >>= bb->shift;
7848 sectors = target - s;
7851 write_seqlock_irq(&bb->lock);
7853 p = bb->page;
7854 lo = 0;
7855 hi = bb->count;
7856 /* Find the last range that starts before 'target' */
7857 while (hi - lo > 1) {
7858 int mid = (lo + hi) / 2;
7859 sector_t a = BB_OFFSET(p[mid]);
7860 if (a < target)
7861 lo = mid;
7862 else
7863 hi = mid;
7865 if (hi > lo) {
7866 /* p[lo] is the last range that could overlap the
7867 * current range. Earlier ranges could also overlap,
7868 * but only this one can overlap the end of the range.
7870 if (BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > target) {
7871 /* Partial overlap, leave the tail of this range */
7872 int ack = BB_ACK(p[lo]);
7873 sector_t a = BB_OFFSET(p[lo]);
7874 sector_t end = a + BB_LEN(p[lo]);
7876 if (a < s) {
7877 /* we need to split this range */
7878 if (bb->count >= MD_MAX_BADBLOCKS) {
7879 rv = 0;
7880 goto out;
7882 memmove(p+lo+1, p+lo, (bb->count - lo) * 8);
7883 bb->count++;
7884 p[lo] = BB_MAKE(a, s-a, ack);
7885 lo++;
7887 p[lo] = BB_MAKE(target, end - target, ack);
7888 /* there is no longer an overlap */
7889 hi = lo;
7890 lo--;
7892 while (lo >= 0 &&
7893 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
7894 /* This range does overlap */
7895 if (BB_OFFSET(p[lo]) < s) {
7896 /* Keep the early parts of this range. */
7897 int ack = BB_ACK(p[lo]);
7898 sector_t start = BB_OFFSET(p[lo]);
7899 p[lo] = BB_MAKE(start, s - start, ack);
7900 /* now low doesn't overlap, so.. */
7901 break;
7903 lo--;
7905 /* 'lo' is strictly before, 'hi' is strictly after,
7906 * anything between needs to be discarded
7908 if (hi - lo > 1) {
7909 memmove(p+lo+1, p+hi, (bb->count - hi) * 8);
7910 bb->count -= (hi - lo - 1);
7914 bb->changed = 1;
7915 out:
7916 write_sequnlock_irq(&bb->lock);
7917 return rv;
7920 int rdev_clear_badblocks(mdk_rdev_t *rdev, sector_t s, int sectors)
7922 return md_clear_badblocks(&rdev->badblocks,
7923 s + rdev->data_offset,
7924 sectors);
7926 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
7929 * Acknowledge all bad blocks in a list.
7930 * This only succeeds if ->changed is clear. It is used by
7931 * in-kernel metadata updates
7933 void md_ack_all_badblocks(struct badblocks *bb)
7935 if (bb->page == NULL || bb->changed)
7936 /* no point even trying */
7937 return;
7938 write_seqlock_irq(&bb->lock);
7940 if (bb->changed == 0) {
7941 u64 *p = bb->page;
7942 int i;
7943 for (i = 0; i < bb->count ; i++) {
7944 if (!BB_ACK(p[i])) {
7945 sector_t start = BB_OFFSET(p[i]);
7946 int len = BB_LEN(p[i]);
7947 p[i] = BB_MAKE(start, len, 1);
7950 bb->unacked_exist = 0;
7952 write_sequnlock_irq(&bb->lock);
7954 EXPORT_SYMBOL_GPL(md_ack_all_badblocks);
7956 /* sysfs access to bad-blocks list.
7957 * We present two files.
7958 * 'bad-blocks' lists sector numbers and lengths of ranges that
7959 * are recorded as bad. The list is truncated to fit within
7960 * the one-page limit of sysfs.
7961 * Writing "sector length" to this file adds an acknowledged
7962 * bad block list.
7963 * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
7964 * been acknowledged. Writing to this file adds bad blocks
7965 * without acknowledging them. This is largely for testing.
7968 static ssize_t
7969 badblocks_show(struct badblocks *bb, char *page, int unack)
7971 size_t len;
7972 int i;
7973 u64 *p = bb->page;
7974 unsigned seq;
7976 if (bb->shift < 0)
7977 return 0;
7979 retry:
7980 seq = read_seqbegin(&bb->lock);
7982 len = 0;
7983 i = 0;
7985 while (len < PAGE_SIZE && i < bb->count) {
7986 sector_t s = BB_OFFSET(p[i]);
7987 unsigned int length = BB_LEN(p[i]);
7988 int ack = BB_ACK(p[i]);
7989 i++;
7991 if (unack && ack)
7992 continue;
7994 len += snprintf(page+len, PAGE_SIZE-len, "%llu %u\n",
7995 (unsigned long long)s << bb->shift,
7996 length << bb->shift);
7998 if (unack && len == 0)
7999 bb->unacked_exist = 0;
8001 if (read_seqretry(&bb->lock, seq))
8002 goto retry;
8004 return len;
8007 #define DO_DEBUG 1
8009 static ssize_t
8010 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack)
8012 unsigned long long sector;
8013 int length;
8014 char newline;
8015 #ifdef DO_DEBUG
8016 /* Allow clearing via sysfs *only* for testing/debugging.
8017 * Normally only a successful write may clear a badblock
8019 int clear = 0;
8020 if (page[0] == '-') {
8021 clear = 1;
8022 page++;
8024 #endif /* DO_DEBUG */
8026 switch (sscanf(page, "%llu %d%c", &sector, &length, &newline)) {
8027 case 3:
8028 if (newline != '\n')
8029 return -EINVAL;
8030 case 2:
8031 if (length <= 0)
8032 return -EINVAL;
8033 break;
8034 default:
8035 return -EINVAL;
8038 #ifdef DO_DEBUG
8039 if (clear) {
8040 md_clear_badblocks(bb, sector, length);
8041 return len;
8043 #endif /* DO_DEBUG */
8044 if (md_set_badblocks(bb, sector, length, !unack))
8045 return len;
8046 else
8047 return -ENOSPC;
8050 static int md_notify_reboot(struct notifier_block *this,
8051 unsigned long code, void *x)
8053 struct list_head *tmp;
8054 mddev_t *mddev;
8056 if ((code == SYS_DOWN) || (code == SYS_HALT) || (code == SYS_POWER_OFF)) {
8058 printk(KERN_INFO "md: stopping all md devices.\n");
8060 for_each_mddev(mddev, tmp)
8061 if (mddev_trylock(mddev)) {
8062 /* Force a switch to readonly even array
8063 * appears to still be in use. Hence
8064 * the '100'.
8066 md_set_readonly(mddev, 100);
8067 mddev_unlock(mddev);
8070 * certain more exotic SCSI devices are known to be
8071 * volatile wrt too early system reboots. While the
8072 * right place to handle this issue is the given
8073 * driver, we do want to have a safe RAID driver ...
8075 mdelay(1000*1);
8077 return NOTIFY_DONE;
8080 static struct notifier_block md_notifier = {
8081 .notifier_call = md_notify_reboot,
8082 .next = NULL,
8083 .priority = INT_MAX, /* before any real devices */
8086 static void md_geninit(void)
8088 dprintk("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
8090 proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
8093 static int __init md_init(void)
8095 int ret = -ENOMEM;
8097 md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
8098 if (!md_wq)
8099 goto err_wq;
8101 md_misc_wq = alloc_workqueue("md_misc", 0, 0);
8102 if (!md_misc_wq)
8103 goto err_misc_wq;
8105 if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
8106 goto err_md;
8108 if ((ret = register_blkdev(0, "mdp")) < 0)
8109 goto err_mdp;
8110 mdp_major = ret;
8112 blk_register_region(MKDEV(MD_MAJOR, 0), 1UL<<MINORBITS, THIS_MODULE,
8113 md_probe, NULL, NULL);
8114 blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
8115 md_probe, NULL, NULL);
8117 register_reboot_notifier(&md_notifier);
8118 raid_table_header = register_sysctl_table(raid_root_table);
8120 md_geninit();
8121 return 0;
8123 err_mdp:
8124 unregister_blkdev(MD_MAJOR, "md");
8125 err_md:
8126 destroy_workqueue(md_misc_wq);
8127 err_misc_wq:
8128 destroy_workqueue(md_wq);
8129 err_wq:
8130 return ret;
8133 #ifndef MODULE
8136 * Searches all registered partitions for autorun RAID arrays
8137 * at boot time.
8140 static LIST_HEAD(all_detected_devices);
8141 struct detected_devices_node {
8142 struct list_head list;
8143 dev_t dev;
8146 void md_autodetect_dev(dev_t dev)
8148 struct detected_devices_node *node_detected_dev;
8150 node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
8151 if (node_detected_dev) {
8152 node_detected_dev->dev = dev;
8153 list_add_tail(&node_detected_dev->list, &all_detected_devices);
8154 } else {
8155 printk(KERN_CRIT "md: md_autodetect_dev: kzalloc failed"
8156 ", skipping dev(%d,%d)\n", MAJOR(dev), MINOR(dev));
8161 static void autostart_arrays(int part)
8163 mdk_rdev_t *rdev;
8164 struct detected_devices_node *node_detected_dev;
8165 dev_t dev;
8166 int i_scanned, i_passed;
8168 i_scanned = 0;
8169 i_passed = 0;
8171 printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
8173 while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
8174 i_scanned++;
8175 node_detected_dev = list_entry(all_detected_devices.next,
8176 struct detected_devices_node, list);
8177 list_del(&node_detected_dev->list);
8178 dev = node_detected_dev->dev;
8179 kfree(node_detected_dev);
8180 rdev = md_import_device(dev,0, 90);
8181 if (IS_ERR(rdev))
8182 continue;
8184 if (test_bit(Faulty, &rdev->flags)) {
8185 MD_BUG();
8186 continue;
8188 set_bit(AutoDetected, &rdev->flags);
8189 list_add(&rdev->same_set, &pending_raid_disks);
8190 i_passed++;
8193 printk(KERN_INFO "md: Scanned %d and added %d devices.\n",
8194 i_scanned, i_passed);
8196 autorun_devices(part);
8199 #endif /* !MODULE */
8201 static __exit void md_exit(void)
8203 mddev_t *mddev;
8204 struct list_head *tmp;
8206 blk_unregister_region(MKDEV(MD_MAJOR,0), 1U << MINORBITS);
8207 blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
8209 unregister_blkdev(MD_MAJOR,"md");
8210 unregister_blkdev(mdp_major, "mdp");
8211 unregister_reboot_notifier(&md_notifier);
8212 unregister_sysctl_table(raid_table_header);
8213 remove_proc_entry("mdstat", NULL);
8214 for_each_mddev(mddev, tmp) {
8215 export_array(mddev);
8216 mddev->hold_active = 0;
8218 destroy_workqueue(md_misc_wq);
8219 destroy_workqueue(md_wq);
8222 subsys_initcall(md_init);
8223 module_exit(md_exit)
8225 static int get_ro(char *buffer, struct kernel_param *kp)
8227 return sprintf(buffer, "%d", start_readonly);
8229 static int set_ro(const char *val, struct kernel_param *kp)
8231 char *e;
8232 int num = simple_strtoul(val, &e, 10);
8233 if (*val && (*e == '\0' || *e == '\n')) {
8234 start_readonly = num;
8235 return 0;
8237 return -EINVAL;
8240 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
8241 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
8243 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
8245 EXPORT_SYMBOL(register_md_personality);
8246 EXPORT_SYMBOL(unregister_md_personality);
8247 EXPORT_SYMBOL(md_error);
8248 EXPORT_SYMBOL(md_done_sync);
8249 EXPORT_SYMBOL(md_write_start);
8250 EXPORT_SYMBOL(md_write_end);
8251 EXPORT_SYMBOL(md_register_thread);
8252 EXPORT_SYMBOL(md_unregister_thread);
8253 EXPORT_SYMBOL(md_wakeup_thread);
8254 EXPORT_SYMBOL(md_check_recovery);
8255 MODULE_LICENSE("GPL");
8256 MODULE_DESCRIPTION("MD RAID framework");
8257 MODULE_ALIAS("md");
8258 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);