md/raid1: avoid reading from known bad blocks.
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / drivers / md / md.c
blob48217e8aa0ebef7d957e288dace9e5f6510437bf
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/reboot.h>
48 #include <linux/file.h>
49 #include <linux/compat.h>
50 #include <linux/delay.h>
51 #include <linux/raid/md_p.h>
52 #include <linux/raid/md_u.h>
53 #include <linux/slab.h>
54 #include "md.h"
55 #include "bitmap.h"
57 #define DEBUG 0
58 #define dprintk(x...) ((void)(DEBUG && printk(x)))
60 #ifndef MODULE
61 static void autostart_arrays(int part);
62 #endif
64 static LIST_HEAD(pers_list);
65 static DEFINE_SPINLOCK(pers_lock);
67 static void md_print_devices(void);
69 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
70 static struct workqueue_struct *md_wq;
71 static struct workqueue_struct *md_misc_wq;
73 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
76 * Default number of read corrections we'll attempt on an rdev
77 * before ejecting it from the array. We divide the read error
78 * count by 2 for every hour elapsed between read errors.
80 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
82 * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
83 * is 1000 KB/sec, so the extra system load does not show up that much.
84 * Increase it if you want to have more _guaranteed_ speed. Note that
85 * the RAID driver will use the maximum available bandwidth if the IO
86 * subsystem is idle. There is also an 'absolute maximum' reconstruction
87 * speed limit - in case reconstruction slows down your system despite
88 * idle IO detection.
90 * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
91 * or /sys/block/mdX/md/sync_speed_{min,max}
94 static int sysctl_speed_limit_min = 1000;
95 static int sysctl_speed_limit_max = 200000;
96 static inline int speed_min(mddev_t *mddev)
98 return mddev->sync_speed_min ?
99 mddev->sync_speed_min : sysctl_speed_limit_min;
102 static inline int speed_max(mddev_t *mddev)
104 return mddev->sync_speed_max ?
105 mddev->sync_speed_max : sysctl_speed_limit_max;
108 static struct ctl_table_header *raid_table_header;
110 static ctl_table raid_table[] = {
112 .procname = "speed_limit_min",
113 .data = &sysctl_speed_limit_min,
114 .maxlen = sizeof(int),
115 .mode = S_IRUGO|S_IWUSR,
116 .proc_handler = proc_dointvec,
119 .procname = "speed_limit_max",
120 .data = &sysctl_speed_limit_max,
121 .maxlen = sizeof(int),
122 .mode = S_IRUGO|S_IWUSR,
123 .proc_handler = proc_dointvec,
128 static ctl_table raid_dir_table[] = {
130 .procname = "raid",
131 .maxlen = 0,
132 .mode = S_IRUGO|S_IXUGO,
133 .child = raid_table,
138 static ctl_table raid_root_table[] = {
140 .procname = "dev",
141 .maxlen = 0,
142 .mode = 0555,
143 .child = raid_dir_table,
148 static const struct block_device_operations md_fops;
150 static int start_readonly;
152 /* bio_clone_mddev
153 * like bio_clone, but with a local bio set
156 static void mddev_bio_destructor(struct bio *bio)
158 mddev_t *mddev, **mddevp;
160 mddevp = (void*)bio;
161 mddev = mddevp[-1];
163 bio_free(bio, mddev->bio_set);
166 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
167 mddev_t *mddev)
169 struct bio *b;
170 mddev_t **mddevp;
172 if (!mddev || !mddev->bio_set)
173 return bio_alloc(gfp_mask, nr_iovecs);
175 b = bio_alloc_bioset(gfp_mask, nr_iovecs,
176 mddev->bio_set);
177 if (!b)
178 return NULL;
179 mddevp = (void*)b;
180 mddevp[-1] = mddev;
181 b->bi_destructor = mddev_bio_destructor;
182 return b;
184 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
186 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
187 mddev_t *mddev)
189 struct bio *b;
190 mddev_t **mddevp;
192 if (!mddev || !mddev->bio_set)
193 return bio_clone(bio, gfp_mask);
195 b = bio_alloc_bioset(gfp_mask, bio->bi_max_vecs,
196 mddev->bio_set);
197 if (!b)
198 return NULL;
199 mddevp = (void*)b;
200 mddevp[-1] = mddev;
201 b->bi_destructor = mddev_bio_destructor;
202 __bio_clone(b, bio);
203 if (bio_integrity(bio)) {
204 int ret;
206 ret = bio_integrity_clone(b, bio, gfp_mask, mddev->bio_set);
208 if (ret < 0) {
209 bio_put(b);
210 return NULL;
214 return b;
216 EXPORT_SYMBOL_GPL(bio_clone_mddev);
218 void md_trim_bio(struct bio *bio, int offset, int size)
220 /* 'bio' is a cloned bio which we need to trim to match
221 * the given offset and size.
222 * This requires adjusting bi_sector, bi_size, and bi_io_vec
224 int i;
225 struct bio_vec *bvec;
226 int sofar = 0;
228 size <<= 9;
229 if (offset == 0 && size == bio->bi_size)
230 return;
232 bio->bi_sector += offset;
233 bio->bi_size = size;
234 offset <<= 9;
235 clear_bit(BIO_SEG_VALID, &bio->bi_flags);
237 while (bio->bi_idx < bio->bi_vcnt &&
238 bio->bi_io_vec[bio->bi_idx].bv_len <= offset) {
239 /* remove this whole bio_vec */
240 offset -= bio->bi_io_vec[bio->bi_idx].bv_len;
241 bio->bi_idx++;
243 if (bio->bi_idx < bio->bi_vcnt) {
244 bio->bi_io_vec[bio->bi_idx].bv_offset += offset;
245 bio->bi_io_vec[bio->bi_idx].bv_len -= offset;
247 /* avoid any complications with bi_idx being non-zero*/
248 if (bio->bi_idx) {
249 memmove(bio->bi_io_vec, bio->bi_io_vec+bio->bi_idx,
250 (bio->bi_vcnt - bio->bi_idx) * sizeof(struct bio_vec));
251 bio->bi_vcnt -= bio->bi_idx;
252 bio->bi_idx = 0;
254 /* Make sure vcnt and last bv are not too big */
255 bio_for_each_segment(bvec, bio, i) {
256 if (sofar + bvec->bv_len > size)
257 bvec->bv_len = size - sofar;
258 if (bvec->bv_len == 0) {
259 bio->bi_vcnt = i;
260 break;
262 sofar += bvec->bv_len;
265 EXPORT_SYMBOL_GPL(md_trim_bio);
268 * We have a system wide 'event count' that is incremented
269 * on any 'interesting' event, and readers of /proc/mdstat
270 * can use 'poll' or 'select' to find out when the event
271 * count increases.
273 * Events are:
274 * start array, stop array, error, add device, remove device,
275 * start build, activate spare
277 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
278 static atomic_t md_event_count;
279 void md_new_event(mddev_t *mddev)
281 atomic_inc(&md_event_count);
282 wake_up(&md_event_waiters);
284 EXPORT_SYMBOL_GPL(md_new_event);
286 /* Alternate version that can be called from interrupts
287 * when calling sysfs_notify isn't needed.
289 static void md_new_event_inintr(mddev_t *mddev)
291 atomic_inc(&md_event_count);
292 wake_up(&md_event_waiters);
296 * Enables to iterate over all existing md arrays
297 * all_mddevs_lock protects this list.
299 static LIST_HEAD(all_mddevs);
300 static DEFINE_SPINLOCK(all_mddevs_lock);
304 * iterates through all used mddevs in the system.
305 * We take care to grab the all_mddevs_lock whenever navigating
306 * the list, and to always hold a refcount when unlocked.
307 * Any code which breaks out of this loop while own
308 * a reference to the current mddev and must mddev_put it.
310 #define for_each_mddev(mddev,tmp) \
312 for (({ spin_lock(&all_mddevs_lock); \
313 tmp = all_mddevs.next; \
314 mddev = NULL;}); \
315 ({ if (tmp != &all_mddevs) \
316 mddev_get(list_entry(tmp, mddev_t, all_mddevs));\
317 spin_unlock(&all_mddevs_lock); \
318 if (mddev) mddev_put(mddev); \
319 mddev = list_entry(tmp, mddev_t, all_mddevs); \
320 tmp != &all_mddevs;}); \
321 ({ spin_lock(&all_mddevs_lock); \
322 tmp = tmp->next;}) \
326 /* Rather than calling directly into the personality make_request function,
327 * IO requests come here first so that we can check if the device is
328 * being suspended pending a reconfiguration.
329 * We hold a refcount over the call to ->make_request. By the time that
330 * call has finished, the bio has been linked into some internal structure
331 * and so is visible to ->quiesce(), so we don't need the refcount any more.
333 static int md_make_request(struct request_queue *q, struct bio *bio)
335 const int rw = bio_data_dir(bio);
336 mddev_t *mddev = q->queuedata;
337 int rv;
338 int cpu;
339 unsigned int sectors;
341 if (mddev == NULL || mddev->pers == NULL
342 || !mddev->ready) {
343 bio_io_error(bio);
344 return 0;
346 smp_rmb(); /* Ensure implications of 'active' are visible */
347 rcu_read_lock();
348 if (mddev->suspended) {
349 DEFINE_WAIT(__wait);
350 for (;;) {
351 prepare_to_wait(&mddev->sb_wait, &__wait,
352 TASK_UNINTERRUPTIBLE);
353 if (!mddev->suspended)
354 break;
355 rcu_read_unlock();
356 schedule();
357 rcu_read_lock();
359 finish_wait(&mddev->sb_wait, &__wait);
361 atomic_inc(&mddev->active_io);
362 rcu_read_unlock();
365 * save the sectors now since our bio can
366 * go away inside make_request
368 sectors = bio_sectors(bio);
369 rv = mddev->pers->make_request(mddev, bio);
371 cpu = part_stat_lock();
372 part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
373 part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw], sectors);
374 part_stat_unlock();
376 if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
377 wake_up(&mddev->sb_wait);
379 return rv;
382 /* mddev_suspend makes sure no new requests are submitted
383 * to the device, and that any requests that have been submitted
384 * are completely handled.
385 * Once ->stop is called and completes, the module will be completely
386 * unused.
388 void mddev_suspend(mddev_t *mddev)
390 BUG_ON(mddev->suspended);
391 mddev->suspended = 1;
392 synchronize_rcu();
393 wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
394 mddev->pers->quiesce(mddev, 1);
396 EXPORT_SYMBOL_GPL(mddev_suspend);
398 void mddev_resume(mddev_t *mddev)
400 mddev->suspended = 0;
401 wake_up(&mddev->sb_wait);
402 mddev->pers->quiesce(mddev, 0);
404 md_wakeup_thread(mddev->thread);
405 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
407 EXPORT_SYMBOL_GPL(mddev_resume);
409 int mddev_congested(mddev_t *mddev, int bits)
411 return mddev->suspended;
413 EXPORT_SYMBOL(mddev_congested);
416 * Generic flush handling for md
419 static void md_end_flush(struct bio *bio, int err)
421 mdk_rdev_t *rdev = bio->bi_private;
422 mddev_t *mddev = rdev->mddev;
424 rdev_dec_pending(rdev, mddev);
426 if (atomic_dec_and_test(&mddev->flush_pending)) {
427 /* The pre-request flush has finished */
428 queue_work(md_wq, &mddev->flush_work);
430 bio_put(bio);
433 static void md_submit_flush_data(struct work_struct *ws);
435 static void submit_flushes(struct work_struct *ws)
437 mddev_t *mddev = container_of(ws, mddev_t, flush_work);
438 mdk_rdev_t *rdev;
440 INIT_WORK(&mddev->flush_work, md_submit_flush_data);
441 atomic_set(&mddev->flush_pending, 1);
442 rcu_read_lock();
443 list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
444 if (rdev->raid_disk >= 0 &&
445 !test_bit(Faulty, &rdev->flags)) {
446 /* Take two references, one is dropped
447 * when request finishes, one after
448 * we reclaim rcu_read_lock
450 struct bio *bi;
451 atomic_inc(&rdev->nr_pending);
452 atomic_inc(&rdev->nr_pending);
453 rcu_read_unlock();
454 bi = bio_alloc_mddev(GFP_KERNEL, 0, mddev);
455 bi->bi_end_io = md_end_flush;
456 bi->bi_private = rdev;
457 bi->bi_bdev = rdev->bdev;
458 atomic_inc(&mddev->flush_pending);
459 submit_bio(WRITE_FLUSH, bi);
460 rcu_read_lock();
461 rdev_dec_pending(rdev, mddev);
463 rcu_read_unlock();
464 if (atomic_dec_and_test(&mddev->flush_pending))
465 queue_work(md_wq, &mddev->flush_work);
468 static void md_submit_flush_data(struct work_struct *ws)
470 mddev_t *mddev = container_of(ws, mddev_t, flush_work);
471 struct bio *bio = mddev->flush_bio;
473 if (bio->bi_size == 0)
474 /* an empty barrier - all done */
475 bio_endio(bio, 0);
476 else {
477 bio->bi_rw &= ~REQ_FLUSH;
478 if (mddev->pers->make_request(mddev, bio))
479 generic_make_request(bio);
482 mddev->flush_bio = NULL;
483 wake_up(&mddev->sb_wait);
486 void md_flush_request(mddev_t *mddev, struct bio *bio)
488 spin_lock_irq(&mddev->write_lock);
489 wait_event_lock_irq(mddev->sb_wait,
490 !mddev->flush_bio,
491 mddev->write_lock, /*nothing*/);
492 mddev->flush_bio = bio;
493 spin_unlock_irq(&mddev->write_lock);
495 INIT_WORK(&mddev->flush_work, submit_flushes);
496 queue_work(md_wq, &mddev->flush_work);
498 EXPORT_SYMBOL(md_flush_request);
500 /* Support for plugging.
501 * This mirrors the plugging support in request_queue, but does not
502 * require having a whole queue or request structures.
503 * We allocate an md_plug_cb for each md device and each thread it gets
504 * plugged on. This links tot the private plug_handle structure in the
505 * personality data where we keep a count of the number of outstanding
506 * plugs so other code can see if a plug is active.
508 struct md_plug_cb {
509 struct blk_plug_cb cb;
510 mddev_t *mddev;
513 static void plugger_unplug(struct blk_plug_cb *cb)
515 struct md_plug_cb *mdcb = container_of(cb, struct md_plug_cb, cb);
516 if (atomic_dec_and_test(&mdcb->mddev->plug_cnt))
517 md_wakeup_thread(mdcb->mddev->thread);
518 kfree(mdcb);
521 /* Check that an unplug wakeup will come shortly.
522 * If not, wakeup the md thread immediately
524 int mddev_check_plugged(mddev_t *mddev)
526 struct blk_plug *plug = current->plug;
527 struct md_plug_cb *mdcb;
529 if (!plug)
530 return 0;
532 list_for_each_entry(mdcb, &plug->cb_list, cb.list) {
533 if (mdcb->cb.callback == plugger_unplug &&
534 mdcb->mddev == mddev) {
535 /* Already on the list, move to top */
536 if (mdcb != list_first_entry(&plug->cb_list,
537 struct md_plug_cb,
538 cb.list))
539 list_move(&mdcb->cb.list, &plug->cb_list);
540 return 1;
543 /* Not currently on the callback list */
544 mdcb = kmalloc(sizeof(*mdcb), GFP_ATOMIC);
545 if (!mdcb)
546 return 0;
548 mdcb->mddev = mddev;
549 mdcb->cb.callback = plugger_unplug;
550 atomic_inc(&mddev->plug_cnt);
551 list_add(&mdcb->cb.list, &plug->cb_list);
552 return 1;
554 EXPORT_SYMBOL_GPL(mddev_check_plugged);
556 static inline mddev_t *mddev_get(mddev_t *mddev)
558 atomic_inc(&mddev->active);
559 return mddev;
562 static void mddev_delayed_delete(struct work_struct *ws);
564 static void mddev_put(mddev_t *mddev)
566 struct bio_set *bs = NULL;
568 if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
569 return;
570 if (!mddev->raid_disks && list_empty(&mddev->disks) &&
571 mddev->ctime == 0 && !mddev->hold_active) {
572 /* Array is not configured at all, and not held active,
573 * so destroy it */
574 list_del(&mddev->all_mddevs);
575 bs = mddev->bio_set;
576 mddev->bio_set = NULL;
577 if (mddev->gendisk) {
578 /* We did a probe so need to clean up. Call
579 * queue_work inside the spinlock so that
580 * flush_workqueue() after mddev_find will
581 * succeed in waiting for the work to be done.
583 INIT_WORK(&mddev->del_work, mddev_delayed_delete);
584 queue_work(md_misc_wq, &mddev->del_work);
585 } else
586 kfree(mddev);
588 spin_unlock(&all_mddevs_lock);
589 if (bs)
590 bioset_free(bs);
593 void mddev_init(mddev_t *mddev)
595 mutex_init(&mddev->open_mutex);
596 mutex_init(&mddev->reconfig_mutex);
597 mutex_init(&mddev->bitmap_info.mutex);
598 INIT_LIST_HEAD(&mddev->disks);
599 INIT_LIST_HEAD(&mddev->all_mddevs);
600 init_timer(&mddev->safemode_timer);
601 atomic_set(&mddev->active, 1);
602 atomic_set(&mddev->openers, 0);
603 atomic_set(&mddev->active_io, 0);
604 atomic_set(&mddev->plug_cnt, 0);
605 spin_lock_init(&mddev->write_lock);
606 atomic_set(&mddev->flush_pending, 0);
607 init_waitqueue_head(&mddev->sb_wait);
608 init_waitqueue_head(&mddev->recovery_wait);
609 mddev->reshape_position = MaxSector;
610 mddev->resync_min = 0;
611 mddev->resync_max = MaxSector;
612 mddev->level = LEVEL_NONE;
614 EXPORT_SYMBOL_GPL(mddev_init);
616 static mddev_t * mddev_find(dev_t unit)
618 mddev_t *mddev, *new = NULL;
620 if (unit && MAJOR(unit) != MD_MAJOR)
621 unit &= ~((1<<MdpMinorShift)-1);
623 retry:
624 spin_lock(&all_mddevs_lock);
626 if (unit) {
627 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
628 if (mddev->unit == unit) {
629 mddev_get(mddev);
630 spin_unlock(&all_mddevs_lock);
631 kfree(new);
632 return mddev;
635 if (new) {
636 list_add(&new->all_mddevs, &all_mddevs);
637 spin_unlock(&all_mddevs_lock);
638 new->hold_active = UNTIL_IOCTL;
639 return new;
641 } else if (new) {
642 /* find an unused unit number */
643 static int next_minor = 512;
644 int start = next_minor;
645 int is_free = 0;
646 int dev = 0;
647 while (!is_free) {
648 dev = MKDEV(MD_MAJOR, next_minor);
649 next_minor++;
650 if (next_minor > MINORMASK)
651 next_minor = 0;
652 if (next_minor == start) {
653 /* Oh dear, all in use. */
654 spin_unlock(&all_mddevs_lock);
655 kfree(new);
656 return NULL;
659 is_free = 1;
660 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
661 if (mddev->unit == dev) {
662 is_free = 0;
663 break;
666 new->unit = dev;
667 new->md_minor = MINOR(dev);
668 new->hold_active = UNTIL_STOP;
669 list_add(&new->all_mddevs, &all_mddevs);
670 spin_unlock(&all_mddevs_lock);
671 return new;
673 spin_unlock(&all_mddevs_lock);
675 new = kzalloc(sizeof(*new), GFP_KERNEL);
676 if (!new)
677 return NULL;
679 new->unit = unit;
680 if (MAJOR(unit) == MD_MAJOR)
681 new->md_minor = MINOR(unit);
682 else
683 new->md_minor = MINOR(unit) >> MdpMinorShift;
685 mddev_init(new);
687 goto retry;
690 static inline int mddev_lock(mddev_t * mddev)
692 return mutex_lock_interruptible(&mddev->reconfig_mutex);
695 static inline int mddev_is_locked(mddev_t *mddev)
697 return mutex_is_locked(&mddev->reconfig_mutex);
700 static inline int mddev_trylock(mddev_t * mddev)
702 return mutex_trylock(&mddev->reconfig_mutex);
705 static struct attribute_group md_redundancy_group;
707 static void mddev_unlock(mddev_t * mddev)
709 if (mddev->to_remove) {
710 /* These cannot be removed under reconfig_mutex as
711 * an access to the files will try to take reconfig_mutex
712 * while holding the file unremovable, which leads to
713 * a deadlock.
714 * So hold set sysfs_active while the remove in happeing,
715 * and anything else which might set ->to_remove or my
716 * otherwise change the sysfs namespace will fail with
717 * -EBUSY if sysfs_active is still set.
718 * We set sysfs_active under reconfig_mutex and elsewhere
719 * test it under the same mutex to ensure its correct value
720 * is seen.
722 struct attribute_group *to_remove = mddev->to_remove;
723 mddev->to_remove = NULL;
724 mddev->sysfs_active = 1;
725 mutex_unlock(&mddev->reconfig_mutex);
727 if (mddev->kobj.sd) {
728 if (to_remove != &md_redundancy_group)
729 sysfs_remove_group(&mddev->kobj, to_remove);
730 if (mddev->pers == NULL ||
731 mddev->pers->sync_request == NULL) {
732 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
733 if (mddev->sysfs_action)
734 sysfs_put(mddev->sysfs_action);
735 mddev->sysfs_action = NULL;
738 mddev->sysfs_active = 0;
739 } else
740 mutex_unlock(&mddev->reconfig_mutex);
742 md_wakeup_thread(mddev->thread);
745 static mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
747 mdk_rdev_t *rdev;
749 list_for_each_entry(rdev, &mddev->disks, same_set)
750 if (rdev->desc_nr == nr)
751 return rdev;
753 return NULL;
756 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
758 mdk_rdev_t *rdev;
760 list_for_each_entry(rdev, &mddev->disks, same_set)
761 if (rdev->bdev->bd_dev == dev)
762 return rdev;
764 return NULL;
767 static struct mdk_personality *find_pers(int level, char *clevel)
769 struct mdk_personality *pers;
770 list_for_each_entry(pers, &pers_list, list) {
771 if (level != LEVEL_NONE && pers->level == level)
772 return pers;
773 if (strcmp(pers->name, clevel)==0)
774 return pers;
776 return NULL;
779 /* return the offset of the super block in 512byte sectors */
780 static inline sector_t calc_dev_sboffset(mdk_rdev_t *rdev)
782 sector_t num_sectors = i_size_read(rdev->bdev->bd_inode) / 512;
783 return MD_NEW_SIZE_SECTORS(num_sectors);
786 static int alloc_disk_sb(mdk_rdev_t * rdev)
788 if (rdev->sb_page)
789 MD_BUG();
791 rdev->sb_page = alloc_page(GFP_KERNEL);
792 if (!rdev->sb_page) {
793 printk(KERN_ALERT "md: out of memory.\n");
794 return -ENOMEM;
797 return 0;
800 static void free_disk_sb(mdk_rdev_t * rdev)
802 if (rdev->sb_page) {
803 put_page(rdev->sb_page);
804 rdev->sb_loaded = 0;
805 rdev->sb_page = NULL;
806 rdev->sb_start = 0;
807 rdev->sectors = 0;
809 if (rdev->bb_page) {
810 put_page(rdev->bb_page);
811 rdev->bb_page = NULL;
816 static void super_written(struct bio *bio, int error)
818 mdk_rdev_t *rdev = bio->bi_private;
819 mddev_t *mddev = rdev->mddev;
821 if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
822 printk("md: super_written gets error=%d, uptodate=%d\n",
823 error, test_bit(BIO_UPTODATE, &bio->bi_flags));
824 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
825 md_error(mddev, rdev);
828 if (atomic_dec_and_test(&mddev->pending_writes))
829 wake_up(&mddev->sb_wait);
830 bio_put(bio);
833 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
834 sector_t sector, int size, struct page *page)
836 /* write first size bytes of page to sector of rdev
837 * Increment mddev->pending_writes before returning
838 * and decrement it on completion, waking up sb_wait
839 * if zero is reached.
840 * If an error occurred, call md_error
842 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
844 bio->bi_bdev = rdev->meta_bdev ? rdev->meta_bdev : rdev->bdev;
845 bio->bi_sector = sector;
846 bio_add_page(bio, page, size, 0);
847 bio->bi_private = rdev;
848 bio->bi_end_io = super_written;
850 atomic_inc(&mddev->pending_writes);
851 submit_bio(REQ_WRITE | REQ_SYNC | REQ_FLUSH | REQ_FUA, bio);
854 void md_super_wait(mddev_t *mddev)
856 /* wait for all superblock writes that were scheduled to complete */
857 DEFINE_WAIT(wq);
858 for(;;) {
859 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
860 if (atomic_read(&mddev->pending_writes)==0)
861 break;
862 schedule();
864 finish_wait(&mddev->sb_wait, &wq);
867 static void bi_complete(struct bio *bio, int error)
869 complete((struct completion*)bio->bi_private);
872 int sync_page_io(mdk_rdev_t *rdev, sector_t sector, int size,
873 struct page *page, int rw, bool metadata_op)
875 struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
876 struct completion event;
877 int ret;
879 rw |= REQ_SYNC;
881 bio->bi_bdev = (metadata_op && rdev->meta_bdev) ?
882 rdev->meta_bdev : rdev->bdev;
883 if (metadata_op)
884 bio->bi_sector = sector + rdev->sb_start;
885 else
886 bio->bi_sector = sector + rdev->data_offset;
887 bio_add_page(bio, page, size, 0);
888 init_completion(&event);
889 bio->bi_private = &event;
890 bio->bi_end_io = bi_complete;
891 submit_bio(rw, bio);
892 wait_for_completion(&event);
894 ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
895 bio_put(bio);
896 return ret;
898 EXPORT_SYMBOL_GPL(sync_page_io);
900 static int read_disk_sb(mdk_rdev_t * rdev, int size)
902 char b[BDEVNAME_SIZE];
903 if (!rdev->sb_page) {
904 MD_BUG();
905 return -EINVAL;
907 if (rdev->sb_loaded)
908 return 0;
911 if (!sync_page_io(rdev, 0, size, rdev->sb_page, READ, true))
912 goto fail;
913 rdev->sb_loaded = 1;
914 return 0;
916 fail:
917 printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
918 bdevname(rdev->bdev,b));
919 return -EINVAL;
922 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
924 return sb1->set_uuid0 == sb2->set_uuid0 &&
925 sb1->set_uuid1 == sb2->set_uuid1 &&
926 sb1->set_uuid2 == sb2->set_uuid2 &&
927 sb1->set_uuid3 == sb2->set_uuid3;
930 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
932 int ret;
933 mdp_super_t *tmp1, *tmp2;
935 tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
936 tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
938 if (!tmp1 || !tmp2) {
939 ret = 0;
940 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
941 goto abort;
944 *tmp1 = *sb1;
945 *tmp2 = *sb2;
948 * nr_disks is not constant
950 tmp1->nr_disks = 0;
951 tmp2->nr_disks = 0;
953 ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
954 abort:
955 kfree(tmp1);
956 kfree(tmp2);
957 return ret;
961 static u32 md_csum_fold(u32 csum)
963 csum = (csum & 0xffff) + (csum >> 16);
964 return (csum & 0xffff) + (csum >> 16);
967 static unsigned int calc_sb_csum(mdp_super_t * sb)
969 u64 newcsum = 0;
970 u32 *sb32 = (u32*)sb;
971 int i;
972 unsigned int disk_csum, csum;
974 disk_csum = sb->sb_csum;
975 sb->sb_csum = 0;
977 for (i = 0; i < MD_SB_BYTES/4 ; i++)
978 newcsum += sb32[i];
979 csum = (newcsum & 0xffffffff) + (newcsum>>32);
982 #ifdef CONFIG_ALPHA
983 /* This used to use csum_partial, which was wrong for several
984 * reasons including that different results are returned on
985 * different architectures. It isn't critical that we get exactly
986 * the same return value as before (we always csum_fold before
987 * testing, and that removes any differences). However as we
988 * know that csum_partial always returned a 16bit value on
989 * alphas, do a fold to maximise conformity to previous behaviour.
991 sb->sb_csum = md_csum_fold(disk_csum);
992 #else
993 sb->sb_csum = disk_csum;
994 #endif
995 return csum;
1000 * Handle superblock details.
1001 * We want to be able to handle multiple superblock formats
1002 * so we have a common interface to them all, and an array of
1003 * different handlers.
1004 * We rely on user-space to write the initial superblock, and support
1005 * reading and updating of superblocks.
1006 * Interface methods are:
1007 * int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
1008 * loads and validates a superblock on dev.
1009 * if refdev != NULL, compare superblocks on both devices
1010 * Return:
1011 * 0 - dev has a superblock that is compatible with refdev
1012 * 1 - dev has a superblock that is compatible and newer than refdev
1013 * so dev should be used as the refdev in future
1014 * -EINVAL superblock incompatible or invalid
1015 * -othererror e.g. -EIO
1017 * int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
1018 * Verify that dev is acceptable into mddev.
1019 * The first time, mddev->raid_disks will be 0, and data from
1020 * dev should be merged in. Subsequent calls check that dev
1021 * is new enough. Return 0 or -EINVAL
1023 * void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
1024 * Update the superblock for rdev with data in mddev
1025 * This does not write to disc.
1029 struct super_type {
1030 char *name;
1031 struct module *owner;
1032 int (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev,
1033 int minor_version);
1034 int (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
1035 void (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
1036 unsigned long long (*rdev_size_change)(mdk_rdev_t *rdev,
1037 sector_t num_sectors);
1041 * Check that the given mddev has no bitmap.
1043 * This function is called from the run method of all personalities that do not
1044 * support bitmaps. It prints an error message and returns non-zero if mddev
1045 * has a bitmap. Otherwise, it returns 0.
1048 int md_check_no_bitmap(mddev_t *mddev)
1050 if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
1051 return 0;
1052 printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
1053 mdname(mddev), mddev->pers->name);
1054 return 1;
1056 EXPORT_SYMBOL(md_check_no_bitmap);
1059 * load_super for 0.90.0
1061 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1063 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1064 mdp_super_t *sb;
1065 int ret;
1068 * Calculate the position of the superblock (512byte sectors),
1069 * it's at the end of the disk.
1071 * It also happens to be a multiple of 4Kb.
1073 rdev->sb_start = calc_dev_sboffset(rdev);
1075 ret = read_disk_sb(rdev, MD_SB_BYTES);
1076 if (ret) return ret;
1078 ret = -EINVAL;
1080 bdevname(rdev->bdev, b);
1081 sb = page_address(rdev->sb_page);
1083 if (sb->md_magic != MD_SB_MAGIC) {
1084 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
1086 goto abort;
1089 if (sb->major_version != 0 ||
1090 sb->minor_version < 90 ||
1091 sb->minor_version > 91) {
1092 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
1093 sb->major_version, sb->minor_version,
1095 goto abort;
1098 if (sb->raid_disks <= 0)
1099 goto abort;
1101 if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1102 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1104 goto abort;
1107 rdev->preferred_minor = sb->md_minor;
1108 rdev->data_offset = 0;
1109 rdev->sb_size = MD_SB_BYTES;
1110 rdev->badblocks.shift = -1;
1112 if (sb->level == LEVEL_MULTIPATH)
1113 rdev->desc_nr = -1;
1114 else
1115 rdev->desc_nr = sb->this_disk.number;
1117 if (!refdev) {
1118 ret = 1;
1119 } else {
1120 __u64 ev1, ev2;
1121 mdp_super_t *refsb = page_address(refdev->sb_page);
1122 if (!uuid_equal(refsb, sb)) {
1123 printk(KERN_WARNING "md: %s has different UUID to %s\n",
1124 b, bdevname(refdev->bdev,b2));
1125 goto abort;
1127 if (!sb_equal(refsb, sb)) {
1128 printk(KERN_WARNING "md: %s has same UUID"
1129 " but different superblock to %s\n",
1130 b, bdevname(refdev->bdev, b2));
1131 goto abort;
1133 ev1 = md_event(sb);
1134 ev2 = md_event(refsb);
1135 if (ev1 > ev2)
1136 ret = 1;
1137 else
1138 ret = 0;
1140 rdev->sectors = rdev->sb_start;
1142 if (rdev->sectors < sb->size * 2 && sb->level > 1)
1143 /* "this cannot possibly happen" ... */
1144 ret = -EINVAL;
1146 abort:
1147 return ret;
1151 * validate_super for 0.90.0
1153 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1155 mdp_disk_t *desc;
1156 mdp_super_t *sb = page_address(rdev->sb_page);
1157 __u64 ev1 = md_event(sb);
1159 rdev->raid_disk = -1;
1160 clear_bit(Faulty, &rdev->flags);
1161 clear_bit(In_sync, &rdev->flags);
1162 clear_bit(WriteMostly, &rdev->flags);
1164 if (mddev->raid_disks == 0) {
1165 mddev->major_version = 0;
1166 mddev->minor_version = sb->minor_version;
1167 mddev->patch_version = sb->patch_version;
1168 mddev->external = 0;
1169 mddev->chunk_sectors = sb->chunk_size >> 9;
1170 mddev->ctime = sb->ctime;
1171 mddev->utime = sb->utime;
1172 mddev->level = sb->level;
1173 mddev->clevel[0] = 0;
1174 mddev->layout = sb->layout;
1175 mddev->raid_disks = sb->raid_disks;
1176 mddev->dev_sectors = sb->size * 2;
1177 mddev->events = ev1;
1178 mddev->bitmap_info.offset = 0;
1179 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1181 if (mddev->minor_version >= 91) {
1182 mddev->reshape_position = sb->reshape_position;
1183 mddev->delta_disks = sb->delta_disks;
1184 mddev->new_level = sb->new_level;
1185 mddev->new_layout = sb->new_layout;
1186 mddev->new_chunk_sectors = sb->new_chunk >> 9;
1187 } else {
1188 mddev->reshape_position = MaxSector;
1189 mddev->delta_disks = 0;
1190 mddev->new_level = mddev->level;
1191 mddev->new_layout = mddev->layout;
1192 mddev->new_chunk_sectors = mddev->chunk_sectors;
1195 if (sb->state & (1<<MD_SB_CLEAN))
1196 mddev->recovery_cp = MaxSector;
1197 else {
1198 if (sb->events_hi == sb->cp_events_hi &&
1199 sb->events_lo == sb->cp_events_lo) {
1200 mddev->recovery_cp = sb->recovery_cp;
1201 } else
1202 mddev->recovery_cp = 0;
1205 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1206 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1207 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1208 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1210 mddev->max_disks = MD_SB_DISKS;
1212 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1213 mddev->bitmap_info.file == NULL)
1214 mddev->bitmap_info.offset =
1215 mddev->bitmap_info.default_offset;
1217 } else if (mddev->pers == NULL) {
1218 /* Insist on good event counter while assembling, except
1219 * for spares (which don't need an event count) */
1220 ++ev1;
1221 if (sb->disks[rdev->desc_nr].state & (
1222 (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1223 if (ev1 < mddev->events)
1224 return -EINVAL;
1225 } else if (mddev->bitmap) {
1226 /* if adding to array with a bitmap, then we can accept an
1227 * older device ... but not too old.
1229 if (ev1 < mddev->bitmap->events_cleared)
1230 return 0;
1231 } else {
1232 if (ev1 < mddev->events)
1233 /* just a hot-add of a new device, leave raid_disk at -1 */
1234 return 0;
1237 if (mddev->level != LEVEL_MULTIPATH) {
1238 desc = sb->disks + rdev->desc_nr;
1240 if (desc->state & (1<<MD_DISK_FAULTY))
1241 set_bit(Faulty, &rdev->flags);
1242 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1243 desc->raid_disk < mddev->raid_disks */) {
1244 set_bit(In_sync, &rdev->flags);
1245 rdev->raid_disk = desc->raid_disk;
1246 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1247 /* active but not in sync implies recovery up to
1248 * reshape position. We don't know exactly where
1249 * that is, so set to zero for now */
1250 if (mddev->minor_version >= 91) {
1251 rdev->recovery_offset = 0;
1252 rdev->raid_disk = desc->raid_disk;
1255 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1256 set_bit(WriteMostly, &rdev->flags);
1257 } else /* MULTIPATH are always insync */
1258 set_bit(In_sync, &rdev->flags);
1259 return 0;
1263 * sync_super for 0.90.0
1265 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1267 mdp_super_t *sb;
1268 mdk_rdev_t *rdev2;
1269 int next_spare = mddev->raid_disks;
1272 /* make rdev->sb match mddev data..
1274 * 1/ zero out disks
1275 * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1276 * 3/ any empty disks < next_spare become removed
1278 * disks[0] gets initialised to REMOVED because
1279 * we cannot be sure from other fields if it has
1280 * been initialised or not.
1282 int i;
1283 int active=0, working=0,failed=0,spare=0,nr_disks=0;
1285 rdev->sb_size = MD_SB_BYTES;
1287 sb = page_address(rdev->sb_page);
1289 memset(sb, 0, sizeof(*sb));
1291 sb->md_magic = MD_SB_MAGIC;
1292 sb->major_version = mddev->major_version;
1293 sb->patch_version = mddev->patch_version;
1294 sb->gvalid_words = 0; /* ignored */
1295 memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1296 memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1297 memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1298 memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1300 sb->ctime = mddev->ctime;
1301 sb->level = mddev->level;
1302 sb->size = mddev->dev_sectors / 2;
1303 sb->raid_disks = mddev->raid_disks;
1304 sb->md_minor = mddev->md_minor;
1305 sb->not_persistent = 0;
1306 sb->utime = mddev->utime;
1307 sb->state = 0;
1308 sb->events_hi = (mddev->events>>32);
1309 sb->events_lo = (u32)mddev->events;
1311 if (mddev->reshape_position == MaxSector)
1312 sb->minor_version = 90;
1313 else {
1314 sb->minor_version = 91;
1315 sb->reshape_position = mddev->reshape_position;
1316 sb->new_level = mddev->new_level;
1317 sb->delta_disks = mddev->delta_disks;
1318 sb->new_layout = mddev->new_layout;
1319 sb->new_chunk = mddev->new_chunk_sectors << 9;
1321 mddev->minor_version = sb->minor_version;
1322 if (mddev->in_sync)
1324 sb->recovery_cp = mddev->recovery_cp;
1325 sb->cp_events_hi = (mddev->events>>32);
1326 sb->cp_events_lo = (u32)mddev->events;
1327 if (mddev->recovery_cp == MaxSector)
1328 sb->state = (1<< MD_SB_CLEAN);
1329 } else
1330 sb->recovery_cp = 0;
1332 sb->layout = mddev->layout;
1333 sb->chunk_size = mddev->chunk_sectors << 9;
1335 if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1336 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1338 sb->disks[0].state = (1<<MD_DISK_REMOVED);
1339 list_for_each_entry(rdev2, &mddev->disks, same_set) {
1340 mdp_disk_t *d;
1341 int desc_nr;
1342 int is_active = test_bit(In_sync, &rdev2->flags);
1344 if (rdev2->raid_disk >= 0 &&
1345 sb->minor_version >= 91)
1346 /* we have nowhere to store the recovery_offset,
1347 * but if it is not below the reshape_position,
1348 * we can piggy-back on that.
1350 is_active = 1;
1351 if (rdev2->raid_disk < 0 ||
1352 test_bit(Faulty, &rdev2->flags))
1353 is_active = 0;
1354 if (is_active)
1355 desc_nr = rdev2->raid_disk;
1356 else
1357 desc_nr = next_spare++;
1358 rdev2->desc_nr = desc_nr;
1359 d = &sb->disks[rdev2->desc_nr];
1360 nr_disks++;
1361 d->number = rdev2->desc_nr;
1362 d->major = MAJOR(rdev2->bdev->bd_dev);
1363 d->minor = MINOR(rdev2->bdev->bd_dev);
1364 if (is_active)
1365 d->raid_disk = rdev2->raid_disk;
1366 else
1367 d->raid_disk = rdev2->desc_nr; /* compatibility */
1368 if (test_bit(Faulty, &rdev2->flags))
1369 d->state = (1<<MD_DISK_FAULTY);
1370 else if (is_active) {
1371 d->state = (1<<MD_DISK_ACTIVE);
1372 if (test_bit(In_sync, &rdev2->flags))
1373 d->state |= (1<<MD_DISK_SYNC);
1374 active++;
1375 working++;
1376 } else {
1377 d->state = 0;
1378 spare++;
1379 working++;
1381 if (test_bit(WriteMostly, &rdev2->flags))
1382 d->state |= (1<<MD_DISK_WRITEMOSTLY);
1384 /* now set the "removed" and "faulty" bits on any missing devices */
1385 for (i=0 ; i < mddev->raid_disks ; i++) {
1386 mdp_disk_t *d = &sb->disks[i];
1387 if (d->state == 0 && d->number == 0) {
1388 d->number = i;
1389 d->raid_disk = i;
1390 d->state = (1<<MD_DISK_REMOVED);
1391 d->state |= (1<<MD_DISK_FAULTY);
1392 failed++;
1395 sb->nr_disks = nr_disks;
1396 sb->active_disks = active;
1397 sb->working_disks = working;
1398 sb->failed_disks = failed;
1399 sb->spare_disks = spare;
1401 sb->this_disk = sb->disks[rdev->desc_nr];
1402 sb->sb_csum = calc_sb_csum(sb);
1406 * rdev_size_change for 0.90.0
1408 static unsigned long long
1409 super_90_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1411 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1412 return 0; /* component must fit device */
1413 if (rdev->mddev->bitmap_info.offset)
1414 return 0; /* can't move bitmap */
1415 rdev->sb_start = calc_dev_sboffset(rdev);
1416 if (!num_sectors || num_sectors > rdev->sb_start)
1417 num_sectors = rdev->sb_start;
1418 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1419 rdev->sb_page);
1420 md_super_wait(rdev->mddev);
1421 return num_sectors;
1426 * version 1 superblock
1429 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1431 __le32 disk_csum;
1432 u32 csum;
1433 unsigned long long newcsum;
1434 int size = 256 + le32_to_cpu(sb->max_dev)*2;
1435 __le32 *isuper = (__le32*)sb;
1436 int i;
1438 disk_csum = sb->sb_csum;
1439 sb->sb_csum = 0;
1440 newcsum = 0;
1441 for (i=0; size>=4; size -= 4 )
1442 newcsum += le32_to_cpu(*isuper++);
1444 if (size == 2)
1445 newcsum += le16_to_cpu(*(__le16*) isuper);
1447 csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1448 sb->sb_csum = disk_csum;
1449 return cpu_to_le32(csum);
1452 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
1453 int acknowledged);
1454 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1456 struct mdp_superblock_1 *sb;
1457 int ret;
1458 sector_t sb_start;
1459 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1460 int bmask;
1463 * Calculate the position of the superblock in 512byte sectors.
1464 * It is always aligned to a 4K boundary and
1465 * depeding on minor_version, it can be:
1466 * 0: At least 8K, but less than 12K, from end of device
1467 * 1: At start of device
1468 * 2: 4K from start of device.
1470 switch(minor_version) {
1471 case 0:
1472 sb_start = i_size_read(rdev->bdev->bd_inode) >> 9;
1473 sb_start -= 8*2;
1474 sb_start &= ~(sector_t)(4*2-1);
1475 break;
1476 case 1:
1477 sb_start = 0;
1478 break;
1479 case 2:
1480 sb_start = 8;
1481 break;
1482 default:
1483 return -EINVAL;
1485 rdev->sb_start = sb_start;
1487 /* superblock is rarely larger than 1K, but it can be larger,
1488 * and it is safe to read 4k, so we do that
1490 ret = read_disk_sb(rdev, 4096);
1491 if (ret) return ret;
1494 sb = page_address(rdev->sb_page);
1496 if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1497 sb->major_version != cpu_to_le32(1) ||
1498 le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1499 le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1500 (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1501 return -EINVAL;
1503 if (calc_sb_1_csum(sb) != sb->sb_csum) {
1504 printk("md: invalid superblock checksum on %s\n",
1505 bdevname(rdev->bdev,b));
1506 return -EINVAL;
1508 if (le64_to_cpu(sb->data_size) < 10) {
1509 printk("md: data_size too small on %s\n",
1510 bdevname(rdev->bdev,b));
1511 return -EINVAL;
1514 rdev->preferred_minor = 0xffff;
1515 rdev->data_offset = le64_to_cpu(sb->data_offset);
1516 atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1518 rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1519 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1520 if (rdev->sb_size & bmask)
1521 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1523 if (minor_version
1524 && rdev->data_offset < sb_start + (rdev->sb_size/512))
1525 return -EINVAL;
1527 if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1528 rdev->desc_nr = -1;
1529 else
1530 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1532 if (!rdev->bb_page) {
1533 rdev->bb_page = alloc_page(GFP_KERNEL);
1534 if (!rdev->bb_page)
1535 return -ENOMEM;
1537 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BAD_BLOCKS) &&
1538 rdev->badblocks.count == 0) {
1539 /* need to load the bad block list.
1540 * Currently we limit it to one page.
1542 s32 offset;
1543 sector_t bb_sector;
1544 u64 *bbp;
1545 int i;
1546 int sectors = le16_to_cpu(sb->bblog_size);
1547 if (sectors > (PAGE_SIZE / 512))
1548 return -EINVAL;
1549 offset = le32_to_cpu(sb->bblog_offset);
1550 if (offset == 0)
1551 return -EINVAL;
1552 bb_sector = (long long)offset;
1553 if (!sync_page_io(rdev, bb_sector, sectors << 9,
1554 rdev->bb_page, READ, true))
1555 return -EIO;
1556 bbp = (u64 *)page_address(rdev->bb_page);
1557 rdev->badblocks.shift = sb->bblog_shift;
1558 for (i = 0 ; i < (sectors << (9-3)) ; i++, bbp++) {
1559 u64 bb = le64_to_cpu(*bbp);
1560 int count = bb & (0x3ff);
1561 u64 sector = bb >> 10;
1562 sector <<= sb->bblog_shift;
1563 count <<= sb->bblog_shift;
1564 if (bb + 1 == 0)
1565 break;
1566 if (md_set_badblocks(&rdev->badblocks,
1567 sector, count, 1) == 0)
1568 return -EINVAL;
1570 } else if (sb->bblog_offset == 0)
1571 rdev->badblocks.shift = -1;
1573 if (!refdev) {
1574 ret = 1;
1575 } else {
1576 __u64 ev1, ev2;
1577 struct mdp_superblock_1 *refsb = page_address(refdev->sb_page);
1579 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1580 sb->level != refsb->level ||
1581 sb->layout != refsb->layout ||
1582 sb->chunksize != refsb->chunksize) {
1583 printk(KERN_WARNING "md: %s has strangely different"
1584 " superblock to %s\n",
1585 bdevname(rdev->bdev,b),
1586 bdevname(refdev->bdev,b2));
1587 return -EINVAL;
1589 ev1 = le64_to_cpu(sb->events);
1590 ev2 = le64_to_cpu(refsb->events);
1592 if (ev1 > ev2)
1593 ret = 1;
1594 else
1595 ret = 0;
1597 if (minor_version)
1598 rdev->sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
1599 le64_to_cpu(sb->data_offset);
1600 else
1601 rdev->sectors = rdev->sb_start;
1602 if (rdev->sectors < le64_to_cpu(sb->data_size))
1603 return -EINVAL;
1604 rdev->sectors = le64_to_cpu(sb->data_size);
1605 if (le64_to_cpu(sb->size) > rdev->sectors)
1606 return -EINVAL;
1607 return ret;
1610 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1612 struct mdp_superblock_1 *sb = page_address(rdev->sb_page);
1613 __u64 ev1 = le64_to_cpu(sb->events);
1615 rdev->raid_disk = -1;
1616 clear_bit(Faulty, &rdev->flags);
1617 clear_bit(In_sync, &rdev->flags);
1618 clear_bit(WriteMostly, &rdev->flags);
1620 if (mddev->raid_disks == 0) {
1621 mddev->major_version = 1;
1622 mddev->patch_version = 0;
1623 mddev->external = 0;
1624 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1625 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1626 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1627 mddev->level = le32_to_cpu(sb->level);
1628 mddev->clevel[0] = 0;
1629 mddev->layout = le32_to_cpu(sb->layout);
1630 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1631 mddev->dev_sectors = le64_to_cpu(sb->size);
1632 mddev->events = ev1;
1633 mddev->bitmap_info.offset = 0;
1634 mddev->bitmap_info.default_offset = 1024 >> 9;
1636 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1637 memcpy(mddev->uuid, sb->set_uuid, 16);
1639 mddev->max_disks = (4096-256)/2;
1641 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1642 mddev->bitmap_info.file == NULL )
1643 mddev->bitmap_info.offset =
1644 (__s32)le32_to_cpu(sb->bitmap_offset);
1646 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1647 mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1648 mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1649 mddev->new_level = le32_to_cpu(sb->new_level);
1650 mddev->new_layout = le32_to_cpu(sb->new_layout);
1651 mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1652 } else {
1653 mddev->reshape_position = MaxSector;
1654 mddev->delta_disks = 0;
1655 mddev->new_level = mddev->level;
1656 mddev->new_layout = mddev->layout;
1657 mddev->new_chunk_sectors = mddev->chunk_sectors;
1660 } else if (mddev->pers == NULL) {
1661 /* Insist of good event counter while assembling, except for
1662 * spares (which don't need an event count) */
1663 ++ev1;
1664 if (rdev->desc_nr >= 0 &&
1665 rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1666 le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1667 if (ev1 < mddev->events)
1668 return -EINVAL;
1669 } else if (mddev->bitmap) {
1670 /* If adding to array with a bitmap, then we can accept an
1671 * older device, but not too old.
1673 if (ev1 < mddev->bitmap->events_cleared)
1674 return 0;
1675 } else {
1676 if (ev1 < mddev->events)
1677 /* just a hot-add of a new device, leave raid_disk at -1 */
1678 return 0;
1680 if (mddev->level != LEVEL_MULTIPATH) {
1681 int role;
1682 if (rdev->desc_nr < 0 ||
1683 rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1684 role = 0xffff;
1685 rdev->desc_nr = -1;
1686 } else
1687 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1688 switch(role) {
1689 case 0xffff: /* spare */
1690 break;
1691 case 0xfffe: /* faulty */
1692 set_bit(Faulty, &rdev->flags);
1693 break;
1694 default:
1695 if ((le32_to_cpu(sb->feature_map) &
1696 MD_FEATURE_RECOVERY_OFFSET))
1697 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1698 else
1699 set_bit(In_sync, &rdev->flags);
1700 rdev->raid_disk = role;
1701 break;
1703 if (sb->devflags & WriteMostly1)
1704 set_bit(WriteMostly, &rdev->flags);
1705 } else /* MULTIPATH are always insync */
1706 set_bit(In_sync, &rdev->flags);
1708 return 0;
1711 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1713 struct mdp_superblock_1 *sb;
1714 mdk_rdev_t *rdev2;
1715 int max_dev, i;
1716 /* make rdev->sb match mddev and rdev data. */
1718 sb = page_address(rdev->sb_page);
1720 sb->feature_map = 0;
1721 sb->pad0 = 0;
1722 sb->recovery_offset = cpu_to_le64(0);
1723 memset(sb->pad1, 0, sizeof(sb->pad1));
1724 memset(sb->pad3, 0, sizeof(sb->pad3));
1726 sb->utime = cpu_to_le64((__u64)mddev->utime);
1727 sb->events = cpu_to_le64(mddev->events);
1728 if (mddev->in_sync)
1729 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1730 else
1731 sb->resync_offset = cpu_to_le64(0);
1733 sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1735 sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1736 sb->size = cpu_to_le64(mddev->dev_sectors);
1737 sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1738 sb->level = cpu_to_le32(mddev->level);
1739 sb->layout = cpu_to_le32(mddev->layout);
1741 if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1742 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1743 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1746 if (rdev->raid_disk >= 0 &&
1747 !test_bit(In_sync, &rdev->flags)) {
1748 sb->feature_map |=
1749 cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1750 sb->recovery_offset =
1751 cpu_to_le64(rdev->recovery_offset);
1754 if (mddev->reshape_position != MaxSector) {
1755 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1756 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1757 sb->new_layout = cpu_to_le32(mddev->new_layout);
1758 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1759 sb->new_level = cpu_to_le32(mddev->new_level);
1760 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1763 if (rdev->badblocks.count == 0)
1764 /* Nothing to do for bad blocks*/ ;
1765 else if (sb->bblog_offset == 0)
1766 /* Cannot record bad blocks on this device */
1767 md_error(mddev, rdev);
1768 else {
1769 struct badblocks *bb = &rdev->badblocks;
1770 u64 *bbp = (u64 *)page_address(rdev->bb_page);
1771 u64 *p = bb->page;
1772 sb->feature_map |= cpu_to_le32(MD_FEATURE_BAD_BLOCKS);
1773 if (bb->changed) {
1774 unsigned seq;
1776 retry:
1777 seq = read_seqbegin(&bb->lock);
1779 memset(bbp, 0xff, PAGE_SIZE);
1781 for (i = 0 ; i < bb->count ; i++) {
1782 u64 internal_bb = *p++;
1783 u64 store_bb = ((BB_OFFSET(internal_bb) << 10)
1784 | BB_LEN(internal_bb));
1785 *bbp++ = cpu_to_le64(store_bb);
1787 if (read_seqretry(&bb->lock, seq))
1788 goto retry;
1790 bb->sector = (rdev->sb_start +
1791 (int)le32_to_cpu(sb->bblog_offset));
1792 bb->size = le16_to_cpu(sb->bblog_size);
1793 bb->changed = 0;
1797 max_dev = 0;
1798 list_for_each_entry(rdev2, &mddev->disks, same_set)
1799 if (rdev2->desc_nr+1 > max_dev)
1800 max_dev = rdev2->desc_nr+1;
1802 if (max_dev > le32_to_cpu(sb->max_dev)) {
1803 int bmask;
1804 sb->max_dev = cpu_to_le32(max_dev);
1805 rdev->sb_size = max_dev * 2 + 256;
1806 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1807 if (rdev->sb_size & bmask)
1808 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1809 } else
1810 max_dev = le32_to_cpu(sb->max_dev);
1812 for (i=0; i<max_dev;i++)
1813 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1815 list_for_each_entry(rdev2, &mddev->disks, same_set) {
1816 i = rdev2->desc_nr;
1817 if (test_bit(Faulty, &rdev2->flags))
1818 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1819 else if (test_bit(In_sync, &rdev2->flags))
1820 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1821 else if (rdev2->raid_disk >= 0)
1822 sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1823 else
1824 sb->dev_roles[i] = cpu_to_le16(0xffff);
1827 sb->sb_csum = calc_sb_1_csum(sb);
1830 static unsigned long long
1831 super_1_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1833 struct mdp_superblock_1 *sb;
1834 sector_t max_sectors;
1835 if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1836 return 0; /* component must fit device */
1837 if (rdev->sb_start < rdev->data_offset) {
1838 /* minor versions 1 and 2; superblock before data */
1839 max_sectors = i_size_read(rdev->bdev->bd_inode) >> 9;
1840 max_sectors -= rdev->data_offset;
1841 if (!num_sectors || num_sectors > max_sectors)
1842 num_sectors = max_sectors;
1843 } else if (rdev->mddev->bitmap_info.offset) {
1844 /* minor version 0 with bitmap we can't move */
1845 return 0;
1846 } else {
1847 /* minor version 0; superblock after data */
1848 sector_t sb_start;
1849 sb_start = (i_size_read(rdev->bdev->bd_inode) >> 9) - 8*2;
1850 sb_start &= ~(sector_t)(4*2 - 1);
1851 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1852 if (!num_sectors || num_sectors > max_sectors)
1853 num_sectors = max_sectors;
1854 rdev->sb_start = sb_start;
1856 sb = page_address(rdev->sb_page);
1857 sb->data_size = cpu_to_le64(num_sectors);
1858 sb->super_offset = rdev->sb_start;
1859 sb->sb_csum = calc_sb_1_csum(sb);
1860 md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1861 rdev->sb_page);
1862 md_super_wait(rdev->mddev);
1863 return num_sectors;
1866 static struct super_type super_types[] = {
1867 [0] = {
1868 .name = "0.90.0",
1869 .owner = THIS_MODULE,
1870 .load_super = super_90_load,
1871 .validate_super = super_90_validate,
1872 .sync_super = super_90_sync,
1873 .rdev_size_change = super_90_rdev_size_change,
1875 [1] = {
1876 .name = "md-1",
1877 .owner = THIS_MODULE,
1878 .load_super = super_1_load,
1879 .validate_super = super_1_validate,
1880 .sync_super = super_1_sync,
1881 .rdev_size_change = super_1_rdev_size_change,
1885 static void sync_super(mddev_t *mddev, mdk_rdev_t *rdev)
1887 if (mddev->sync_super) {
1888 mddev->sync_super(mddev, rdev);
1889 return;
1892 BUG_ON(mddev->major_version >= ARRAY_SIZE(super_types));
1894 super_types[mddev->major_version].sync_super(mddev, rdev);
1897 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1899 mdk_rdev_t *rdev, *rdev2;
1901 rcu_read_lock();
1902 rdev_for_each_rcu(rdev, mddev1)
1903 rdev_for_each_rcu(rdev2, mddev2)
1904 if (rdev->bdev->bd_contains ==
1905 rdev2->bdev->bd_contains) {
1906 rcu_read_unlock();
1907 return 1;
1909 rcu_read_unlock();
1910 return 0;
1913 static LIST_HEAD(pending_raid_disks);
1916 * Try to register data integrity profile for an mddev
1918 * This is called when an array is started and after a disk has been kicked
1919 * from the array. It only succeeds if all working and active component devices
1920 * are integrity capable with matching profiles.
1922 int md_integrity_register(mddev_t *mddev)
1924 mdk_rdev_t *rdev, *reference = NULL;
1926 if (list_empty(&mddev->disks))
1927 return 0; /* nothing to do */
1928 if (!mddev->gendisk || blk_get_integrity(mddev->gendisk))
1929 return 0; /* shouldn't register, or already is */
1930 list_for_each_entry(rdev, &mddev->disks, same_set) {
1931 /* skip spares and non-functional disks */
1932 if (test_bit(Faulty, &rdev->flags))
1933 continue;
1934 if (rdev->raid_disk < 0)
1935 continue;
1936 if (!reference) {
1937 /* Use the first rdev as the reference */
1938 reference = rdev;
1939 continue;
1941 /* does this rdev's profile match the reference profile? */
1942 if (blk_integrity_compare(reference->bdev->bd_disk,
1943 rdev->bdev->bd_disk) < 0)
1944 return -EINVAL;
1946 if (!reference || !bdev_get_integrity(reference->bdev))
1947 return 0;
1949 * All component devices are integrity capable and have matching
1950 * profiles, register the common profile for the md device.
1952 if (blk_integrity_register(mddev->gendisk,
1953 bdev_get_integrity(reference->bdev)) != 0) {
1954 printk(KERN_ERR "md: failed to register integrity for %s\n",
1955 mdname(mddev));
1956 return -EINVAL;
1958 printk(KERN_NOTICE "md: data integrity enabled on %s\n", mdname(mddev));
1959 if (bioset_integrity_create(mddev->bio_set, BIO_POOL_SIZE)) {
1960 printk(KERN_ERR "md: failed to create integrity pool for %s\n",
1961 mdname(mddev));
1962 return -EINVAL;
1964 return 0;
1966 EXPORT_SYMBOL(md_integrity_register);
1968 /* Disable data integrity if non-capable/non-matching disk is being added */
1969 void md_integrity_add_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
1971 struct blk_integrity *bi_rdev = bdev_get_integrity(rdev->bdev);
1972 struct blk_integrity *bi_mddev = blk_get_integrity(mddev->gendisk);
1974 if (!bi_mddev) /* nothing to do */
1975 return;
1976 if (rdev->raid_disk < 0) /* skip spares */
1977 return;
1978 if (bi_rdev && blk_integrity_compare(mddev->gendisk,
1979 rdev->bdev->bd_disk) >= 0)
1980 return;
1981 printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
1982 blk_integrity_unregister(mddev->gendisk);
1984 EXPORT_SYMBOL(md_integrity_add_rdev);
1986 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1988 char b[BDEVNAME_SIZE];
1989 struct kobject *ko;
1990 char *s;
1991 int err;
1993 if (rdev->mddev) {
1994 MD_BUG();
1995 return -EINVAL;
1998 /* prevent duplicates */
1999 if (find_rdev(mddev, rdev->bdev->bd_dev))
2000 return -EEXIST;
2002 /* make sure rdev->sectors exceeds mddev->dev_sectors */
2003 if (rdev->sectors && (mddev->dev_sectors == 0 ||
2004 rdev->sectors < mddev->dev_sectors)) {
2005 if (mddev->pers) {
2006 /* Cannot change size, so fail
2007 * If mddev->level <= 0, then we don't care
2008 * about aligning sizes (e.g. linear)
2010 if (mddev->level > 0)
2011 return -ENOSPC;
2012 } else
2013 mddev->dev_sectors = rdev->sectors;
2016 /* Verify rdev->desc_nr is unique.
2017 * If it is -1, assign a free number, else
2018 * check number is not in use
2020 if (rdev->desc_nr < 0) {
2021 int choice = 0;
2022 if (mddev->pers) choice = mddev->raid_disks;
2023 while (find_rdev_nr(mddev, choice))
2024 choice++;
2025 rdev->desc_nr = choice;
2026 } else {
2027 if (find_rdev_nr(mddev, rdev->desc_nr))
2028 return -EBUSY;
2030 if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
2031 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
2032 mdname(mddev), mddev->max_disks);
2033 return -EBUSY;
2035 bdevname(rdev->bdev,b);
2036 while ( (s=strchr(b, '/')) != NULL)
2037 *s = '!';
2039 rdev->mddev = mddev;
2040 printk(KERN_INFO "md: bind<%s>\n", b);
2042 if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
2043 goto fail;
2045 ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
2046 if (sysfs_create_link(&rdev->kobj, ko, "block"))
2047 /* failure here is OK */;
2048 rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
2050 list_add_rcu(&rdev->same_set, &mddev->disks);
2051 bd_link_disk_holder(rdev->bdev, mddev->gendisk);
2053 /* May as well allow recovery to be retried once */
2054 mddev->recovery_disabled++;
2056 return 0;
2058 fail:
2059 printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
2060 b, mdname(mddev));
2061 return err;
2064 static void md_delayed_delete(struct work_struct *ws)
2066 mdk_rdev_t *rdev = container_of(ws, mdk_rdev_t, del_work);
2067 kobject_del(&rdev->kobj);
2068 kobject_put(&rdev->kobj);
2071 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
2073 char b[BDEVNAME_SIZE];
2074 if (!rdev->mddev) {
2075 MD_BUG();
2076 return;
2078 bd_unlink_disk_holder(rdev->bdev, rdev->mddev->gendisk);
2079 list_del_rcu(&rdev->same_set);
2080 printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
2081 rdev->mddev = NULL;
2082 sysfs_remove_link(&rdev->kobj, "block");
2083 sysfs_put(rdev->sysfs_state);
2084 rdev->sysfs_state = NULL;
2085 kfree(rdev->badblocks.page);
2086 rdev->badblocks.count = 0;
2087 rdev->badblocks.page = NULL;
2088 /* We need to delay this, otherwise we can deadlock when
2089 * writing to 'remove' to "dev/state". We also need
2090 * to delay it due to rcu usage.
2092 synchronize_rcu();
2093 INIT_WORK(&rdev->del_work, md_delayed_delete);
2094 kobject_get(&rdev->kobj);
2095 queue_work(md_misc_wq, &rdev->del_work);
2099 * prevent the device from being mounted, repartitioned or
2100 * otherwise reused by a RAID array (or any other kernel
2101 * subsystem), by bd_claiming the device.
2103 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev, int shared)
2105 int err = 0;
2106 struct block_device *bdev;
2107 char b[BDEVNAME_SIZE];
2109 bdev = blkdev_get_by_dev(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
2110 shared ? (mdk_rdev_t *)lock_rdev : rdev);
2111 if (IS_ERR(bdev)) {
2112 printk(KERN_ERR "md: could not open %s.\n",
2113 __bdevname(dev, b));
2114 return PTR_ERR(bdev);
2116 rdev->bdev = bdev;
2117 return err;
2120 static void unlock_rdev(mdk_rdev_t *rdev)
2122 struct block_device *bdev = rdev->bdev;
2123 rdev->bdev = NULL;
2124 if (!bdev)
2125 MD_BUG();
2126 blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
2129 void md_autodetect_dev(dev_t dev);
2131 static void export_rdev(mdk_rdev_t * rdev)
2133 char b[BDEVNAME_SIZE];
2134 printk(KERN_INFO "md: export_rdev(%s)\n",
2135 bdevname(rdev->bdev,b));
2136 if (rdev->mddev)
2137 MD_BUG();
2138 free_disk_sb(rdev);
2139 #ifndef MODULE
2140 if (test_bit(AutoDetected, &rdev->flags))
2141 md_autodetect_dev(rdev->bdev->bd_dev);
2142 #endif
2143 unlock_rdev(rdev);
2144 kobject_put(&rdev->kobj);
2147 static void kick_rdev_from_array(mdk_rdev_t * rdev)
2149 unbind_rdev_from_array(rdev);
2150 export_rdev(rdev);
2153 static void export_array(mddev_t *mddev)
2155 mdk_rdev_t *rdev, *tmp;
2157 rdev_for_each(rdev, tmp, mddev) {
2158 if (!rdev->mddev) {
2159 MD_BUG();
2160 continue;
2162 kick_rdev_from_array(rdev);
2164 if (!list_empty(&mddev->disks))
2165 MD_BUG();
2166 mddev->raid_disks = 0;
2167 mddev->major_version = 0;
2170 static void print_desc(mdp_disk_t *desc)
2172 printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
2173 desc->major,desc->minor,desc->raid_disk,desc->state);
2176 static void print_sb_90(mdp_super_t *sb)
2178 int i;
2180 printk(KERN_INFO
2181 "md: SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
2182 sb->major_version, sb->minor_version, sb->patch_version,
2183 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
2184 sb->ctime);
2185 printk(KERN_INFO "md: L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
2186 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
2187 sb->md_minor, sb->layout, sb->chunk_size);
2188 printk(KERN_INFO "md: UT:%08x ST:%d AD:%d WD:%d"
2189 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
2190 sb->utime, sb->state, sb->active_disks, sb->working_disks,
2191 sb->failed_disks, sb->spare_disks,
2192 sb->sb_csum, (unsigned long)sb->events_lo);
2194 printk(KERN_INFO);
2195 for (i = 0; i < MD_SB_DISKS; i++) {
2196 mdp_disk_t *desc;
2198 desc = sb->disks + i;
2199 if (desc->number || desc->major || desc->minor ||
2200 desc->raid_disk || (desc->state && (desc->state != 4))) {
2201 printk(" D %2d: ", i);
2202 print_desc(desc);
2205 printk(KERN_INFO "md: THIS: ");
2206 print_desc(&sb->this_disk);
2209 static void print_sb_1(struct mdp_superblock_1 *sb)
2211 __u8 *uuid;
2213 uuid = sb->set_uuid;
2214 printk(KERN_INFO
2215 "md: SB: (V:%u) (F:0x%08x) Array-ID:<%pU>\n"
2216 "md: Name: \"%s\" CT:%llu\n",
2217 le32_to_cpu(sb->major_version),
2218 le32_to_cpu(sb->feature_map),
2219 uuid,
2220 sb->set_name,
2221 (unsigned long long)le64_to_cpu(sb->ctime)
2222 & MD_SUPERBLOCK_1_TIME_SEC_MASK);
2224 uuid = sb->device_uuid;
2225 printk(KERN_INFO
2226 "md: L%u SZ%llu RD:%u LO:%u CS:%u DO:%llu DS:%llu SO:%llu"
2227 " RO:%llu\n"
2228 "md: Dev:%08x UUID: %pU\n"
2229 "md: (F:0x%08x) UT:%llu Events:%llu ResyncOffset:%llu CSUM:0x%08x\n"
2230 "md: (MaxDev:%u) \n",
2231 le32_to_cpu(sb->level),
2232 (unsigned long long)le64_to_cpu(sb->size),
2233 le32_to_cpu(sb->raid_disks),
2234 le32_to_cpu(sb->layout),
2235 le32_to_cpu(sb->chunksize),
2236 (unsigned long long)le64_to_cpu(sb->data_offset),
2237 (unsigned long long)le64_to_cpu(sb->data_size),
2238 (unsigned long long)le64_to_cpu(sb->super_offset),
2239 (unsigned long long)le64_to_cpu(sb->recovery_offset),
2240 le32_to_cpu(sb->dev_number),
2241 uuid,
2242 sb->devflags,
2243 (unsigned long long)le64_to_cpu(sb->utime) & MD_SUPERBLOCK_1_TIME_SEC_MASK,
2244 (unsigned long long)le64_to_cpu(sb->events),
2245 (unsigned long long)le64_to_cpu(sb->resync_offset),
2246 le32_to_cpu(sb->sb_csum),
2247 le32_to_cpu(sb->max_dev)
2251 static void print_rdev(mdk_rdev_t *rdev, int major_version)
2253 char b[BDEVNAME_SIZE];
2254 printk(KERN_INFO "md: rdev %s, Sect:%08llu F:%d S:%d DN:%u\n",
2255 bdevname(rdev->bdev, b), (unsigned long long)rdev->sectors,
2256 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
2257 rdev->desc_nr);
2258 if (rdev->sb_loaded) {
2259 printk(KERN_INFO "md: rdev superblock (MJ:%d):\n", major_version);
2260 switch (major_version) {
2261 case 0:
2262 print_sb_90(page_address(rdev->sb_page));
2263 break;
2264 case 1:
2265 print_sb_1(page_address(rdev->sb_page));
2266 break;
2268 } else
2269 printk(KERN_INFO "md: no rdev superblock!\n");
2272 static void md_print_devices(void)
2274 struct list_head *tmp;
2275 mdk_rdev_t *rdev;
2276 mddev_t *mddev;
2277 char b[BDEVNAME_SIZE];
2279 printk("\n");
2280 printk("md: **********************************\n");
2281 printk("md: * <COMPLETE RAID STATE PRINTOUT> *\n");
2282 printk("md: **********************************\n");
2283 for_each_mddev(mddev, tmp) {
2285 if (mddev->bitmap)
2286 bitmap_print_sb(mddev->bitmap);
2287 else
2288 printk("%s: ", mdname(mddev));
2289 list_for_each_entry(rdev, &mddev->disks, same_set)
2290 printk("<%s>", bdevname(rdev->bdev,b));
2291 printk("\n");
2293 list_for_each_entry(rdev, &mddev->disks, same_set)
2294 print_rdev(rdev, mddev->major_version);
2296 printk("md: **********************************\n");
2297 printk("\n");
2301 static void sync_sbs(mddev_t * mddev, int nospares)
2303 /* Update each superblock (in-memory image), but
2304 * if we are allowed to, skip spares which already
2305 * have the right event counter, or have one earlier
2306 * (which would mean they aren't being marked as dirty
2307 * with the rest of the array)
2309 mdk_rdev_t *rdev;
2310 list_for_each_entry(rdev, &mddev->disks, same_set) {
2311 if (rdev->sb_events == mddev->events ||
2312 (nospares &&
2313 rdev->raid_disk < 0 &&
2314 rdev->sb_events+1 == mddev->events)) {
2315 /* Don't update this superblock */
2316 rdev->sb_loaded = 2;
2317 } else {
2318 sync_super(mddev, rdev);
2319 rdev->sb_loaded = 1;
2324 static void md_update_sb(mddev_t * mddev, int force_change)
2326 mdk_rdev_t *rdev;
2327 int sync_req;
2328 int nospares = 0;
2329 int any_badblocks_changed = 0;
2331 repeat:
2332 /* First make sure individual recovery_offsets are correct */
2333 list_for_each_entry(rdev, &mddev->disks, same_set) {
2334 if (rdev->raid_disk >= 0 &&
2335 mddev->delta_disks >= 0 &&
2336 !test_bit(In_sync, &rdev->flags) &&
2337 mddev->curr_resync_completed > rdev->recovery_offset)
2338 rdev->recovery_offset = mddev->curr_resync_completed;
2341 if (!mddev->persistent) {
2342 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2343 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2344 if (!mddev->external)
2345 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2346 wake_up(&mddev->sb_wait);
2347 return;
2350 spin_lock_irq(&mddev->write_lock);
2352 mddev->utime = get_seconds();
2354 if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2355 force_change = 1;
2356 if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2357 /* just a clean<-> dirty transition, possibly leave spares alone,
2358 * though if events isn't the right even/odd, we will have to do
2359 * spares after all
2361 nospares = 1;
2362 if (force_change)
2363 nospares = 0;
2364 if (mddev->degraded)
2365 /* If the array is degraded, then skipping spares is both
2366 * dangerous and fairly pointless.
2367 * Dangerous because a device that was removed from the array
2368 * might have a event_count that still looks up-to-date,
2369 * so it can be re-added without a resync.
2370 * Pointless because if there are any spares to skip,
2371 * then a recovery will happen and soon that array won't
2372 * be degraded any more and the spare can go back to sleep then.
2374 nospares = 0;
2376 sync_req = mddev->in_sync;
2378 /* If this is just a dirty<->clean transition, and the array is clean
2379 * and 'events' is odd, we can roll back to the previous clean state */
2380 if (nospares
2381 && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2382 && mddev->can_decrease_events
2383 && mddev->events != 1) {
2384 mddev->events--;
2385 mddev->can_decrease_events = 0;
2386 } else {
2387 /* otherwise we have to go forward and ... */
2388 mddev->events ++;
2389 mddev->can_decrease_events = nospares;
2392 if (!mddev->events) {
2394 * oops, this 64-bit counter should never wrap.
2395 * Either we are in around ~1 trillion A.C., assuming
2396 * 1 reboot per second, or we have a bug:
2398 MD_BUG();
2399 mddev->events --;
2402 list_for_each_entry(rdev, &mddev->disks, same_set)
2403 if (rdev->badblocks.changed)
2404 any_badblocks_changed++;
2406 sync_sbs(mddev, nospares);
2407 spin_unlock_irq(&mddev->write_lock);
2409 dprintk(KERN_INFO
2410 "md: updating %s RAID superblock on device (in sync %d)\n",
2411 mdname(mddev),mddev->in_sync);
2413 bitmap_update_sb(mddev->bitmap);
2414 list_for_each_entry(rdev, &mddev->disks, same_set) {
2415 char b[BDEVNAME_SIZE];
2416 dprintk(KERN_INFO "md: ");
2417 if (rdev->sb_loaded != 1)
2418 continue; /* no noise on spare devices */
2419 if (test_bit(Faulty, &rdev->flags))
2420 dprintk("(skipping faulty ");
2422 dprintk("%s ", bdevname(rdev->bdev,b));
2423 if (!test_bit(Faulty, &rdev->flags)) {
2424 md_super_write(mddev,rdev,
2425 rdev->sb_start, rdev->sb_size,
2426 rdev->sb_page);
2427 dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
2428 bdevname(rdev->bdev,b),
2429 (unsigned long long)rdev->sb_start);
2430 rdev->sb_events = mddev->events;
2431 if (rdev->badblocks.size) {
2432 md_super_write(mddev, rdev,
2433 rdev->badblocks.sector,
2434 rdev->badblocks.size << 9,
2435 rdev->bb_page);
2436 rdev->badblocks.size = 0;
2439 } else
2440 dprintk(")\n");
2441 if (mddev->level == LEVEL_MULTIPATH)
2442 /* only need to write one superblock... */
2443 break;
2445 md_super_wait(mddev);
2446 /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2448 spin_lock_irq(&mddev->write_lock);
2449 if (mddev->in_sync != sync_req ||
2450 test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2451 /* have to write it out again */
2452 spin_unlock_irq(&mddev->write_lock);
2453 goto repeat;
2455 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2456 spin_unlock_irq(&mddev->write_lock);
2457 wake_up(&mddev->sb_wait);
2458 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2459 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2461 if (any_badblocks_changed)
2462 list_for_each_entry(rdev, &mddev->disks, same_set)
2463 md_ack_all_badblocks(&rdev->badblocks);
2466 /* words written to sysfs files may, or may not, be \n terminated.
2467 * We want to accept with case. For this we use cmd_match.
2469 static int cmd_match(const char *cmd, const char *str)
2471 /* See if cmd, written into a sysfs file, matches
2472 * str. They must either be the same, or cmd can
2473 * have a trailing newline
2475 while (*cmd && *str && *cmd == *str) {
2476 cmd++;
2477 str++;
2479 if (*cmd == '\n')
2480 cmd++;
2481 if (*str || *cmd)
2482 return 0;
2483 return 1;
2486 struct rdev_sysfs_entry {
2487 struct attribute attr;
2488 ssize_t (*show)(mdk_rdev_t *, char *);
2489 ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
2492 static ssize_t
2493 state_show(mdk_rdev_t *rdev, char *page)
2495 char *sep = "";
2496 size_t len = 0;
2498 if (test_bit(Faulty, &rdev->flags)) {
2499 len+= sprintf(page+len, "%sfaulty",sep);
2500 sep = ",";
2502 if (test_bit(In_sync, &rdev->flags)) {
2503 len += sprintf(page+len, "%sin_sync",sep);
2504 sep = ",";
2506 if (test_bit(WriteMostly, &rdev->flags)) {
2507 len += sprintf(page+len, "%swrite_mostly",sep);
2508 sep = ",";
2510 if (test_bit(Blocked, &rdev->flags)) {
2511 len += sprintf(page+len, "%sblocked", sep);
2512 sep = ",";
2514 if (!test_bit(Faulty, &rdev->flags) &&
2515 !test_bit(In_sync, &rdev->flags)) {
2516 len += sprintf(page+len, "%sspare", sep);
2517 sep = ",";
2519 return len+sprintf(page+len, "\n");
2522 static ssize_t
2523 state_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2525 /* can write
2526 * faulty - simulates and error
2527 * remove - disconnects the device
2528 * writemostly - sets write_mostly
2529 * -writemostly - clears write_mostly
2530 * blocked - sets the Blocked flag
2531 * -blocked - clears the Blocked flag
2532 * insync - sets Insync providing device isn't active
2534 int err = -EINVAL;
2535 if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2536 md_error(rdev->mddev, rdev);
2537 err = 0;
2538 } else if (cmd_match(buf, "remove")) {
2539 if (rdev->raid_disk >= 0)
2540 err = -EBUSY;
2541 else {
2542 mddev_t *mddev = rdev->mddev;
2543 kick_rdev_from_array(rdev);
2544 if (mddev->pers)
2545 md_update_sb(mddev, 1);
2546 md_new_event(mddev);
2547 err = 0;
2549 } else if (cmd_match(buf, "writemostly")) {
2550 set_bit(WriteMostly, &rdev->flags);
2551 err = 0;
2552 } else if (cmd_match(buf, "-writemostly")) {
2553 clear_bit(WriteMostly, &rdev->flags);
2554 err = 0;
2555 } else if (cmd_match(buf, "blocked")) {
2556 set_bit(Blocked, &rdev->flags);
2557 err = 0;
2558 } else if (cmd_match(buf, "-blocked")) {
2559 clear_bit(Blocked, &rdev->flags);
2560 wake_up(&rdev->blocked_wait);
2561 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2562 md_wakeup_thread(rdev->mddev->thread);
2564 err = 0;
2565 } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2566 set_bit(In_sync, &rdev->flags);
2567 err = 0;
2569 if (!err)
2570 sysfs_notify_dirent_safe(rdev->sysfs_state);
2571 return err ? err : len;
2573 static struct rdev_sysfs_entry rdev_state =
2574 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
2576 static ssize_t
2577 errors_show(mdk_rdev_t *rdev, char *page)
2579 return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2582 static ssize_t
2583 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2585 char *e;
2586 unsigned long n = simple_strtoul(buf, &e, 10);
2587 if (*buf && (*e == 0 || *e == '\n')) {
2588 atomic_set(&rdev->corrected_errors, n);
2589 return len;
2591 return -EINVAL;
2593 static struct rdev_sysfs_entry rdev_errors =
2594 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2596 static ssize_t
2597 slot_show(mdk_rdev_t *rdev, char *page)
2599 if (rdev->raid_disk < 0)
2600 return sprintf(page, "none\n");
2601 else
2602 return sprintf(page, "%d\n", rdev->raid_disk);
2605 static ssize_t
2606 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2608 char *e;
2609 int err;
2610 int slot = simple_strtoul(buf, &e, 10);
2611 if (strncmp(buf, "none", 4)==0)
2612 slot = -1;
2613 else if (e==buf || (*e && *e!= '\n'))
2614 return -EINVAL;
2615 if (rdev->mddev->pers && slot == -1) {
2616 /* Setting 'slot' on an active array requires also
2617 * updating the 'rd%d' link, and communicating
2618 * with the personality with ->hot_*_disk.
2619 * For now we only support removing
2620 * failed/spare devices. This normally happens automatically,
2621 * but not when the metadata is externally managed.
2623 if (rdev->raid_disk == -1)
2624 return -EEXIST;
2625 /* personality does all needed checks */
2626 if (rdev->mddev->pers->hot_remove_disk == NULL)
2627 return -EINVAL;
2628 err = rdev->mddev->pers->
2629 hot_remove_disk(rdev->mddev, rdev->raid_disk);
2630 if (err)
2631 return err;
2632 sysfs_unlink_rdev(rdev->mddev, rdev);
2633 rdev->raid_disk = -1;
2634 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2635 md_wakeup_thread(rdev->mddev->thread);
2636 } else if (rdev->mddev->pers) {
2637 mdk_rdev_t *rdev2;
2638 /* Activating a spare .. or possibly reactivating
2639 * if we ever get bitmaps working here.
2642 if (rdev->raid_disk != -1)
2643 return -EBUSY;
2645 if (test_bit(MD_RECOVERY_RUNNING, &rdev->mddev->recovery))
2646 return -EBUSY;
2648 if (rdev->mddev->pers->hot_add_disk == NULL)
2649 return -EINVAL;
2651 list_for_each_entry(rdev2, &rdev->mddev->disks, same_set)
2652 if (rdev2->raid_disk == slot)
2653 return -EEXIST;
2655 if (slot >= rdev->mddev->raid_disks &&
2656 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2657 return -ENOSPC;
2659 rdev->raid_disk = slot;
2660 if (test_bit(In_sync, &rdev->flags))
2661 rdev->saved_raid_disk = slot;
2662 else
2663 rdev->saved_raid_disk = -1;
2664 err = rdev->mddev->pers->
2665 hot_add_disk(rdev->mddev, rdev);
2666 if (err) {
2667 rdev->raid_disk = -1;
2668 return err;
2669 } else
2670 sysfs_notify_dirent_safe(rdev->sysfs_state);
2671 if (sysfs_link_rdev(rdev->mddev, rdev))
2672 /* failure here is OK */;
2673 /* don't wakeup anyone, leave that to userspace. */
2674 } else {
2675 if (slot >= rdev->mddev->raid_disks &&
2676 slot >= rdev->mddev->raid_disks + rdev->mddev->delta_disks)
2677 return -ENOSPC;
2678 rdev->raid_disk = slot;
2679 /* assume it is working */
2680 clear_bit(Faulty, &rdev->flags);
2681 clear_bit(WriteMostly, &rdev->flags);
2682 set_bit(In_sync, &rdev->flags);
2683 sysfs_notify_dirent_safe(rdev->sysfs_state);
2685 return len;
2689 static struct rdev_sysfs_entry rdev_slot =
2690 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2692 static ssize_t
2693 offset_show(mdk_rdev_t *rdev, char *page)
2695 return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2698 static ssize_t
2699 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2701 char *e;
2702 unsigned long long offset = simple_strtoull(buf, &e, 10);
2703 if (e==buf || (*e && *e != '\n'))
2704 return -EINVAL;
2705 if (rdev->mddev->pers && rdev->raid_disk >= 0)
2706 return -EBUSY;
2707 if (rdev->sectors && rdev->mddev->external)
2708 /* Must set offset before size, so overlap checks
2709 * can be sane */
2710 return -EBUSY;
2711 rdev->data_offset = offset;
2712 return len;
2715 static struct rdev_sysfs_entry rdev_offset =
2716 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2718 static ssize_t
2719 rdev_size_show(mdk_rdev_t *rdev, char *page)
2721 return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2724 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2726 /* check if two start/length pairs overlap */
2727 if (s1+l1 <= s2)
2728 return 0;
2729 if (s2+l2 <= s1)
2730 return 0;
2731 return 1;
2734 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2736 unsigned long long blocks;
2737 sector_t new;
2739 if (strict_strtoull(buf, 10, &blocks) < 0)
2740 return -EINVAL;
2742 if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2743 return -EINVAL; /* sector conversion overflow */
2745 new = blocks * 2;
2746 if (new != blocks * 2)
2747 return -EINVAL; /* unsigned long long to sector_t overflow */
2749 *sectors = new;
2750 return 0;
2753 static ssize_t
2754 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2756 mddev_t *my_mddev = rdev->mddev;
2757 sector_t oldsectors = rdev->sectors;
2758 sector_t sectors;
2760 if (strict_blocks_to_sectors(buf, &sectors) < 0)
2761 return -EINVAL;
2762 if (my_mddev->pers && rdev->raid_disk >= 0) {
2763 if (my_mddev->persistent) {
2764 sectors = super_types[my_mddev->major_version].
2765 rdev_size_change(rdev, sectors);
2766 if (!sectors)
2767 return -EBUSY;
2768 } else if (!sectors)
2769 sectors = (i_size_read(rdev->bdev->bd_inode) >> 9) -
2770 rdev->data_offset;
2772 if (sectors < my_mddev->dev_sectors)
2773 return -EINVAL; /* component must fit device */
2775 rdev->sectors = sectors;
2776 if (sectors > oldsectors && my_mddev->external) {
2777 /* need to check that all other rdevs with the same ->bdev
2778 * do not overlap. We need to unlock the mddev to avoid
2779 * a deadlock. We have already changed rdev->sectors, and if
2780 * we have to change it back, we will have the lock again.
2782 mddev_t *mddev;
2783 int overlap = 0;
2784 struct list_head *tmp;
2786 mddev_unlock(my_mddev);
2787 for_each_mddev(mddev, tmp) {
2788 mdk_rdev_t *rdev2;
2790 mddev_lock(mddev);
2791 list_for_each_entry(rdev2, &mddev->disks, same_set)
2792 if (rdev->bdev == rdev2->bdev &&
2793 rdev != rdev2 &&
2794 overlaps(rdev->data_offset, rdev->sectors,
2795 rdev2->data_offset,
2796 rdev2->sectors)) {
2797 overlap = 1;
2798 break;
2800 mddev_unlock(mddev);
2801 if (overlap) {
2802 mddev_put(mddev);
2803 break;
2806 mddev_lock(my_mddev);
2807 if (overlap) {
2808 /* Someone else could have slipped in a size
2809 * change here, but doing so is just silly.
2810 * We put oldsectors back because we *know* it is
2811 * safe, and trust userspace not to race with
2812 * itself
2814 rdev->sectors = oldsectors;
2815 return -EBUSY;
2818 return len;
2821 static struct rdev_sysfs_entry rdev_size =
2822 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2825 static ssize_t recovery_start_show(mdk_rdev_t *rdev, char *page)
2827 unsigned long long recovery_start = rdev->recovery_offset;
2829 if (test_bit(In_sync, &rdev->flags) ||
2830 recovery_start == MaxSector)
2831 return sprintf(page, "none\n");
2833 return sprintf(page, "%llu\n", recovery_start);
2836 static ssize_t recovery_start_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2838 unsigned long long recovery_start;
2840 if (cmd_match(buf, "none"))
2841 recovery_start = MaxSector;
2842 else if (strict_strtoull(buf, 10, &recovery_start))
2843 return -EINVAL;
2845 if (rdev->mddev->pers &&
2846 rdev->raid_disk >= 0)
2847 return -EBUSY;
2849 rdev->recovery_offset = recovery_start;
2850 if (recovery_start == MaxSector)
2851 set_bit(In_sync, &rdev->flags);
2852 else
2853 clear_bit(In_sync, &rdev->flags);
2854 return len;
2857 static struct rdev_sysfs_entry rdev_recovery_start =
2858 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
2861 static ssize_t
2862 badblocks_show(struct badblocks *bb, char *page, int unack);
2863 static ssize_t
2864 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack);
2866 static ssize_t bb_show(mdk_rdev_t *rdev, char *page)
2868 return badblocks_show(&rdev->badblocks, page, 0);
2870 static ssize_t bb_store(mdk_rdev_t *rdev, const char *page, size_t len)
2872 return badblocks_store(&rdev->badblocks, page, len, 0);
2874 static struct rdev_sysfs_entry rdev_bad_blocks =
2875 __ATTR(bad_blocks, S_IRUGO|S_IWUSR, bb_show, bb_store);
2878 static ssize_t ubb_show(mdk_rdev_t *rdev, char *page)
2880 return badblocks_show(&rdev->badblocks, page, 1);
2882 static ssize_t ubb_store(mdk_rdev_t *rdev, const char *page, size_t len)
2884 return badblocks_store(&rdev->badblocks, page, len, 1);
2886 static struct rdev_sysfs_entry rdev_unack_bad_blocks =
2887 __ATTR(unacknowledged_bad_blocks, S_IRUGO|S_IWUSR, ubb_show, ubb_store);
2889 static struct attribute *rdev_default_attrs[] = {
2890 &rdev_state.attr,
2891 &rdev_errors.attr,
2892 &rdev_slot.attr,
2893 &rdev_offset.attr,
2894 &rdev_size.attr,
2895 &rdev_recovery_start.attr,
2896 &rdev_bad_blocks.attr,
2897 &rdev_unack_bad_blocks.attr,
2898 NULL,
2900 static ssize_t
2901 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2903 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2904 mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2905 mddev_t *mddev = rdev->mddev;
2906 ssize_t rv;
2908 if (!entry->show)
2909 return -EIO;
2911 rv = mddev ? mddev_lock(mddev) : -EBUSY;
2912 if (!rv) {
2913 if (rdev->mddev == NULL)
2914 rv = -EBUSY;
2915 else
2916 rv = entry->show(rdev, page);
2917 mddev_unlock(mddev);
2919 return rv;
2922 static ssize_t
2923 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
2924 const char *page, size_t length)
2926 struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2927 mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2928 ssize_t rv;
2929 mddev_t *mddev = rdev->mddev;
2931 if (!entry->store)
2932 return -EIO;
2933 if (!capable(CAP_SYS_ADMIN))
2934 return -EACCES;
2935 rv = mddev ? mddev_lock(mddev): -EBUSY;
2936 if (!rv) {
2937 if (rdev->mddev == NULL)
2938 rv = -EBUSY;
2939 else
2940 rv = entry->store(rdev, page, length);
2941 mddev_unlock(mddev);
2943 return rv;
2946 static void rdev_free(struct kobject *ko)
2948 mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
2949 kfree(rdev);
2951 static const struct sysfs_ops rdev_sysfs_ops = {
2952 .show = rdev_attr_show,
2953 .store = rdev_attr_store,
2955 static struct kobj_type rdev_ktype = {
2956 .release = rdev_free,
2957 .sysfs_ops = &rdev_sysfs_ops,
2958 .default_attrs = rdev_default_attrs,
2961 int md_rdev_init(mdk_rdev_t *rdev)
2963 rdev->desc_nr = -1;
2964 rdev->saved_raid_disk = -1;
2965 rdev->raid_disk = -1;
2966 rdev->flags = 0;
2967 rdev->data_offset = 0;
2968 rdev->sb_events = 0;
2969 rdev->last_read_error.tv_sec = 0;
2970 rdev->last_read_error.tv_nsec = 0;
2971 rdev->sb_loaded = 0;
2972 rdev->bb_page = NULL;
2973 atomic_set(&rdev->nr_pending, 0);
2974 atomic_set(&rdev->read_errors, 0);
2975 atomic_set(&rdev->corrected_errors, 0);
2977 INIT_LIST_HEAD(&rdev->same_set);
2978 init_waitqueue_head(&rdev->blocked_wait);
2980 /* Add space to store bad block list.
2981 * This reserves the space even on arrays where it cannot
2982 * be used - I wonder if that matters
2984 rdev->badblocks.count = 0;
2985 rdev->badblocks.shift = 0;
2986 rdev->badblocks.page = kmalloc(PAGE_SIZE, GFP_KERNEL);
2987 seqlock_init(&rdev->badblocks.lock);
2988 if (rdev->badblocks.page == NULL)
2989 return -ENOMEM;
2991 return 0;
2993 EXPORT_SYMBOL_GPL(md_rdev_init);
2995 * Import a device. If 'super_format' >= 0, then sanity check the superblock
2997 * mark the device faulty if:
2999 * - the device is nonexistent (zero size)
3000 * - the device has no valid superblock
3002 * a faulty rdev _never_ has rdev->sb set.
3004 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
3006 char b[BDEVNAME_SIZE];
3007 int err;
3008 mdk_rdev_t *rdev;
3009 sector_t size;
3011 rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
3012 if (!rdev) {
3013 printk(KERN_ERR "md: could not alloc mem for new device!\n");
3014 return ERR_PTR(-ENOMEM);
3017 err = md_rdev_init(rdev);
3018 if (err)
3019 goto abort_free;
3020 err = alloc_disk_sb(rdev);
3021 if (err)
3022 goto abort_free;
3024 err = lock_rdev(rdev, newdev, super_format == -2);
3025 if (err)
3026 goto abort_free;
3028 kobject_init(&rdev->kobj, &rdev_ktype);
3030 size = i_size_read(rdev->bdev->bd_inode) >> BLOCK_SIZE_BITS;
3031 if (!size) {
3032 printk(KERN_WARNING
3033 "md: %s has zero or unknown size, marking faulty!\n",
3034 bdevname(rdev->bdev,b));
3035 err = -EINVAL;
3036 goto abort_free;
3039 if (super_format >= 0) {
3040 err = super_types[super_format].
3041 load_super(rdev, NULL, super_minor);
3042 if (err == -EINVAL) {
3043 printk(KERN_WARNING
3044 "md: %s does not have a valid v%d.%d "
3045 "superblock, not importing!\n",
3046 bdevname(rdev->bdev,b),
3047 super_format, super_minor);
3048 goto abort_free;
3050 if (err < 0) {
3051 printk(KERN_WARNING
3052 "md: could not read %s's sb, not importing!\n",
3053 bdevname(rdev->bdev,b));
3054 goto abort_free;
3057 if (super_format == -1)
3058 /* hot-add for 0.90, or non-persistent: so no badblocks */
3059 rdev->badblocks.shift = -1;
3061 return rdev;
3063 abort_free:
3064 if (rdev->bdev)
3065 unlock_rdev(rdev);
3066 free_disk_sb(rdev);
3067 kfree(rdev->badblocks.page);
3068 kfree(rdev);
3069 return ERR_PTR(err);
3073 * Check a full RAID array for plausibility
3077 static void analyze_sbs(mddev_t * mddev)
3079 int i;
3080 mdk_rdev_t *rdev, *freshest, *tmp;
3081 char b[BDEVNAME_SIZE];
3083 freshest = NULL;
3084 rdev_for_each(rdev, tmp, mddev)
3085 switch (super_types[mddev->major_version].
3086 load_super(rdev, freshest, mddev->minor_version)) {
3087 case 1:
3088 freshest = rdev;
3089 break;
3090 case 0:
3091 break;
3092 default:
3093 printk( KERN_ERR \
3094 "md: fatal superblock inconsistency in %s"
3095 " -- removing from array\n",
3096 bdevname(rdev->bdev,b));
3097 kick_rdev_from_array(rdev);
3101 super_types[mddev->major_version].
3102 validate_super(mddev, freshest);
3104 i = 0;
3105 rdev_for_each(rdev, tmp, mddev) {
3106 if (mddev->max_disks &&
3107 (rdev->desc_nr >= mddev->max_disks ||
3108 i > mddev->max_disks)) {
3109 printk(KERN_WARNING
3110 "md: %s: %s: only %d devices permitted\n",
3111 mdname(mddev), bdevname(rdev->bdev, b),
3112 mddev->max_disks);
3113 kick_rdev_from_array(rdev);
3114 continue;
3116 if (rdev != freshest)
3117 if (super_types[mddev->major_version].
3118 validate_super(mddev, rdev)) {
3119 printk(KERN_WARNING "md: kicking non-fresh %s"
3120 " from array!\n",
3121 bdevname(rdev->bdev,b));
3122 kick_rdev_from_array(rdev);
3123 continue;
3125 if (mddev->level == LEVEL_MULTIPATH) {
3126 rdev->desc_nr = i++;
3127 rdev->raid_disk = rdev->desc_nr;
3128 set_bit(In_sync, &rdev->flags);
3129 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
3130 rdev->raid_disk = -1;
3131 clear_bit(In_sync, &rdev->flags);
3136 /* Read a fixed-point number.
3137 * Numbers in sysfs attributes should be in "standard" units where
3138 * possible, so time should be in seconds.
3139 * However we internally use a a much smaller unit such as
3140 * milliseconds or jiffies.
3141 * This function takes a decimal number with a possible fractional
3142 * component, and produces an integer which is the result of
3143 * multiplying that number by 10^'scale'.
3144 * all without any floating-point arithmetic.
3146 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
3148 unsigned long result = 0;
3149 long decimals = -1;
3150 while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
3151 if (*cp == '.')
3152 decimals = 0;
3153 else if (decimals < scale) {
3154 unsigned int value;
3155 value = *cp - '0';
3156 result = result * 10 + value;
3157 if (decimals >= 0)
3158 decimals++;
3160 cp++;
3162 if (*cp == '\n')
3163 cp++;
3164 if (*cp)
3165 return -EINVAL;
3166 if (decimals < 0)
3167 decimals = 0;
3168 while (decimals < scale) {
3169 result *= 10;
3170 decimals ++;
3172 *res = result;
3173 return 0;
3177 static void md_safemode_timeout(unsigned long data);
3179 static ssize_t
3180 safe_delay_show(mddev_t *mddev, char *page)
3182 int msec = (mddev->safemode_delay*1000)/HZ;
3183 return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
3185 static ssize_t
3186 safe_delay_store(mddev_t *mddev, const char *cbuf, size_t len)
3188 unsigned long msec;
3190 if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
3191 return -EINVAL;
3192 if (msec == 0)
3193 mddev->safemode_delay = 0;
3194 else {
3195 unsigned long old_delay = mddev->safemode_delay;
3196 mddev->safemode_delay = (msec*HZ)/1000;
3197 if (mddev->safemode_delay == 0)
3198 mddev->safemode_delay = 1;
3199 if (mddev->safemode_delay < old_delay)
3200 md_safemode_timeout((unsigned long)mddev);
3202 return len;
3204 static struct md_sysfs_entry md_safe_delay =
3205 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
3207 static ssize_t
3208 level_show(mddev_t *mddev, char *page)
3210 struct mdk_personality *p = mddev->pers;
3211 if (p)
3212 return sprintf(page, "%s\n", p->name);
3213 else if (mddev->clevel[0])
3214 return sprintf(page, "%s\n", mddev->clevel);
3215 else if (mddev->level != LEVEL_NONE)
3216 return sprintf(page, "%d\n", mddev->level);
3217 else
3218 return 0;
3221 static ssize_t
3222 level_store(mddev_t *mddev, const char *buf, size_t len)
3224 char clevel[16];
3225 ssize_t rv = len;
3226 struct mdk_personality *pers;
3227 long level;
3228 void *priv;
3229 mdk_rdev_t *rdev;
3231 if (mddev->pers == NULL) {
3232 if (len == 0)
3233 return 0;
3234 if (len >= sizeof(mddev->clevel))
3235 return -ENOSPC;
3236 strncpy(mddev->clevel, buf, len);
3237 if (mddev->clevel[len-1] == '\n')
3238 len--;
3239 mddev->clevel[len] = 0;
3240 mddev->level = LEVEL_NONE;
3241 return rv;
3244 /* request to change the personality. Need to ensure:
3245 * - array is not engaged in resync/recovery/reshape
3246 * - old personality can be suspended
3247 * - new personality will access other array.
3250 if (mddev->sync_thread ||
3251 mddev->reshape_position != MaxSector ||
3252 mddev->sysfs_active)
3253 return -EBUSY;
3255 if (!mddev->pers->quiesce) {
3256 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3257 mdname(mddev), mddev->pers->name);
3258 return -EINVAL;
3261 /* Now find the new personality */
3262 if (len == 0 || len >= sizeof(clevel))
3263 return -EINVAL;
3264 strncpy(clevel, buf, len);
3265 if (clevel[len-1] == '\n')
3266 len--;
3267 clevel[len] = 0;
3268 if (strict_strtol(clevel, 10, &level))
3269 level = LEVEL_NONE;
3271 if (request_module("md-%s", clevel) != 0)
3272 request_module("md-level-%s", clevel);
3273 spin_lock(&pers_lock);
3274 pers = find_pers(level, clevel);
3275 if (!pers || !try_module_get(pers->owner)) {
3276 spin_unlock(&pers_lock);
3277 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3278 return -EINVAL;
3280 spin_unlock(&pers_lock);
3282 if (pers == mddev->pers) {
3283 /* Nothing to do! */
3284 module_put(pers->owner);
3285 return rv;
3287 if (!pers->takeover) {
3288 module_put(pers->owner);
3289 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3290 mdname(mddev), clevel);
3291 return -EINVAL;
3294 list_for_each_entry(rdev, &mddev->disks, same_set)
3295 rdev->new_raid_disk = rdev->raid_disk;
3297 /* ->takeover must set new_* and/or delta_disks
3298 * if it succeeds, and may set them when it fails.
3300 priv = pers->takeover(mddev);
3301 if (IS_ERR(priv)) {
3302 mddev->new_level = mddev->level;
3303 mddev->new_layout = mddev->layout;
3304 mddev->new_chunk_sectors = mddev->chunk_sectors;
3305 mddev->raid_disks -= mddev->delta_disks;
3306 mddev->delta_disks = 0;
3307 module_put(pers->owner);
3308 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3309 mdname(mddev), clevel);
3310 return PTR_ERR(priv);
3313 /* Looks like we have a winner */
3314 mddev_suspend(mddev);
3315 mddev->pers->stop(mddev);
3317 if (mddev->pers->sync_request == NULL &&
3318 pers->sync_request != NULL) {
3319 /* need to add the md_redundancy_group */
3320 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3321 printk(KERN_WARNING
3322 "md: cannot register extra attributes for %s\n",
3323 mdname(mddev));
3324 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, NULL, "sync_action");
3326 if (mddev->pers->sync_request != NULL &&
3327 pers->sync_request == NULL) {
3328 /* need to remove the md_redundancy_group */
3329 if (mddev->to_remove == NULL)
3330 mddev->to_remove = &md_redundancy_group;
3333 if (mddev->pers->sync_request == NULL &&
3334 mddev->external) {
3335 /* We are converting from a no-redundancy array
3336 * to a redundancy array and metadata is managed
3337 * externally so we need to be sure that writes
3338 * won't block due to a need to transition
3339 * clean->dirty
3340 * until external management is started.
3342 mddev->in_sync = 0;
3343 mddev->safemode_delay = 0;
3344 mddev->safemode = 0;
3347 list_for_each_entry(rdev, &mddev->disks, same_set) {
3348 if (rdev->raid_disk < 0)
3349 continue;
3350 if (rdev->new_raid_disk >= mddev->raid_disks)
3351 rdev->new_raid_disk = -1;
3352 if (rdev->new_raid_disk == rdev->raid_disk)
3353 continue;
3354 sysfs_unlink_rdev(mddev, rdev);
3356 list_for_each_entry(rdev, &mddev->disks, same_set) {
3357 if (rdev->raid_disk < 0)
3358 continue;
3359 if (rdev->new_raid_disk == rdev->raid_disk)
3360 continue;
3361 rdev->raid_disk = rdev->new_raid_disk;
3362 if (rdev->raid_disk < 0)
3363 clear_bit(In_sync, &rdev->flags);
3364 else {
3365 if (sysfs_link_rdev(mddev, rdev))
3366 printk(KERN_WARNING "md: cannot register rd%d"
3367 " for %s after level change\n",
3368 rdev->raid_disk, mdname(mddev));
3372 module_put(mddev->pers->owner);
3373 mddev->pers = pers;
3374 mddev->private = priv;
3375 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3376 mddev->level = mddev->new_level;
3377 mddev->layout = mddev->new_layout;
3378 mddev->chunk_sectors = mddev->new_chunk_sectors;
3379 mddev->delta_disks = 0;
3380 mddev->degraded = 0;
3381 if (mddev->pers->sync_request == NULL) {
3382 /* this is now an array without redundancy, so
3383 * it must always be in_sync
3385 mddev->in_sync = 1;
3386 del_timer_sync(&mddev->safemode_timer);
3388 pers->run(mddev);
3389 mddev_resume(mddev);
3390 set_bit(MD_CHANGE_DEVS, &mddev->flags);
3391 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3392 md_wakeup_thread(mddev->thread);
3393 sysfs_notify(&mddev->kobj, NULL, "level");
3394 md_new_event(mddev);
3395 return rv;
3398 static struct md_sysfs_entry md_level =
3399 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3402 static ssize_t
3403 layout_show(mddev_t *mddev, char *page)
3405 /* just a number, not meaningful for all levels */
3406 if (mddev->reshape_position != MaxSector &&
3407 mddev->layout != mddev->new_layout)
3408 return sprintf(page, "%d (%d)\n",
3409 mddev->new_layout, mddev->layout);
3410 return sprintf(page, "%d\n", mddev->layout);
3413 static ssize_t
3414 layout_store(mddev_t *mddev, const char *buf, size_t len)
3416 char *e;
3417 unsigned long n = simple_strtoul(buf, &e, 10);
3419 if (!*buf || (*e && *e != '\n'))
3420 return -EINVAL;
3422 if (mddev->pers) {
3423 int err;
3424 if (mddev->pers->check_reshape == NULL)
3425 return -EBUSY;
3426 mddev->new_layout = n;
3427 err = mddev->pers->check_reshape(mddev);
3428 if (err) {
3429 mddev->new_layout = mddev->layout;
3430 return err;
3432 } else {
3433 mddev->new_layout = n;
3434 if (mddev->reshape_position == MaxSector)
3435 mddev->layout = n;
3437 return len;
3439 static struct md_sysfs_entry md_layout =
3440 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3443 static ssize_t
3444 raid_disks_show(mddev_t *mddev, char *page)
3446 if (mddev->raid_disks == 0)
3447 return 0;
3448 if (mddev->reshape_position != MaxSector &&
3449 mddev->delta_disks != 0)
3450 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3451 mddev->raid_disks - mddev->delta_disks);
3452 return sprintf(page, "%d\n", mddev->raid_disks);
3455 static int update_raid_disks(mddev_t *mddev, int raid_disks);
3457 static ssize_t
3458 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
3460 char *e;
3461 int rv = 0;
3462 unsigned long n = simple_strtoul(buf, &e, 10);
3464 if (!*buf || (*e && *e != '\n'))
3465 return -EINVAL;
3467 if (mddev->pers)
3468 rv = update_raid_disks(mddev, n);
3469 else if (mddev->reshape_position != MaxSector) {
3470 int olddisks = mddev->raid_disks - mddev->delta_disks;
3471 mddev->delta_disks = n - olddisks;
3472 mddev->raid_disks = n;
3473 } else
3474 mddev->raid_disks = n;
3475 return rv ? rv : len;
3477 static struct md_sysfs_entry md_raid_disks =
3478 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3480 static ssize_t
3481 chunk_size_show(mddev_t *mddev, char *page)
3483 if (mddev->reshape_position != MaxSector &&
3484 mddev->chunk_sectors != mddev->new_chunk_sectors)
3485 return sprintf(page, "%d (%d)\n",
3486 mddev->new_chunk_sectors << 9,
3487 mddev->chunk_sectors << 9);
3488 return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3491 static ssize_t
3492 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
3494 char *e;
3495 unsigned long n = simple_strtoul(buf, &e, 10);
3497 if (!*buf || (*e && *e != '\n'))
3498 return -EINVAL;
3500 if (mddev->pers) {
3501 int err;
3502 if (mddev->pers->check_reshape == NULL)
3503 return -EBUSY;
3504 mddev->new_chunk_sectors = n >> 9;
3505 err = mddev->pers->check_reshape(mddev);
3506 if (err) {
3507 mddev->new_chunk_sectors = mddev->chunk_sectors;
3508 return err;
3510 } else {
3511 mddev->new_chunk_sectors = n >> 9;
3512 if (mddev->reshape_position == MaxSector)
3513 mddev->chunk_sectors = n >> 9;
3515 return len;
3517 static struct md_sysfs_entry md_chunk_size =
3518 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3520 static ssize_t
3521 resync_start_show(mddev_t *mddev, char *page)
3523 if (mddev->recovery_cp == MaxSector)
3524 return sprintf(page, "none\n");
3525 return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3528 static ssize_t
3529 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
3531 char *e;
3532 unsigned long long n = simple_strtoull(buf, &e, 10);
3534 if (mddev->pers && !test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3535 return -EBUSY;
3536 if (cmd_match(buf, "none"))
3537 n = MaxSector;
3538 else if (!*buf || (*e && *e != '\n'))
3539 return -EINVAL;
3541 mddev->recovery_cp = n;
3542 return len;
3544 static struct md_sysfs_entry md_resync_start =
3545 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
3548 * The array state can be:
3550 * clear
3551 * No devices, no size, no level
3552 * Equivalent to STOP_ARRAY ioctl
3553 * inactive
3554 * May have some settings, but array is not active
3555 * all IO results in error
3556 * When written, doesn't tear down array, but just stops it
3557 * suspended (not supported yet)
3558 * All IO requests will block. The array can be reconfigured.
3559 * Writing this, if accepted, will block until array is quiescent
3560 * readonly
3561 * no resync can happen. no superblocks get written.
3562 * write requests fail
3563 * read-auto
3564 * like readonly, but behaves like 'clean' on a write request.
3566 * clean - no pending writes, but otherwise active.
3567 * When written to inactive array, starts without resync
3568 * If a write request arrives then
3569 * if metadata is known, mark 'dirty' and switch to 'active'.
3570 * if not known, block and switch to write-pending
3571 * If written to an active array that has pending writes, then fails.
3572 * active
3573 * fully active: IO and resync can be happening.
3574 * When written to inactive array, starts with resync
3576 * write-pending
3577 * clean, but writes are blocked waiting for 'active' to be written.
3579 * active-idle
3580 * like active, but no writes have been seen for a while (100msec).
3583 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3584 write_pending, active_idle, bad_word};
3585 static char *array_states[] = {
3586 "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3587 "write-pending", "active-idle", NULL };
3589 static int match_word(const char *word, char **list)
3591 int n;
3592 for (n=0; list[n]; n++)
3593 if (cmd_match(word, list[n]))
3594 break;
3595 return n;
3598 static ssize_t
3599 array_state_show(mddev_t *mddev, char *page)
3601 enum array_state st = inactive;
3603 if (mddev->pers)
3604 switch(mddev->ro) {
3605 case 1:
3606 st = readonly;
3607 break;
3608 case 2:
3609 st = read_auto;
3610 break;
3611 case 0:
3612 if (mddev->in_sync)
3613 st = clean;
3614 else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3615 st = write_pending;
3616 else if (mddev->safemode)
3617 st = active_idle;
3618 else
3619 st = active;
3621 else {
3622 if (list_empty(&mddev->disks) &&
3623 mddev->raid_disks == 0 &&
3624 mddev->dev_sectors == 0)
3625 st = clear;
3626 else
3627 st = inactive;
3629 return sprintf(page, "%s\n", array_states[st]);
3632 static int do_md_stop(mddev_t * mddev, int ro, int is_open);
3633 static int md_set_readonly(mddev_t * mddev, int is_open);
3634 static int do_md_run(mddev_t * mddev);
3635 static int restart_array(mddev_t *mddev);
3637 static ssize_t
3638 array_state_store(mddev_t *mddev, const char *buf, size_t len)
3640 int err = -EINVAL;
3641 enum array_state st = match_word(buf, array_states);
3642 switch(st) {
3643 case bad_word:
3644 break;
3645 case clear:
3646 /* stopping an active array */
3647 if (atomic_read(&mddev->openers) > 0)
3648 return -EBUSY;
3649 err = do_md_stop(mddev, 0, 0);
3650 break;
3651 case inactive:
3652 /* stopping an active array */
3653 if (mddev->pers) {
3654 if (atomic_read(&mddev->openers) > 0)
3655 return -EBUSY;
3656 err = do_md_stop(mddev, 2, 0);
3657 } else
3658 err = 0; /* already inactive */
3659 break;
3660 case suspended:
3661 break; /* not supported yet */
3662 case readonly:
3663 if (mddev->pers)
3664 err = md_set_readonly(mddev, 0);
3665 else {
3666 mddev->ro = 1;
3667 set_disk_ro(mddev->gendisk, 1);
3668 err = do_md_run(mddev);
3670 break;
3671 case read_auto:
3672 if (mddev->pers) {
3673 if (mddev->ro == 0)
3674 err = md_set_readonly(mddev, 0);
3675 else if (mddev->ro == 1)
3676 err = restart_array(mddev);
3677 if (err == 0) {
3678 mddev->ro = 2;
3679 set_disk_ro(mddev->gendisk, 0);
3681 } else {
3682 mddev->ro = 2;
3683 err = do_md_run(mddev);
3685 break;
3686 case clean:
3687 if (mddev->pers) {
3688 restart_array(mddev);
3689 spin_lock_irq(&mddev->write_lock);
3690 if (atomic_read(&mddev->writes_pending) == 0) {
3691 if (mddev->in_sync == 0) {
3692 mddev->in_sync = 1;
3693 if (mddev->safemode == 1)
3694 mddev->safemode = 0;
3695 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3697 err = 0;
3698 } else
3699 err = -EBUSY;
3700 spin_unlock_irq(&mddev->write_lock);
3701 } else
3702 err = -EINVAL;
3703 break;
3704 case active:
3705 if (mddev->pers) {
3706 restart_array(mddev);
3707 clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3708 wake_up(&mddev->sb_wait);
3709 err = 0;
3710 } else {
3711 mddev->ro = 0;
3712 set_disk_ro(mddev->gendisk, 0);
3713 err = do_md_run(mddev);
3715 break;
3716 case write_pending:
3717 case active_idle:
3718 /* these cannot be set */
3719 break;
3721 if (err)
3722 return err;
3723 else {
3724 sysfs_notify_dirent_safe(mddev->sysfs_state);
3725 return len;
3728 static struct md_sysfs_entry md_array_state =
3729 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3731 static ssize_t
3732 max_corrected_read_errors_show(mddev_t *mddev, char *page) {
3733 return sprintf(page, "%d\n",
3734 atomic_read(&mddev->max_corr_read_errors));
3737 static ssize_t
3738 max_corrected_read_errors_store(mddev_t *mddev, const char *buf, size_t len)
3740 char *e;
3741 unsigned long n = simple_strtoul(buf, &e, 10);
3743 if (*buf && (*e == 0 || *e == '\n')) {
3744 atomic_set(&mddev->max_corr_read_errors, n);
3745 return len;
3747 return -EINVAL;
3750 static struct md_sysfs_entry max_corr_read_errors =
3751 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
3752 max_corrected_read_errors_store);
3754 static ssize_t
3755 null_show(mddev_t *mddev, char *page)
3757 return -EINVAL;
3760 static ssize_t
3761 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
3763 /* buf must be %d:%d\n? giving major and minor numbers */
3764 /* The new device is added to the array.
3765 * If the array has a persistent superblock, we read the
3766 * superblock to initialise info and check validity.
3767 * Otherwise, only checking done is that in bind_rdev_to_array,
3768 * which mainly checks size.
3770 char *e;
3771 int major = simple_strtoul(buf, &e, 10);
3772 int minor;
3773 dev_t dev;
3774 mdk_rdev_t *rdev;
3775 int err;
3777 if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
3778 return -EINVAL;
3779 minor = simple_strtoul(e+1, &e, 10);
3780 if (*e && *e != '\n')
3781 return -EINVAL;
3782 dev = MKDEV(major, minor);
3783 if (major != MAJOR(dev) ||
3784 minor != MINOR(dev))
3785 return -EOVERFLOW;
3788 if (mddev->persistent) {
3789 rdev = md_import_device(dev, mddev->major_version,
3790 mddev->minor_version);
3791 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
3792 mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
3793 mdk_rdev_t, same_set);
3794 err = super_types[mddev->major_version]
3795 .load_super(rdev, rdev0, mddev->minor_version);
3796 if (err < 0)
3797 goto out;
3799 } else if (mddev->external)
3800 rdev = md_import_device(dev, -2, -1);
3801 else
3802 rdev = md_import_device(dev, -1, -1);
3804 if (IS_ERR(rdev))
3805 return PTR_ERR(rdev);
3806 err = bind_rdev_to_array(rdev, mddev);
3807 out:
3808 if (err)
3809 export_rdev(rdev);
3810 return err ? err : len;
3813 static struct md_sysfs_entry md_new_device =
3814 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
3816 static ssize_t
3817 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
3819 char *end;
3820 unsigned long chunk, end_chunk;
3822 if (!mddev->bitmap)
3823 goto out;
3824 /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
3825 while (*buf) {
3826 chunk = end_chunk = simple_strtoul(buf, &end, 0);
3827 if (buf == end) break;
3828 if (*end == '-') { /* range */
3829 buf = end + 1;
3830 end_chunk = simple_strtoul(buf, &end, 0);
3831 if (buf == end) break;
3833 if (*end && !isspace(*end)) break;
3834 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
3835 buf = skip_spaces(end);
3837 bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
3838 out:
3839 return len;
3842 static struct md_sysfs_entry md_bitmap =
3843 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
3845 static ssize_t
3846 size_show(mddev_t *mddev, char *page)
3848 return sprintf(page, "%llu\n",
3849 (unsigned long long)mddev->dev_sectors / 2);
3852 static int update_size(mddev_t *mddev, sector_t num_sectors);
3854 static ssize_t
3855 size_store(mddev_t *mddev, const char *buf, size_t len)
3857 /* If array is inactive, we can reduce the component size, but
3858 * not increase it (except from 0).
3859 * If array is active, we can try an on-line resize
3861 sector_t sectors;
3862 int err = strict_blocks_to_sectors(buf, &sectors);
3864 if (err < 0)
3865 return err;
3866 if (mddev->pers) {
3867 err = update_size(mddev, sectors);
3868 md_update_sb(mddev, 1);
3869 } else {
3870 if (mddev->dev_sectors == 0 ||
3871 mddev->dev_sectors > sectors)
3872 mddev->dev_sectors = sectors;
3873 else
3874 err = -ENOSPC;
3876 return err ? err : len;
3879 static struct md_sysfs_entry md_size =
3880 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
3883 /* Metdata version.
3884 * This is one of
3885 * 'none' for arrays with no metadata (good luck...)
3886 * 'external' for arrays with externally managed metadata,
3887 * or N.M for internally known formats
3889 static ssize_t
3890 metadata_show(mddev_t *mddev, char *page)
3892 if (mddev->persistent)
3893 return sprintf(page, "%d.%d\n",
3894 mddev->major_version, mddev->minor_version);
3895 else if (mddev->external)
3896 return sprintf(page, "external:%s\n", mddev->metadata_type);
3897 else
3898 return sprintf(page, "none\n");
3901 static ssize_t
3902 metadata_store(mddev_t *mddev, const char *buf, size_t len)
3904 int major, minor;
3905 char *e;
3906 /* Changing the details of 'external' metadata is
3907 * always permitted. Otherwise there must be
3908 * no devices attached to the array.
3910 if (mddev->external && strncmp(buf, "external:", 9) == 0)
3912 else if (!list_empty(&mddev->disks))
3913 return -EBUSY;
3915 if (cmd_match(buf, "none")) {
3916 mddev->persistent = 0;
3917 mddev->external = 0;
3918 mddev->major_version = 0;
3919 mddev->minor_version = 90;
3920 return len;
3922 if (strncmp(buf, "external:", 9) == 0) {
3923 size_t namelen = len-9;
3924 if (namelen >= sizeof(mddev->metadata_type))
3925 namelen = sizeof(mddev->metadata_type)-1;
3926 strncpy(mddev->metadata_type, buf+9, namelen);
3927 mddev->metadata_type[namelen] = 0;
3928 if (namelen && mddev->metadata_type[namelen-1] == '\n')
3929 mddev->metadata_type[--namelen] = 0;
3930 mddev->persistent = 0;
3931 mddev->external = 1;
3932 mddev->major_version = 0;
3933 mddev->minor_version = 90;
3934 return len;
3936 major = simple_strtoul(buf, &e, 10);
3937 if (e==buf || *e != '.')
3938 return -EINVAL;
3939 buf = e+1;
3940 minor = simple_strtoul(buf, &e, 10);
3941 if (e==buf || (*e && *e != '\n') )
3942 return -EINVAL;
3943 if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
3944 return -ENOENT;
3945 mddev->major_version = major;
3946 mddev->minor_version = minor;
3947 mddev->persistent = 1;
3948 mddev->external = 0;
3949 return len;
3952 static struct md_sysfs_entry md_metadata =
3953 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
3955 static ssize_t
3956 action_show(mddev_t *mddev, char *page)
3958 char *type = "idle";
3959 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3960 type = "frozen";
3961 else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3962 (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
3963 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
3964 type = "reshape";
3965 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3966 if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
3967 type = "resync";
3968 else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
3969 type = "check";
3970 else
3971 type = "repair";
3972 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
3973 type = "recover";
3975 return sprintf(page, "%s\n", type);
3978 static void reap_sync_thread(mddev_t *mddev);
3980 static ssize_t
3981 action_store(mddev_t *mddev, const char *page, size_t len)
3983 if (!mddev->pers || !mddev->pers->sync_request)
3984 return -EINVAL;
3986 if (cmd_match(page, "frozen"))
3987 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3988 else
3989 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3991 if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
3992 if (mddev->sync_thread) {
3993 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3994 reap_sync_thread(mddev);
3996 } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3997 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
3998 return -EBUSY;
3999 else if (cmd_match(page, "resync"))
4000 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4001 else if (cmd_match(page, "recover")) {
4002 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
4003 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4004 } else if (cmd_match(page, "reshape")) {
4005 int err;
4006 if (mddev->pers->start_reshape == NULL)
4007 return -EINVAL;
4008 err = mddev->pers->start_reshape(mddev);
4009 if (err)
4010 return err;
4011 sysfs_notify(&mddev->kobj, NULL, "degraded");
4012 } else {
4013 if (cmd_match(page, "check"))
4014 set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
4015 else if (!cmd_match(page, "repair"))
4016 return -EINVAL;
4017 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
4018 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
4020 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4021 md_wakeup_thread(mddev->thread);
4022 sysfs_notify_dirent_safe(mddev->sysfs_action);
4023 return len;
4026 static ssize_t
4027 mismatch_cnt_show(mddev_t *mddev, char *page)
4029 return sprintf(page, "%llu\n",
4030 (unsigned long long) mddev->resync_mismatches);
4033 static struct md_sysfs_entry md_scan_mode =
4034 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
4037 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
4039 static ssize_t
4040 sync_min_show(mddev_t *mddev, char *page)
4042 return sprintf(page, "%d (%s)\n", speed_min(mddev),
4043 mddev->sync_speed_min ? "local": "system");
4046 static ssize_t
4047 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
4049 int min;
4050 char *e;
4051 if (strncmp(buf, "system", 6)==0) {
4052 mddev->sync_speed_min = 0;
4053 return len;
4055 min = simple_strtoul(buf, &e, 10);
4056 if (buf == e || (*e && *e != '\n') || min <= 0)
4057 return -EINVAL;
4058 mddev->sync_speed_min = min;
4059 return len;
4062 static struct md_sysfs_entry md_sync_min =
4063 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
4065 static ssize_t
4066 sync_max_show(mddev_t *mddev, char *page)
4068 return sprintf(page, "%d (%s)\n", speed_max(mddev),
4069 mddev->sync_speed_max ? "local": "system");
4072 static ssize_t
4073 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
4075 int max;
4076 char *e;
4077 if (strncmp(buf, "system", 6)==0) {
4078 mddev->sync_speed_max = 0;
4079 return len;
4081 max = simple_strtoul(buf, &e, 10);
4082 if (buf == e || (*e && *e != '\n') || max <= 0)
4083 return -EINVAL;
4084 mddev->sync_speed_max = max;
4085 return len;
4088 static struct md_sysfs_entry md_sync_max =
4089 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
4091 static ssize_t
4092 degraded_show(mddev_t *mddev, char *page)
4094 return sprintf(page, "%d\n", mddev->degraded);
4096 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
4098 static ssize_t
4099 sync_force_parallel_show(mddev_t *mddev, char *page)
4101 return sprintf(page, "%d\n", mddev->parallel_resync);
4104 static ssize_t
4105 sync_force_parallel_store(mddev_t *mddev, const char *buf, size_t len)
4107 long n;
4109 if (strict_strtol(buf, 10, &n))
4110 return -EINVAL;
4112 if (n != 0 && n != 1)
4113 return -EINVAL;
4115 mddev->parallel_resync = n;
4117 if (mddev->sync_thread)
4118 wake_up(&resync_wait);
4120 return len;
4123 /* force parallel resync, even with shared block devices */
4124 static struct md_sysfs_entry md_sync_force_parallel =
4125 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
4126 sync_force_parallel_show, sync_force_parallel_store);
4128 static ssize_t
4129 sync_speed_show(mddev_t *mddev, char *page)
4131 unsigned long resync, dt, db;
4132 if (mddev->curr_resync == 0)
4133 return sprintf(page, "none\n");
4134 resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
4135 dt = (jiffies - mddev->resync_mark) / HZ;
4136 if (!dt) dt++;
4137 db = resync - mddev->resync_mark_cnt;
4138 return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
4141 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
4143 static ssize_t
4144 sync_completed_show(mddev_t *mddev, char *page)
4146 unsigned long long max_sectors, resync;
4148 if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4149 return sprintf(page, "none\n");
4151 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
4152 max_sectors = mddev->resync_max_sectors;
4153 else
4154 max_sectors = mddev->dev_sectors;
4156 resync = mddev->curr_resync_completed;
4157 return sprintf(page, "%llu / %llu\n", resync, max_sectors);
4160 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
4162 static ssize_t
4163 min_sync_show(mddev_t *mddev, char *page)
4165 return sprintf(page, "%llu\n",
4166 (unsigned long long)mddev->resync_min);
4168 static ssize_t
4169 min_sync_store(mddev_t *mddev, const char *buf, size_t len)
4171 unsigned long long min;
4172 if (strict_strtoull(buf, 10, &min))
4173 return -EINVAL;
4174 if (min > mddev->resync_max)
4175 return -EINVAL;
4176 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4177 return -EBUSY;
4179 /* Must be a multiple of chunk_size */
4180 if (mddev->chunk_sectors) {
4181 sector_t temp = min;
4182 if (sector_div(temp, mddev->chunk_sectors))
4183 return -EINVAL;
4185 mddev->resync_min = min;
4187 return len;
4190 static struct md_sysfs_entry md_min_sync =
4191 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
4193 static ssize_t
4194 max_sync_show(mddev_t *mddev, char *page)
4196 if (mddev->resync_max == MaxSector)
4197 return sprintf(page, "max\n");
4198 else
4199 return sprintf(page, "%llu\n",
4200 (unsigned long long)mddev->resync_max);
4202 static ssize_t
4203 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
4205 if (strncmp(buf, "max", 3) == 0)
4206 mddev->resync_max = MaxSector;
4207 else {
4208 unsigned long long max;
4209 if (strict_strtoull(buf, 10, &max))
4210 return -EINVAL;
4211 if (max < mddev->resync_min)
4212 return -EINVAL;
4213 if (max < mddev->resync_max &&
4214 mddev->ro == 0 &&
4215 test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
4216 return -EBUSY;
4218 /* Must be a multiple of chunk_size */
4219 if (mddev->chunk_sectors) {
4220 sector_t temp = max;
4221 if (sector_div(temp, mddev->chunk_sectors))
4222 return -EINVAL;
4224 mddev->resync_max = max;
4226 wake_up(&mddev->recovery_wait);
4227 return len;
4230 static struct md_sysfs_entry md_max_sync =
4231 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
4233 static ssize_t
4234 suspend_lo_show(mddev_t *mddev, char *page)
4236 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
4239 static ssize_t
4240 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
4242 char *e;
4243 unsigned long long new = simple_strtoull(buf, &e, 10);
4244 unsigned long long old = mddev->suspend_lo;
4246 if (mddev->pers == NULL ||
4247 mddev->pers->quiesce == NULL)
4248 return -EINVAL;
4249 if (buf == e || (*e && *e != '\n'))
4250 return -EINVAL;
4252 mddev->suspend_lo = new;
4253 if (new >= old)
4254 /* Shrinking suspended region */
4255 mddev->pers->quiesce(mddev, 2);
4256 else {
4257 /* Expanding suspended region - need to wait */
4258 mddev->pers->quiesce(mddev, 1);
4259 mddev->pers->quiesce(mddev, 0);
4261 return len;
4263 static struct md_sysfs_entry md_suspend_lo =
4264 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4267 static ssize_t
4268 suspend_hi_show(mddev_t *mddev, char *page)
4270 return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4273 static ssize_t
4274 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
4276 char *e;
4277 unsigned long long new = simple_strtoull(buf, &e, 10);
4278 unsigned long long old = mddev->suspend_hi;
4280 if (mddev->pers == NULL ||
4281 mddev->pers->quiesce == NULL)
4282 return -EINVAL;
4283 if (buf == e || (*e && *e != '\n'))
4284 return -EINVAL;
4286 mddev->suspend_hi = new;
4287 if (new <= old)
4288 /* Shrinking suspended region */
4289 mddev->pers->quiesce(mddev, 2);
4290 else {
4291 /* Expanding suspended region - need to wait */
4292 mddev->pers->quiesce(mddev, 1);
4293 mddev->pers->quiesce(mddev, 0);
4295 return len;
4297 static struct md_sysfs_entry md_suspend_hi =
4298 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4300 static ssize_t
4301 reshape_position_show(mddev_t *mddev, char *page)
4303 if (mddev->reshape_position != MaxSector)
4304 return sprintf(page, "%llu\n",
4305 (unsigned long long)mddev->reshape_position);
4306 strcpy(page, "none\n");
4307 return 5;
4310 static ssize_t
4311 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
4313 char *e;
4314 unsigned long long new = simple_strtoull(buf, &e, 10);
4315 if (mddev->pers)
4316 return -EBUSY;
4317 if (buf == e || (*e && *e != '\n'))
4318 return -EINVAL;
4319 mddev->reshape_position = new;
4320 mddev->delta_disks = 0;
4321 mddev->new_level = mddev->level;
4322 mddev->new_layout = mddev->layout;
4323 mddev->new_chunk_sectors = mddev->chunk_sectors;
4324 return len;
4327 static struct md_sysfs_entry md_reshape_position =
4328 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4329 reshape_position_store);
4331 static ssize_t
4332 array_size_show(mddev_t *mddev, char *page)
4334 if (mddev->external_size)
4335 return sprintf(page, "%llu\n",
4336 (unsigned long long)mddev->array_sectors/2);
4337 else
4338 return sprintf(page, "default\n");
4341 static ssize_t
4342 array_size_store(mddev_t *mddev, const char *buf, size_t len)
4344 sector_t sectors;
4346 if (strncmp(buf, "default", 7) == 0) {
4347 if (mddev->pers)
4348 sectors = mddev->pers->size(mddev, 0, 0);
4349 else
4350 sectors = mddev->array_sectors;
4352 mddev->external_size = 0;
4353 } else {
4354 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4355 return -EINVAL;
4356 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4357 return -E2BIG;
4359 mddev->external_size = 1;
4362 mddev->array_sectors = sectors;
4363 if (mddev->pers) {
4364 set_capacity(mddev->gendisk, mddev->array_sectors);
4365 revalidate_disk(mddev->gendisk);
4367 return len;
4370 static struct md_sysfs_entry md_array_size =
4371 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4372 array_size_store);
4374 static struct attribute *md_default_attrs[] = {
4375 &md_level.attr,
4376 &md_layout.attr,
4377 &md_raid_disks.attr,
4378 &md_chunk_size.attr,
4379 &md_size.attr,
4380 &md_resync_start.attr,
4381 &md_metadata.attr,
4382 &md_new_device.attr,
4383 &md_safe_delay.attr,
4384 &md_array_state.attr,
4385 &md_reshape_position.attr,
4386 &md_array_size.attr,
4387 &max_corr_read_errors.attr,
4388 NULL,
4391 static struct attribute *md_redundancy_attrs[] = {
4392 &md_scan_mode.attr,
4393 &md_mismatches.attr,
4394 &md_sync_min.attr,
4395 &md_sync_max.attr,
4396 &md_sync_speed.attr,
4397 &md_sync_force_parallel.attr,
4398 &md_sync_completed.attr,
4399 &md_min_sync.attr,
4400 &md_max_sync.attr,
4401 &md_suspend_lo.attr,
4402 &md_suspend_hi.attr,
4403 &md_bitmap.attr,
4404 &md_degraded.attr,
4405 NULL,
4407 static struct attribute_group md_redundancy_group = {
4408 .name = NULL,
4409 .attrs = md_redundancy_attrs,
4413 static ssize_t
4414 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4416 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4417 mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
4418 ssize_t rv;
4420 if (!entry->show)
4421 return -EIO;
4422 rv = mddev_lock(mddev);
4423 if (!rv) {
4424 rv = entry->show(mddev, page);
4425 mddev_unlock(mddev);
4427 return rv;
4430 static ssize_t
4431 md_attr_store(struct kobject *kobj, struct attribute *attr,
4432 const char *page, size_t length)
4434 struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4435 mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
4436 ssize_t rv;
4438 if (!entry->store)
4439 return -EIO;
4440 if (!capable(CAP_SYS_ADMIN))
4441 return -EACCES;
4442 rv = mddev_lock(mddev);
4443 if (mddev->hold_active == UNTIL_IOCTL)
4444 mddev->hold_active = 0;
4445 if (!rv) {
4446 rv = entry->store(mddev, page, length);
4447 mddev_unlock(mddev);
4449 return rv;
4452 static void md_free(struct kobject *ko)
4454 mddev_t *mddev = container_of(ko, mddev_t, kobj);
4456 if (mddev->sysfs_state)
4457 sysfs_put(mddev->sysfs_state);
4459 if (mddev->gendisk) {
4460 del_gendisk(mddev->gendisk);
4461 put_disk(mddev->gendisk);
4463 if (mddev->queue)
4464 blk_cleanup_queue(mddev->queue);
4466 kfree(mddev);
4469 static const struct sysfs_ops md_sysfs_ops = {
4470 .show = md_attr_show,
4471 .store = md_attr_store,
4473 static struct kobj_type md_ktype = {
4474 .release = md_free,
4475 .sysfs_ops = &md_sysfs_ops,
4476 .default_attrs = md_default_attrs,
4479 int mdp_major = 0;
4481 static void mddev_delayed_delete(struct work_struct *ws)
4483 mddev_t *mddev = container_of(ws, mddev_t, del_work);
4485 sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4486 kobject_del(&mddev->kobj);
4487 kobject_put(&mddev->kobj);
4490 static int md_alloc(dev_t dev, char *name)
4492 static DEFINE_MUTEX(disks_mutex);
4493 mddev_t *mddev = mddev_find(dev);
4494 struct gendisk *disk;
4495 int partitioned;
4496 int shift;
4497 int unit;
4498 int error;
4500 if (!mddev)
4501 return -ENODEV;
4503 partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4504 shift = partitioned ? MdpMinorShift : 0;
4505 unit = MINOR(mddev->unit) >> shift;
4507 /* wait for any previous instance of this device to be
4508 * completely removed (mddev_delayed_delete).
4510 flush_workqueue(md_misc_wq);
4512 mutex_lock(&disks_mutex);
4513 error = -EEXIST;
4514 if (mddev->gendisk)
4515 goto abort;
4517 if (name) {
4518 /* Need to ensure that 'name' is not a duplicate.
4520 mddev_t *mddev2;
4521 spin_lock(&all_mddevs_lock);
4523 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4524 if (mddev2->gendisk &&
4525 strcmp(mddev2->gendisk->disk_name, name) == 0) {
4526 spin_unlock(&all_mddevs_lock);
4527 goto abort;
4529 spin_unlock(&all_mddevs_lock);
4532 error = -ENOMEM;
4533 mddev->queue = blk_alloc_queue(GFP_KERNEL);
4534 if (!mddev->queue)
4535 goto abort;
4536 mddev->queue->queuedata = mddev;
4538 blk_queue_make_request(mddev->queue, md_make_request);
4540 disk = alloc_disk(1 << shift);
4541 if (!disk) {
4542 blk_cleanup_queue(mddev->queue);
4543 mddev->queue = NULL;
4544 goto abort;
4546 disk->major = MAJOR(mddev->unit);
4547 disk->first_minor = unit << shift;
4548 if (name)
4549 strcpy(disk->disk_name, name);
4550 else if (partitioned)
4551 sprintf(disk->disk_name, "md_d%d", unit);
4552 else
4553 sprintf(disk->disk_name, "md%d", unit);
4554 disk->fops = &md_fops;
4555 disk->private_data = mddev;
4556 disk->queue = mddev->queue;
4557 blk_queue_flush(mddev->queue, REQ_FLUSH | REQ_FUA);
4558 /* Allow extended partitions. This makes the
4559 * 'mdp' device redundant, but we can't really
4560 * remove it now.
4562 disk->flags |= GENHD_FL_EXT_DEVT;
4563 mddev->gendisk = disk;
4564 /* As soon as we call add_disk(), another thread could get
4565 * through to md_open, so make sure it doesn't get too far
4567 mutex_lock(&mddev->open_mutex);
4568 add_disk(disk);
4570 error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4571 &disk_to_dev(disk)->kobj, "%s", "md");
4572 if (error) {
4573 /* This isn't possible, but as kobject_init_and_add is marked
4574 * __must_check, we must do something with the result
4576 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4577 disk->disk_name);
4578 error = 0;
4580 if (mddev->kobj.sd &&
4581 sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4582 printk(KERN_DEBUG "pointless warning\n");
4583 mutex_unlock(&mddev->open_mutex);
4584 abort:
4585 mutex_unlock(&disks_mutex);
4586 if (!error && mddev->kobj.sd) {
4587 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4588 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4590 mddev_put(mddev);
4591 return error;
4594 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4596 md_alloc(dev, NULL);
4597 return NULL;
4600 static int add_named_array(const char *val, struct kernel_param *kp)
4602 /* val must be "md_*" where * is not all digits.
4603 * We allocate an array with a large free minor number, and
4604 * set the name to val. val must not already be an active name.
4606 int len = strlen(val);
4607 char buf[DISK_NAME_LEN];
4609 while (len && val[len-1] == '\n')
4610 len--;
4611 if (len >= DISK_NAME_LEN)
4612 return -E2BIG;
4613 strlcpy(buf, val, len+1);
4614 if (strncmp(buf, "md_", 3) != 0)
4615 return -EINVAL;
4616 return md_alloc(0, buf);
4619 static void md_safemode_timeout(unsigned long data)
4621 mddev_t *mddev = (mddev_t *) data;
4623 if (!atomic_read(&mddev->writes_pending)) {
4624 mddev->safemode = 1;
4625 if (mddev->external)
4626 sysfs_notify_dirent_safe(mddev->sysfs_state);
4628 md_wakeup_thread(mddev->thread);
4631 static int start_dirty_degraded;
4633 int md_run(mddev_t *mddev)
4635 int err;
4636 mdk_rdev_t *rdev;
4637 struct mdk_personality *pers;
4639 if (list_empty(&mddev->disks))
4640 /* cannot run an array with no devices.. */
4641 return -EINVAL;
4643 if (mddev->pers)
4644 return -EBUSY;
4645 /* Cannot run until previous stop completes properly */
4646 if (mddev->sysfs_active)
4647 return -EBUSY;
4650 * Analyze all RAID superblock(s)
4652 if (!mddev->raid_disks) {
4653 if (!mddev->persistent)
4654 return -EINVAL;
4655 analyze_sbs(mddev);
4658 if (mddev->level != LEVEL_NONE)
4659 request_module("md-level-%d", mddev->level);
4660 else if (mddev->clevel[0])
4661 request_module("md-%s", mddev->clevel);
4664 * Drop all container device buffers, from now on
4665 * the only valid external interface is through the md
4666 * device.
4668 list_for_each_entry(rdev, &mddev->disks, same_set) {
4669 if (test_bit(Faulty, &rdev->flags))
4670 continue;
4671 sync_blockdev(rdev->bdev);
4672 invalidate_bdev(rdev->bdev);
4674 /* perform some consistency tests on the device.
4675 * We don't want the data to overlap the metadata,
4676 * Internal Bitmap issues have been handled elsewhere.
4678 if (rdev->meta_bdev) {
4679 /* Nothing to check */;
4680 } else if (rdev->data_offset < rdev->sb_start) {
4681 if (mddev->dev_sectors &&
4682 rdev->data_offset + mddev->dev_sectors
4683 > rdev->sb_start) {
4684 printk("md: %s: data overlaps metadata\n",
4685 mdname(mddev));
4686 return -EINVAL;
4688 } else {
4689 if (rdev->sb_start + rdev->sb_size/512
4690 > rdev->data_offset) {
4691 printk("md: %s: metadata overlaps data\n",
4692 mdname(mddev));
4693 return -EINVAL;
4696 sysfs_notify_dirent_safe(rdev->sysfs_state);
4699 if (mddev->bio_set == NULL)
4700 mddev->bio_set = bioset_create(BIO_POOL_SIZE,
4701 sizeof(mddev_t *));
4703 spin_lock(&pers_lock);
4704 pers = find_pers(mddev->level, mddev->clevel);
4705 if (!pers || !try_module_get(pers->owner)) {
4706 spin_unlock(&pers_lock);
4707 if (mddev->level != LEVEL_NONE)
4708 printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
4709 mddev->level);
4710 else
4711 printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
4712 mddev->clevel);
4713 return -EINVAL;
4715 mddev->pers = pers;
4716 spin_unlock(&pers_lock);
4717 if (mddev->level != pers->level) {
4718 mddev->level = pers->level;
4719 mddev->new_level = pers->level;
4721 strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
4723 if (mddev->reshape_position != MaxSector &&
4724 pers->start_reshape == NULL) {
4725 /* This personality cannot handle reshaping... */
4726 mddev->pers = NULL;
4727 module_put(pers->owner);
4728 return -EINVAL;
4731 if (pers->sync_request) {
4732 /* Warn if this is a potentially silly
4733 * configuration.
4735 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4736 mdk_rdev_t *rdev2;
4737 int warned = 0;
4739 list_for_each_entry(rdev, &mddev->disks, same_set)
4740 list_for_each_entry(rdev2, &mddev->disks, same_set) {
4741 if (rdev < rdev2 &&
4742 rdev->bdev->bd_contains ==
4743 rdev2->bdev->bd_contains) {
4744 printk(KERN_WARNING
4745 "%s: WARNING: %s appears to be"
4746 " on the same physical disk as"
4747 " %s.\n",
4748 mdname(mddev),
4749 bdevname(rdev->bdev,b),
4750 bdevname(rdev2->bdev,b2));
4751 warned = 1;
4755 if (warned)
4756 printk(KERN_WARNING
4757 "True protection against single-disk"
4758 " failure might be compromised.\n");
4761 mddev->recovery = 0;
4762 /* may be over-ridden by personality */
4763 mddev->resync_max_sectors = mddev->dev_sectors;
4765 mddev->ok_start_degraded = start_dirty_degraded;
4767 if (start_readonly && mddev->ro == 0)
4768 mddev->ro = 2; /* read-only, but switch on first write */
4770 err = mddev->pers->run(mddev);
4771 if (err)
4772 printk(KERN_ERR "md: pers->run() failed ...\n");
4773 else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
4774 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
4775 " but 'external_size' not in effect?\n", __func__);
4776 printk(KERN_ERR
4777 "md: invalid array_size %llu > default size %llu\n",
4778 (unsigned long long)mddev->array_sectors / 2,
4779 (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
4780 err = -EINVAL;
4781 mddev->pers->stop(mddev);
4783 if (err == 0 && mddev->pers->sync_request) {
4784 err = bitmap_create(mddev);
4785 if (err) {
4786 printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
4787 mdname(mddev), err);
4788 mddev->pers->stop(mddev);
4791 if (err) {
4792 module_put(mddev->pers->owner);
4793 mddev->pers = NULL;
4794 bitmap_destroy(mddev);
4795 return err;
4797 if (mddev->pers->sync_request) {
4798 if (mddev->kobj.sd &&
4799 sysfs_create_group(&mddev->kobj, &md_redundancy_group))
4800 printk(KERN_WARNING
4801 "md: cannot register extra attributes for %s\n",
4802 mdname(mddev));
4803 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
4804 } else if (mddev->ro == 2) /* auto-readonly not meaningful */
4805 mddev->ro = 0;
4807 atomic_set(&mddev->writes_pending,0);
4808 atomic_set(&mddev->max_corr_read_errors,
4809 MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
4810 mddev->safemode = 0;
4811 mddev->safemode_timer.function = md_safemode_timeout;
4812 mddev->safemode_timer.data = (unsigned long) mddev;
4813 mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
4814 mddev->in_sync = 1;
4815 smp_wmb();
4816 mddev->ready = 1;
4817 list_for_each_entry(rdev, &mddev->disks, same_set)
4818 if (rdev->raid_disk >= 0)
4819 if (sysfs_link_rdev(mddev, rdev))
4820 /* failure here is OK */;
4822 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4824 if (mddev->flags)
4825 md_update_sb(mddev, 0);
4827 md_new_event(mddev);
4828 sysfs_notify_dirent_safe(mddev->sysfs_state);
4829 sysfs_notify_dirent_safe(mddev->sysfs_action);
4830 sysfs_notify(&mddev->kobj, NULL, "degraded");
4831 return 0;
4833 EXPORT_SYMBOL_GPL(md_run);
4835 static int do_md_run(mddev_t *mddev)
4837 int err;
4839 err = md_run(mddev);
4840 if (err)
4841 goto out;
4842 err = bitmap_load(mddev);
4843 if (err) {
4844 bitmap_destroy(mddev);
4845 goto out;
4848 md_wakeup_thread(mddev->thread);
4849 md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
4851 set_capacity(mddev->gendisk, mddev->array_sectors);
4852 revalidate_disk(mddev->gendisk);
4853 mddev->changed = 1;
4854 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4855 out:
4856 return err;
4859 static int restart_array(mddev_t *mddev)
4861 struct gendisk *disk = mddev->gendisk;
4863 /* Complain if it has no devices */
4864 if (list_empty(&mddev->disks))
4865 return -ENXIO;
4866 if (!mddev->pers)
4867 return -EINVAL;
4868 if (!mddev->ro)
4869 return -EBUSY;
4870 mddev->safemode = 0;
4871 mddev->ro = 0;
4872 set_disk_ro(disk, 0);
4873 printk(KERN_INFO "md: %s switched to read-write mode.\n",
4874 mdname(mddev));
4875 /* Kick recovery or resync if necessary */
4876 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4877 md_wakeup_thread(mddev->thread);
4878 md_wakeup_thread(mddev->sync_thread);
4879 sysfs_notify_dirent_safe(mddev->sysfs_state);
4880 return 0;
4883 /* similar to deny_write_access, but accounts for our holding a reference
4884 * to the file ourselves */
4885 static int deny_bitmap_write_access(struct file * file)
4887 struct inode *inode = file->f_mapping->host;
4889 spin_lock(&inode->i_lock);
4890 if (atomic_read(&inode->i_writecount) > 1) {
4891 spin_unlock(&inode->i_lock);
4892 return -ETXTBSY;
4894 atomic_set(&inode->i_writecount, -1);
4895 spin_unlock(&inode->i_lock);
4897 return 0;
4900 void restore_bitmap_write_access(struct file *file)
4902 struct inode *inode = file->f_mapping->host;
4904 spin_lock(&inode->i_lock);
4905 atomic_set(&inode->i_writecount, 1);
4906 spin_unlock(&inode->i_lock);
4909 static void md_clean(mddev_t *mddev)
4911 mddev->array_sectors = 0;
4912 mddev->external_size = 0;
4913 mddev->dev_sectors = 0;
4914 mddev->raid_disks = 0;
4915 mddev->recovery_cp = 0;
4916 mddev->resync_min = 0;
4917 mddev->resync_max = MaxSector;
4918 mddev->reshape_position = MaxSector;
4919 mddev->external = 0;
4920 mddev->persistent = 0;
4921 mddev->level = LEVEL_NONE;
4922 mddev->clevel[0] = 0;
4923 mddev->flags = 0;
4924 mddev->ro = 0;
4925 mddev->metadata_type[0] = 0;
4926 mddev->chunk_sectors = 0;
4927 mddev->ctime = mddev->utime = 0;
4928 mddev->layout = 0;
4929 mddev->max_disks = 0;
4930 mddev->events = 0;
4931 mddev->can_decrease_events = 0;
4932 mddev->delta_disks = 0;
4933 mddev->new_level = LEVEL_NONE;
4934 mddev->new_layout = 0;
4935 mddev->new_chunk_sectors = 0;
4936 mddev->curr_resync = 0;
4937 mddev->resync_mismatches = 0;
4938 mddev->suspend_lo = mddev->suspend_hi = 0;
4939 mddev->sync_speed_min = mddev->sync_speed_max = 0;
4940 mddev->recovery = 0;
4941 mddev->in_sync = 0;
4942 mddev->changed = 0;
4943 mddev->degraded = 0;
4944 mddev->safemode = 0;
4945 mddev->bitmap_info.offset = 0;
4946 mddev->bitmap_info.default_offset = 0;
4947 mddev->bitmap_info.chunksize = 0;
4948 mddev->bitmap_info.daemon_sleep = 0;
4949 mddev->bitmap_info.max_write_behind = 0;
4952 static void __md_stop_writes(mddev_t *mddev)
4954 if (mddev->sync_thread) {
4955 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4956 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4957 reap_sync_thread(mddev);
4960 del_timer_sync(&mddev->safemode_timer);
4962 bitmap_flush(mddev);
4963 md_super_wait(mddev);
4965 if (!mddev->in_sync || mddev->flags) {
4966 /* mark array as shutdown cleanly */
4967 mddev->in_sync = 1;
4968 md_update_sb(mddev, 1);
4972 void md_stop_writes(mddev_t *mddev)
4974 mddev_lock(mddev);
4975 __md_stop_writes(mddev);
4976 mddev_unlock(mddev);
4978 EXPORT_SYMBOL_GPL(md_stop_writes);
4980 void md_stop(mddev_t *mddev)
4982 mddev->ready = 0;
4983 mddev->pers->stop(mddev);
4984 if (mddev->pers->sync_request && mddev->to_remove == NULL)
4985 mddev->to_remove = &md_redundancy_group;
4986 module_put(mddev->pers->owner);
4987 mddev->pers = NULL;
4988 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4990 EXPORT_SYMBOL_GPL(md_stop);
4992 static int md_set_readonly(mddev_t *mddev, int is_open)
4994 int err = 0;
4995 mutex_lock(&mddev->open_mutex);
4996 if (atomic_read(&mddev->openers) > is_open) {
4997 printk("md: %s still in use.\n",mdname(mddev));
4998 err = -EBUSY;
4999 goto out;
5001 if (mddev->pers) {
5002 __md_stop_writes(mddev);
5004 err = -ENXIO;
5005 if (mddev->ro==1)
5006 goto out;
5007 mddev->ro = 1;
5008 set_disk_ro(mddev->gendisk, 1);
5009 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
5010 sysfs_notify_dirent_safe(mddev->sysfs_state);
5011 err = 0;
5013 out:
5014 mutex_unlock(&mddev->open_mutex);
5015 return err;
5018 /* mode:
5019 * 0 - completely stop and dis-assemble array
5020 * 2 - stop but do not disassemble array
5022 static int do_md_stop(mddev_t * mddev, int mode, int is_open)
5024 struct gendisk *disk = mddev->gendisk;
5025 mdk_rdev_t *rdev;
5027 mutex_lock(&mddev->open_mutex);
5028 if (atomic_read(&mddev->openers) > is_open ||
5029 mddev->sysfs_active) {
5030 printk("md: %s still in use.\n",mdname(mddev));
5031 mutex_unlock(&mddev->open_mutex);
5032 return -EBUSY;
5035 if (mddev->pers) {
5036 if (mddev->ro)
5037 set_disk_ro(disk, 0);
5039 __md_stop_writes(mddev);
5040 md_stop(mddev);
5041 mddev->queue->merge_bvec_fn = NULL;
5042 mddev->queue->backing_dev_info.congested_fn = NULL;
5044 /* tell userspace to handle 'inactive' */
5045 sysfs_notify_dirent_safe(mddev->sysfs_state);
5047 list_for_each_entry(rdev, &mddev->disks, same_set)
5048 if (rdev->raid_disk >= 0)
5049 sysfs_unlink_rdev(mddev, rdev);
5051 set_capacity(disk, 0);
5052 mutex_unlock(&mddev->open_mutex);
5053 mddev->changed = 1;
5054 revalidate_disk(disk);
5056 if (mddev->ro)
5057 mddev->ro = 0;
5058 } else
5059 mutex_unlock(&mddev->open_mutex);
5061 * Free resources if final stop
5063 if (mode == 0) {
5064 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
5066 bitmap_destroy(mddev);
5067 if (mddev->bitmap_info.file) {
5068 restore_bitmap_write_access(mddev->bitmap_info.file);
5069 fput(mddev->bitmap_info.file);
5070 mddev->bitmap_info.file = NULL;
5072 mddev->bitmap_info.offset = 0;
5074 export_array(mddev);
5076 md_clean(mddev);
5077 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
5078 if (mddev->hold_active == UNTIL_STOP)
5079 mddev->hold_active = 0;
5081 blk_integrity_unregister(disk);
5082 md_new_event(mddev);
5083 sysfs_notify_dirent_safe(mddev->sysfs_state);
5084 return 0;
5087 #ifndef MODULE
5088 static void autorun_array(mddev_t *mddev)
5090 mdk_rdev_t *rdev;
5091 int err;
5093 if (list_empty(&mddev->disks))
5094 return;
5096 printk(KERN_INFO "md: running: ");
5098 list_for_each_entry(rdev, &mddev->disks, same_set) {
5099 char b[BDEVNAME_SIZE];
5100 printk("<%s>", bdevname(rdev->bdev,b));
5102 printk("\n");
5104 err = do_md_run(mddev);
5105 if (err) {
5106 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
5107 do_md_stop(mddev, 0, 0);
5112 * lets try to run arrays based on all disks that have arrived
5113 * until now. (those are in pending_raid_disks)
5115 * the method: pick the first pending disk, collect all disks with
5116 * the same UUID, remove all from the pending list and put them into
5117 * the 'same_array' list. Then order this list based on superblock
5118 * update time (freshest comes first), kick out 'old' disks and
5119 * compare superblocks. If everything's fine then run it.
5121 * If "unit" is allocated, then bump its reference count
5123 static void autorun_devices(int part)
5125 mdk_rdev_t *rdev0, *rdev, *tmp;
5126 mddev_t *mddev;
5127 char b[BDEVNAME_SIZE];
5129 printk(KERN_INFO "md: autorun ...\n");
5130 while (!list_empty(&pending_raid_disks)) {
5131 int unit;
5132 dev_t dev;
5133 LIST_HEAD(candidates);
5134 rdev0 = list_entry(pending_raid_disks.next,
5135 mdk_rdev_t, same_set);
5137 printk(KERN_INFO "md: considering %s ...\n",
5138 bdevname(rdev0->bdev,b));
5139 INIT_LIST_HEAD(&candidates);
5140 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
5141 if (super_90_load(rdev, rdev0, 0) >= 0) {
5142 printk(KERN_INFO "md: adding %s ...\n",
5143 bdevname(rdev->bdev,b));
5144 list_move(&rdev->same_set, &candidates);
5147 * now we have a set of devices, with all of them having
5148 * mostly sane superblocks. It's time to allocate the
5149 * mddev.
5151 if (part) {
5152 dev = MKDEV(mdp_major,
5153 rdev0->preferred_minor << MdpMinorShift);
5154 unit = MINOR(dev) >> MdpMinorShift;
5155 } else {
5156 dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
5157 unit = MINOR(dev);
5159 if (rdev0->preferred_minor != unit) {
5160 printk(KERN_INFO "md: unit number in %s is bad: %d\n",
5161 bdevname(rdev0->bdev, b), rdev0->preferred_minor);
5162 break;
5165 md_probe(dev, NULL, NULL);
5166 mddev = mddev_find(dev);
5167 if (!mddev || !mddev->gendisk) {
5168 if (mddev)
5169 mddev_put(mddev);
5170 printk(KERN_ERR
5171 "md: cannot allocate memory for md drive.\n");
5172 break;
5174 if (mddev_lock(mddev))
5175 printk(KERN_WARNING "md: %s locked, cannot run\n",
5176 mdname(mddev));
5177 else if (mddev->raid_disks || mddev->major_version
5178 || !list_empty(&mddev->disks)) {
5179 printk(KERN_WARNING
5180 "md: %s already running, cannot run %s\n",
5181 mdname(mddev), bdevname(rdev0->bdev,b));
5182 mddev_unlock(mddev);
5183 } else {
5184 printk(KERN_INFO "md: created %s\n", mdname(mddev));
5185 mddev->persistent = 1;
5186 rdev_for_each_list(rdev, tmp, &candidates) {
5187 list_del_init(&rdev->same_set);
5188 if (bind_rdev_to_array(rdev, mddev))
5189 export_rdev(rdev);
5191 autorun_array(mddev);
5192 mddev_unlock(mddev);
5194 /* on success, candidates will be empty, on error
5195 * it won't...
5197 rdev_for_each_list(rdev, tmp, &candidates) {
5198 list_del_init(&rdev->same_set);
5199 export_rdev(rdev);
5201 mddev_put(mddev);
5203 printk(KERN_INFO "md: ... autorun DONE.\n");
5205 #endif /* !MODULE */
5207 static int get_version(void __user * arg)
5209 mdu_version_t ver;
5211 ver.major = MD_MAJOR_VERSION;
5212 ver.minor = MD_MINOR_VERSION;
5213 ver.patchlevel = MD_PATCHLEVEL_VERSION;
5215 if (copy_to_user(arg, &ver, sizeof(ver)))
5216 return -EFAULT;
5218 return 0;
5221 static int get_array_info(mddev_t * mddev, void __user * arg)
5223 mdu_array_info_t info;
5224 int nr,working,insync,failed,spare;
5225 mdk_rdev_t *rdev;
5227 nr=working=insync=failed=spare=0;
5228 list_for_each_entry(rdev, &mddev->disks, same_set) {
5229 nr++;
5230 if (test_bit(Faulty, &rdev->flags))
5231 failed++;
5232 else {
5233 working++;
5234 if (test_bit(In_sync, &rdev->flags))
5235 insync++;
5236 else
5237 spare++;
5241 info.major_version = mddev->major_version;
5242 info.minor_version = mddev->minor_version;
5243 info.patch_version = MD_PATCHLEVEL_VERSION;
5244 info.ctime = mddev->ctime;
5245 info.level = mddev->level;
5246 info.size = mddev->dev_sectors / 2;
5247 if (info.size != mddev->dev_sectors / 2) /* overflow */
5248 info.size = -1;
5249 info.nr_disks = nr;
5250 info.raid_disks = mddev->raid_disks;
5251 info.md_minor = mddev->md_minor;
5252 info.not_persistent= !mddev->persistent;
5254 info.utime = mddev->utime;
5255 info.state = 0;
5256 if (mddev->in_sync)
5257 info.state = (1<<MD_SB_CLEAN);
5258 if (mddev->bitmap && mddev->bitmap_info.offset)
5259 info.state = (1<<MD_SB_BITMAP_PRESENT);
5260 info.active_disks = insync;
5261 info.working_disks = working;
5262 info.failed_disks = failed;
5263 info.spare_disks = spare;
5265 info.layout = mddev->layout;
5266 info.chunk_size = mddev->chunk_sectors << 9;
5268 if (copy_to_user(arg, &info, sizeof(info)))
5269 return -EFAULT;
5271 return 0;
5274 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
5276 mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5277 char *ptr, *buf = NULL;
5278 int err = -ENOMEM;
5280 if (md_allow_write(mddev))
5281 file = kmalloc(sizeof(*file), GFP_NOIO);
5282 else
5283 file = kmalloc(sizeof(*file), GFP_KERNEL);
5285 if (!file)
5286 goto out;
5288 /* bitmap disabled, zero the first byte and copy out */
5289 if (!mddev->bitmap || !mddev->bitmap->file) {
5290 file->pathname[0] = '\0';
5291 goto copy_out;
5294 buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
5295 if (!buf)
5296 goto out;
5298 ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
5299 if (IS_ERR(ptr))
5300 goto out;
5302 strcpy(file->pathname, ptr);
5304 copy_out:
5305 err = 0;
5306 if (copy_to_user(arg, file, sizeof(*file)))
5307 err = -EFAULT;
5308 out:
5309 kfree(buf);
5310 kfree(file);
5311 return err;
5314 static int get_disk_info(mddev_t * mddev, void __user * arg)
5316 mdu_disk_info_t info;
5317 mdk_rdev_t *rdev;
5319 if (copy_from_user(&info, arg, sizeof(info)))
5320 return -EFAULT;
5322 rdev = find_rdev_nr(mddev, info.number);
5323 if (rdev) {
5324 info.major = MAJOR(rdev->bdev->bd_dev);
5325 info.minor = MINOR(rdev->bdev->bd_dev);
5326 info.raid_disk = rdev->raid_disk;
5327 info.state = 0;
5328 if (test_bit(Faulty, &rdev->flags))
5329 info.state |= (1<<MD_DISK_FAULTY);
5330 else if (test_bit(In_sync, &rdev->flags)) {
5331 info.state |= (1<<MD_DISK_ACTIVE);
5332 info.state |= (1<<MD_DISK_SYNC);
5334 if (test_bit(WriteMostly, &rdev->flags))
5335 info.state |= (1<<MD_DISK_WRITEMOSTLY);
5336 } else {
5337 info.major = info.minor = 0;
5338 info.raid_disk = -1;
5339 info.state = (1<<MD_DISK_REMOVED);
5342 if (copy_to_user(arg, &info, sizeof(info)))
5343 return -EFAULT;
5345 return 0;
5348 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
5350 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5351 mdk_rdev_t *rdev;
5352 dev_t dev = MKDEV(info->major,info->minor);
5354 if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5355 return -EOVERFLOW;
5357 if (!mddev->raid_disks) {
5358 int err;
5359 /* expecting a device which has a superblock */
5360 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5361 if (IS_ERR(rdev)) {
5362 printk(KERN_WARNING
5363 "md: md_import_device returned %ld\n",
5364 PTR_ERR(rdev));
5365 return PTR_ERR(rdev);
5367 if (!list_empty(&mddev->disks)) {
5368 mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
5369 mdk_rdev_t, same_set);
5370 err = super_types[mddev->major_version]
5371 .load_super(rdev, rdev0, mddev->minor_version);
5372 if (err < 0) {
5373 printk(KERN_WARNING
5374 "md: %s has different UUID to %s\n",
5375 bdevname(rdev->bdev,b),
5376 bdevname(rdev0->bdev,b2));
5377 export_rdev(rdev);
5378 return -EINVAL;
5381 err = bind_rdev_to_array(rdev, mddev);
5382 if (err)
5383 export_rdev(rdev);
5384 return err;
5388 * add_new_disk can be used once the array is assembled
5389 * to add "hot spares". They must already have a superblock
5390 * written
5392 if (mddev->pers) {
5393 int err;
5394 if (!mddev->pers->hot_add_disk) {
5395 printk(KERN_WARNING
5396 "%s: personality does not support diskops!\n",
5397 mdname(mddev));
5398 return -EINVAL;
5400 if (mddev->persistent)
5401 rdev = md_import_device(dev, mddev->major_version,
5402 mddev->minor_version);
5403 else
5404 rdev = md_import_device(dev, -1, -1);
5405 if (IS_ERR(rdev)) {
5406 printk(KERN_WARNING
5407 "md: md_import_device returned %ld\n",
5408 PTR_ERR(rdev));
5409 return PTR_ERR(rdev);
5411 /* set saved_raid_disk if appropriate */
5412 if (!mddev->persistent) {
5413 if (info->state & (1<<MD_DISK_SYNC) &&
5414 info->raid_disk < mddev->raid_disks) {
5415 rdev->raid_disk = info->raid_disk;
5416 set_bit(In_sync, &rdev->flags);
5417 } else
5418 rdev->raid_disk = -1;
5419 } else
5420 super_types[mddev->major_version].
5421 validate_super(mddev, rdev);
5422 if ((info->state & (1<<MD_DISK_SYNC)) &&
5423 (!test_bit(In_sync, &rdev->flags) ||
5424 rdev->raid_disk != info->raid_disk)) {
5425 /* This was a hot-add request, but events doesn't
5426 * match, so reject it.
5428 export_rdev(rdev);
5429 return -EINVAL;
5432 if (test_bit(In_sync, &rdev->flags))
5433 rdev->saved_raid_disk = rdev->raid_disk;
5434 else
5435 rdev->saved_raid_disk = -1;
5437 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5438 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5439 set_bit(WriteMostly, &rdev->flags);
5440 else
5441 clear_bit(WriteMostly, &rdev->flags);
5443 rdev->raid_disk = -1;
5444 err = bind_rdev_to_array(rdev, mddev);
5445 if (!err && !mddev->pers->hot_remove_disk) {
5446 /* If there is hot_add_disk but no hot_remove_disk
5447 * then added disks for geometry changes,
5448 * and should be added immediately.
5450 super_types[mddev->major_version].
5451 validate_super(mddev, rdev);
5452 err = mddev->pers->hot_add_disk(mddev, rdev);
5453 if (err)
5454 unbind_rdev_from_array(rdev);
5456 if (err)
5457 export_rdev(rdev);
5458 else
5459 sysfs_notify_dirent_safe(rdev->sysfs_state);
5461 md_update_sb(mddev, 1);
5462 if (mddev->degraded)
5463 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5464 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5465 if (!err)
5466 md_new_event(mddev);
5467 md_wakeup_thread(mddev->thread);
5468 return err;
5471 /* otherwise, add_new_disk is only allowed
5472 * for major_version==0 superblocks
5474 if (mddev->major_version != 0) {
5475 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5476 mdname(mddev));
5477 return -EINVAL;
5480 if (!(info->state & (1<<MD_DISK_FAULTY))) {
5481 int err;
5482 rdev = md_import_device(dev, -1, 0);
5483 if (IS_ERR(rdev)) {
5484 printk(KERN_WARNING
5485 "md: error, md_import_device() returned %ld\n",
5486 PTR_ERR(rdev));
5487 return PTR_ERR(rdev);
5489 rdev->desc_nr = info->number;
5490 if (info->raid_disk < mddev->raid_disks)
5491 rdev->raid_disk = info->raid_disk;
5492 else
5493 rdev->raid_disk = -1;
5495 if (rdev->raid_disk < mddev->raid_disks)
5496 if (info->state & (1<<MD_DISK_SYNC))
5497 set_bit(In_sync, &rdev->flags);
5499 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5500 set_bit(WriteMostly, &rdev->flags);
5502 if (!mddev->persistent) {
5503 printk(KERN_INFO "md: nonpersistent superblock ...\n");
5504 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5505 } else
5506 rdev->sb_start = calc_dev_sboffset(rdev);
5507 rdev->sectors = rdev->sb_start;
5509 err = bind_rdev_to_array(rdev, mddev);
5510 if (err) {
5511 export_rdev(rdev);
5512 return err;
5516 return 0;
5519 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
5521 char b[BDEVNAME_SIZE];
5522 mdk_rdev_t *rdev;
5524 rdev = find_rdev(mddev, dev);
5525 if (!rdev)
5526 return -ENXIO;
5528 if (rdev->raid_disk >= 0)
5529 goto busy;
5531 kick_rdev_from_array(rdev);
5532 md_update_sb(mddev, 1);
5533 md_new_event(mddev);
5535 return 0;
5536 busy:
5537 printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
5538 bdevname(rdev->bdev,b), mdname(mddev));
5539 return -EBUSY;
5542 static int hot_add_disk(mddev_t * mddev, dev_t dev)
5544 char b[BDEVNAME_SIZE];
5545 int err;
5546 mdk_rdev_t *rdev;
5548 if (!mddev->pers)
5549 return -ENODEV;
5551 if (mddev->major_version != 0) {
5552 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
5553 " version-0 superblocks.\n",
5554 mdname(mddev));
5555 return -EINVAL;
5557 if (!mddev->pers->hot_add_disk) {
5558 printk(KERN_WARNING
5559 "%s: personality does not support diskops!\n",
5560 mdname(mddev));
5561 return -EINVAL;
5564 rdev = md_import_device(dev, -1, 0);
5565 if (IS_ERR(rdev)) {
5566 printk(KERN_WARNING
5567 "md: error, md_import_device() returned %ld\n",
5568 PTR_ERR(rdev));
5569 return -EINVAL;
5572 if (mddev->persistent)
5573 rdev->sb_start = calc_dev_sboffset(rdev);
5574 else
5575 rdev->sb_start = i_size_read(rdev->bdev->bd_inode) / 512;
5577 rdev->sectors = rdev->sb_start;
5579 if (test_bit(Faulty, &rdev->flags)) {
5580 printk(KERN_WARNING
5581 "md: can not hot-add faulty %s disk to %s!\n",
5582 bdevname(rdev->bdev,b), mdname(mddev));
5583 err = -EINVAL;
5584 goto abort_export;
5586 clear_bit(In_sync, &rdev->flags);
5587 rdev->desc_nr = -1;
5588 rdev->saved_raid_disk = -1;
5589 err = bind_rdev_to_array(rdev, mddev);
5590 if (err)
5591 goto abort_export;
5594 * The rest should better be atomic, we can have disk failures
5595 * noticed in interrupt contexts ...
5598 rdev->raid_disk = -1;
5600 md_update_sb(mddev, 1);
5603 * Kick recovery, maybe this spare has to be added to the
5604 * array immediately.
5606 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5607 md_wakeup_thread(mddev->thread);
5608 md_new_event(mddev);
5609 return 0;
5611 abort_export:
5612 export_rdev(rdev);
5613 return err;
5616 static int set_bitmap_file(mddev_t *mddev, int fd)
5618 int err;
5620 if (mddev->pers) {
5621 if (!mddev->pers->quiesce)
5622 return -EBUSY;
5623 if (mddev->recovery || mddev->sync_thread)
5624 return -EBUSY;
5625 /* we should be able to change the bitmap.. */
5629 if (fd >= 0) {
5630 if (mddev->bitmap)
5631 return -EEXIST; /* cannot add when bitmap is present */
5632 mddev->bitmap_info.file = fget(fd);
5634 if (mddev->bitmap_info.file == NULL) {
5635 printk(KERN_ERR "%s: error: failed to get bitmap file\n",
5636 mdname(mddev));
5637 return -EBADF;
5640 err = deny_bitmap_write_access(mddev->bitmap_info.file);
5641 if (err) {
5642 printk(KERN_ERR "%s: error: bitmap file is already in use\n",
5643 mdname(mddev));
5644 fput(mddev->bitmap_info.file);
5645 mddev->bitmap_info.file = NULL;
5646 return err;
5648 mddev->bitmap_info.offset = 0; /* file overrides offset */
5649 } else if (mddev->bitmap == NULL)
5650 return -ENOENT; /* cannot remove what isn't there */
5651 err = 0;
5652 if (mddev->pers) {
5653 mddev->pers->quiesce(mddev, 1);
5654 if (fd >= 0) {
5655 err = bitmap_create(mddev);
5656 if (!err)
5657 err = bitmap_load(mddev);
5659 if (fd < 0 || err) {
5660 bitmap_destroy(mddev);
5661 fd = -1; /* make sure to put the file */
5663 mddev->pers->quiesce(mddev, 0);
5665 if (fd < 0) {
5666 if (mddev->bitmap_info.file) {
5667 restore_bitmap_write_access(mddev->bitmap_info.file);
5668 fput(mddev->bitmap_info.file);
5670 mddev->bitmap_info.file = NULL;
5673 return err;
5677 * set_array_info is used two different ways
5678 * The original usage is when creating a new array.
5679 * In this usage, raid_disks is > 0 and it together with
5680 * level, size, not_persistent,layout,chunksize determine the
5681 * shape of the array.
5682 * This will always create an array with a type-0.90.0 superblock.
5683 * The newer usage is when assembling an array.
5684 * In this case raid_disks will be 0, and the major_version field is
5685 * use to determine which style super-blocks are to be found on the devices.
5686 * The minor and patch _version numbers are also kept incase the
5687 * super_block handler wishes to interpret them.
5689 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
5692 if (info->raid_disks == 0) {
5693 /* just setting version number for superblock loading */
5694 if (info->major_version < 0 ||
5695 info->major_version >= ARRAY_SIZE(super_types) ||
5696 super_types[info->major_version].name == NULL) {
5697 /* maybe try to auto-load a module? */
5698 printk(KERN_INFO
5699 "md: superblock version %d not known\n",
5700 info->major_version);
5701 return -EINVAL;
5703 mddev->major_version = info->major_version;
5704 mddev->minor_version = info->minor_version;
5705 mddev->patch_version = info->patch_version;
5706 mddev->persistent = !info->not_persistent;
5707 /* ensure mddev_put doesn't delete this now that there
5708 * is some minimal configuration.
5710 mddev->ctime = get_seconds();
5711 return 0;
5713 mddev->major_version = MD_MAJOR_VERSION;
5714 mddev->minor_version = MD_MINOR_VERSION;
5715 mddev->patch_version = MD_PATCHLEVEL_VERSION;
5716 mddev->ctime = get_seconds();
5718 mddev->level = info->level;
5719 mddev->clevel[0] = 0;
5720 mddev->dev_sectors = 2 * (sector_t)info->size;
5721 mddev->raid_disks = info->raid_disks;
5722 /* don't set md_minor, it is determined by which /dev/md* was
5723 * openned
5725 if (info->state & (1<<MD_SB_CLEAN))
5726 mddev->recovery_cp = MaxSector;
5727 else
5728 mddev->recovery_cp = 0;
5729 mddev->persistent = ! info->not_persistent;
5730 mddev->external = 0;
5732 mddev->layout = info->layout;
5733 mddev->chunk_sectors = info->chunk_size >> 9;
5735 mddev->max_disks = MD_SB_DISKS;
5737 if (mddev->persistent)
5738 mddev->flags = 0;
5739 set_bit(MD_CHANGE_DEVS, &mddev->flags);
5741 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
5742 mddev->bitmap_info.offset = 0;
5744 mddev->reshape_position = MaxSector;
5747 * Generate a 128 bit UUID
5749 get_random_bytes(mddev->uuid, 16);
5751 mddev->new_level = mddev->level;
5752 mddev->new_chunk_sectors = mddev->chunk_sectors;
5753 mddev->new_layout = mddev->layout;
5754 mddev->delta_disks = 0;
5756 return 0;
5759 void md_set_array_sectors(mddev_t *mddev, sector_t array_sectors)
5761 WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
5763 if (mddev->external_size)
5764 return;
5766 mddev->array_sectors = array_sectors;
5768 EXPORT_SYMBOL(md_set_array_sectors);
5770 static int update_size(mddev_t *mddev, sector_t num_sectors)
5772 mdk_rdev_t *rdev;
5773 int rv;
5774 int fit = (num_sectors == 0);
5776 if (mddev->pers->resize == NULL)
5777 return -EINVAL;
5778 /* The "num_sectors" is the number of sectors of each device that
5779 * is used. This can only make sense for arrays with redundancy.
5780 * linear and raid0 always use whatever space is available. We can only
5781 * consider changing this number if no resync or reconstruction is
5782 * happening, and if the new size is acceptable. It must fit before the
5783 * sb_start or, if that is <data_offset, it must fit before the size
5784 * of each device. If num_sectors is zero, we find the largest size
5785 * that fits.
5787 if (mddev->sync_thread)
5788 return -EBUSY;
5789 if (mddev->bitmap)
5790 /* Sorry, cannot grow a bitmap yet, just remove it,
5791 * grow, and re-add.
5793 return -EBUSY;
5794 list_for_each_entry(rdev, &mddev->disks, same_set) {
5795 sector_t avail = rdev->sectors;
5797 if (fit && (num_sectors == 0 || num_sectors > avail))
5798 num_sectors = avail;
5799 if (avail < num_sectors)
5800 return -ENOSPC;
5802 rv = mddev->pers->resize(mddev, num_sectors);
5803 if (!rv)
5804 revalidate_disk(mddev->gendisk);
5805 return rv;
5808 static int update_raid_disks(mddev_t *mddev, int raid_disks)
5810 int rv;
5811 /* change the number of raid disks */
5812 if (mddev->pers->check_reshape == NULL)
5813 return -EINVAL;
5814 if (raid_disks <= 0 ||
5815 (mddev->max_disks && raid_disks >= mddev->max_disks))
5816 return -EINVAL;
5817 if (mddev->sync_thread || mddev->reshape_position != MaxSector)
5818 return -EBUSY;
5819 mddev->delta_disks = raid_disks - mddev->raid_disks;
5821 rv = mddev->pers->check_reshape(mddev);
5822 if (rv < 0)
5823 mddev->delta_disks = 0;
5824 return rv;
5829 * update_array_info is used to change the configuration of an
5830 * on-line array.
5831 * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
5832 * fields in the info are checked against the array.
5833 * Any differences that cannot be handled will cause an error.
5834 * Normally, only one change can be managed at a time.
5836 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
5838 int rv = 0;
5839 int cnt = 0;
5840 int state = 0;
5842 /* calculate expected state,ignoring low bits */
5843 if (mddev->bitmap && mddev->bitmap_info.offset)
5844 state |= (1 << MD_SB_BITMAP_PRESENT);
5846 if (mddev->major_version != info->major_version ||
5847 mddev->minor_version != info->minor_version ||
5848 /* mddev->patch_version != info->patch_version || */
5849 mddev->ctime != info->ctime ||
5850 mddev->level != info->level ||
5851 /* mddev->layout != info->layout || */
5852 !mddev->persistent != info->not_persistent||
5853 mddev->chunk_sectors != info->chunk_size >> 9 ||
5854 /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
5855 ((state^info->state) & 0xfffffe00)
5857 return -EINVAL;
5858 /* Check there is only one change */
5859 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5860 cnt++;
5861 if (mddev->raid_disks != info->raid_disks)
5862 cnt++;
5863 if (mddev->layout != info->layout)
5864 cnt++;
5865 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
5866 cnt++;
5867 if (cnt == 0)
5868 return 0;
5869 if (cnt > 1)
5870 return -EINVAL;
5872 if (mddev->layout != info->layout) {
5873 /* Change layout
5874 * we don't need to do anything at the md level, the
5875 * personality will take care of it all.
5877 if (mddev->pers->check_reshape == NULL)
5878 return -EINVAL;
5879 else {
5880 mddev->new_layout = info->layout;
5881 rv = mddev->pers->check_reshape(mddev);
5882 if (rv)
5883 mddev->new_layout = mddev->layout;
5884 return rv;
5887 if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5888 rv = update_size(mddev, (sector_t)info->size * 2);
5890 if (mddev->raid_disks != info->raid_disks)
5891 rv = update_raid_disks(mddev, info->raid_disks);
5893 if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
5894 if (mddev->pers->quiesce == NULL)
5895 return -EINVAL;
5896 if (mddev->recovery || mddev->sync_thread)
5897 return -EBUSY;
5898 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
5899 /* add the bitmap */
5900 if (mddev->bitmap)
5901 return -EEXIST;
5902 if (mddev->bitmap_info.default_offset == 0)
5903 return -EINVAL;
5904 mddev->bitmap_info.offset =
5905 mddev->bitmap_info.default_offset;
5906 mddev->pers->quiesce(mddev, 1);
5907 rv = bitmap_create(mddev);
5908 if (!rv)
5909 rv = bitmap_load(mddev);
5910 if (rv)
5911 bitmap_destroy(mddev);
5912 mddev->pers->quiesce(mddev, 0);
5913 } else {
5914 /* remove the bitmap */
5915 if (!mddev->bitmap)
5916 return -ENOENT;
5917 if (mddev->bitmap->file)
5918 return -EINVAL;
5919 mddev->pers->quiesce(mddev, 1);
5920 bitmap_destroy(mddev);
5921 mddev->pers->quiesce(mddev, 0);
5922 mddev->bitmap_info.offset = 0;
5925 md_update_sb(mddev, 1);
5926 return rv;
5929 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
5931 mdk_rdev_t *rdev;
5933 if (mddev->pers == NULL)
5934 return -ENODEV;
5936 rdev = find_rdev(mddev, dev);
5937 if (!rdev)
5938 return -ENODEV;
5940 md_error(mddev, rdev);
5941 return 0;
5945 * We have a problem here : there is no easy way to give a CHS
5946 * virtual geometry. We currently pretend that we have a 2 heads
5947 * 4 sectors (with a BIG number of cylinders...). This drives
5948 * dosfs just mad... ;-)
5950 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
5952 mddev_t *mddev = bdev->bd_disk->private_data;
5954 geo->heads = 2;
5955 geo->sectors = 4;
5956 geo->cylinders = mddev->array_sectors / 8;
5957 return 0;
5960 static int md_ioctl(struct block_device *bdev, fmode_t mode,
5961 unsigned int cmd, unsigned long arg)
5963 int err = 0;
5964 void __user *argp = (void __user *)arg;
5965 mddev_t *mddev = NULL;
5966 int ro;
5968 if (!capable(CAP_SYS_ADMIN))
5969 return -EACCES;
5972 * Commands dealing with the RAID driver but not any
5973 * particular array:
5975 switch (cmd)
5977 case RAID_VERSION:
5978 err = get_version(argp);
5979 goto done;
5981 case PRINT_RAID_DEBUG:
5982 err = 0;
5983 md_print_devices();
5984 goto done;
5986 #ifndef MODULE
5987 case RAID_AUTORUN:
5988 err = 0;
5989 autostart_arrays(arg);
5990 goto done;
5991 #endif
5992 default:;
5996 * Commands creating/starting a new array:
5999 mddev = bdev->bd_disk->private_data;
6001 if (!mddev) {
6002 BUG();
6003 goto abort;
6006 err = mddev_lock(mddev);
6007 if (err) {
6008 printk(KERN_INFO
6009 "md: ioctl lock interrupted, reason %d, cmd %d\n",
6010 err, cmd);
6011 goto abort;
6014 switch (cmd)
6016 case SET_ARRAY_INFO:
6018 mdu_array_info_t info;
6019 if (!arg)
6020 memset(&info, 0, sizeof(info));
6021 else if (copy_from_user(&info, argp, sizeof(info))) {
6022 err = -EFAULT;
6023 goto abort_unlock;
6025 if (mddev->pers) {
6026 err = update_array_info(mddev, &info);
6027 if (err) {
6028 printk(KERN_WARNING "md: couldn't update"
6029 " array info. %d\n", err);
6030 goto abort_unlock;
6032 goto done_unlock;
6034 if (!list_empty(&mddev->disks)) {
6035 printk(KERN_WARNING
6036 "md: array %s already has disks!\n",
6037 mdname(mddev));
6038 err = -EBUSY;
6039 goto abort_unlock;
6041 if (mddev->raid_disks) {
6042 printk(KERN_WARNING
6043 "md: array %s already initialised!\n",
6044 mdname(mddev));
6045 err = -EBUSY;
6046 goto abort_unlock;
6048 err = set_array_info(mddev, &info);
6049 if (err) {
6050 printk(KERN_WARNING "md: couldn't set"
6051 " array info. %d\n", err);
6052 goto abort_unlock;
6055 goto done_unlock;
6057 default:;
6061 * Commands querying/configuring an existing array:
6063 /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
6064 * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
6065 if ((!mddev->raid_disks && !mddev->external)
6066 && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
6067 && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
6068 && cmd != GET_BITMAP_FILE) {
6069 err = -ENODEV;
6070 goto abort_unlock;
6074 * Commands even a read-only array can execute:
6076 switch (cmd)
6078 case GET_ARRAY_INFO:
6079 err = get_array_info(mddev, argp);
6080 goto done_unlock;
6082 case GET_BITMAP_FILE:
6083 err = get_bitmap_file(mddev, argp);
6084 goto done_unlock;
6086 case GET_DISK_INFO:
6087 err = get_disk_info(mddev, argp);
6088 goto done_unlock;
6090 case RESTART_ARRAY_RW:
6091 err = restart_array(mddev);
6092 goto done_unlock;
6094 case STOP_ARRAY:
6095 err = do_md_stop(mddev, 0, 1);
6096 goto done_unlock;
6098 case STOP_ARRAY_RO:
6099 err = md_set_readonly(mddev, 1);
6100 goto done_unlock;
6102 case BLKROSET:
6103 if (get_user(ro, (int __user *)(arg))) {
6104 err = -EFAULT;
6105 goto done_unlock;
6107 err = -EINVAL;
6109 /* if the bdev is going readonly the value of mddev->ro
6110 * does not matter, no writes are coming
6112 if (ro)
6113 goto done_unlock;
6115 /* are we are already prepared for writes? */
6116 if (mddev->ro != 1)
6117 goto done_unlock;
6119 /* transitioning to readauto need only happen for
6120 * arrays that call md_write_start
6122 if (mddev->pers) {
6123 err = restart_array(mddev);
6124 if (err == 0) {
6125 mddev->ro = 2;
6126 set_disk_ro(mddev->gendisk, 0);
6129 goto done_unlock;
6133 * The remaining ioctls are changing the state of the
6134 * superblock, so we do not allow them on read-only arrays.
6135 * However non-MD ioctls (e.g. get-size) will still come through
6136 * here and hit the 'default' below, so only disallow
6137 * 'md' ioctls, and switch to rw mode if started auto-readonly.
6139 if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
6140 if (mddev->ro == 2) {
6141 mddev->ro = 0;
6142 sysfs_notify_dirent_safe(mddev->sysfs_state);
6143 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6144 md_wakeup_thread(mddev->thread);
6145 } else {
6146 err = -EROFS;
6147 goto abort_unlock;
6151 switch (cmd)
6153 case ADD_NEW_DISK:
6155 mdu_disk_info_t info;
6156 if (copy_from_user(&info, argp, sizeof(info)))
6157 err = -EFAULT;
6158 else
6159 err = add_new_disk(mddev, &info);
6160 goto done_unlock;
6163 case HOT_REMOVE_DISK:
6164 err = hot_remove_disk(mddev, new_decode_dev(arg));
6165 goto done_unlock;
6167 case HOT_ADD_DISK:
6168 err = hot_add_disk(mddev, new_decode_dev(arg));
6169 goto done_unlock;
6171 case SET_DISK_FAULTY:
6172 err = set_disk_faulty(mddev, new_decode_dev(arg));
6173 goto done_unlock;
6175 case RUN_ARRAY:
6176 err = do_md_run(mddev);
6177 goto done_unlock;
6179 case SET_BITMAP_FILE:
6180 err = set_bitmap_file(mddev, (int)arg);
6181 goto done_unlock;
6183 default:
6184 err = -EINVAL;
6185 goto abort_unlock;
6188 done_unlock:
6189 abort_unlock:
6190 if (mddev->hold_active == UNTIL_IOCTL &&
6191 err != -EINVAL)
6192 mddev->hold_active = 0;
6193 mddev_unlock(mddev);
6195 return err;
6196 done:
6197 if (err)
6198 MD_BUG();
6199 abort:
6200 return err;
6202 #ifdef CONFIG_COMPAT
6203 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
6204 unsigned int cmd, unsigned long arg)
6206 switch (cmd) {
6207 case HOT_REMOVE_DISK:
6208 case HOT_ADD_DISK:
6209 case SET_DISK_FAULTY:
6210 case SET_BITMAP_FILE:
6211 /* These take in integer arg, do not convert */
6212 break;
6213 default:
6214 arg = (unsigned long)compat_ptr(arg);
6215 break;
6218 return md_ioctl(bdev, mode, cmd, arg);
6220 #endif /* CONFIG_COMPAT */
6222 static int md_open(struct block_device *bdev, fmode_t mode)
6225 * Succeed if we can lock the mddev, which confirms that
6226 * it isn't being stopped right now.
6228 mddev_t *mddev = mddev_find(bdev->bd_dev);
6229 int err;
6231 if (mddev->gendisk != bdev->bd_disk) {
6232 /* we are racing with mddev_put which is discarding this
6233 * bd_disk.
6235 mddev_put(mddev);
6236 /* Wait until bdev->bd_disk is definitely gone */
6237 flush_workqueue(md_misc_wq);
6238 /* Then retry the open from the top */
6239 return -ERESTARTSYS;
6241 BUG_ON(mddev != bdev->bd_disk->private_data);
6243 if ((err = mutex_lock_interruptible(&mddev->open_mutex)))
6244 goto out;
6246 err = 0;
6247 atomic_inc(&mddev->openers);
6248 mutex_unlock(&mddev->open_mutex);
6250 check_disk_change(bdev);
6251 out:
6252 return err;
6255 static int md_release(struct gendisk *disk, fmode_t mode)
6257 mddev_t *mddev = disk->private_data;
6259 BUG_ON(!mddev);
6260 atomic_dec(&mddev->openers);
6261 mddev_put(mddev);
6263 return 0;
6266 static int md_media_changed(struct gendisk *disk)
6268 mddev_t *mddev = disk->private_data;
6270 return mddev->changed;
6273 static int md_revalidate(struct gendisk *disk)
6275 mddev_t *mddev = disk->private_data;
6277 mddev->changed = 0;
6278 return 0;
6280 static const struct block_device_operations md_fops =
6282 .owner = THIS_MODULE,
6283 .open = md_open,
6284 .release = md_release,
6285 .ioctl = md_ioctl,
6286 #ifdef CONFIG_COMPAT
6287 .compat_ioctl = md_compat_ioctl,
6288 #endif
6289 .getgeo = md_getgeo,
6290 .media_changed = md_media_changed,
6291 .revalidate_disk= md_revalidate,
6294 static int md_thread(void * arg)
6296 mdk_thread_t *thread = arg;
6299 * md_thread is a 'system-thread', it's priority should be very
6300 * high. We avoid resource deadlocks individually in each
6301 * raid personality. (RAID5 does preallocation) We also use RR and
6302 * the very same RT priority as kswapd, thus we will never get
6303 * into a priority inversion deadlock.
6305 * we definitely have to have equal or higher priority than
6306 * bdflush, otherwise bdflush will deadlock if there are too
6307 * many dirty RAID5 blocks.
6310 allow_signal(SIGKILL);
6311 while (!kthread_should_stop()) {
6313 /* We need to wait INTERRUPTIBLE so that
6314 * we don't add to the load-average.
6315 * That means we need to be sure no signals are
6316 * pending
6318 if (signal_pending(current))
6319 flush_signals(current);
6321 wait_event_interruptible_timeout
6322 (thread->wqueue,
6323 test_bit(THREAD_WAKEUP, &thread->flags)
6324 || kthread_should_stop(),
6325 thread->timeout);
6327 clear_bit(THREAD_WAKEUP, &thread->flags);
6328 if (!kthread_should_stop())
6329 thread->run(thread->mddev);
6332 return 0;
6335 void md_wakeup_thread(mdk_thread_t *thread)
6337 if (thread) {
6338 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
6339 set_bit(THREAD_WAKEUP, &thread->flags);
6340 wake_up(&thread->wqueue);
6344 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
6345 const char *name)
6347 mdk_thread_t *thread;
6349 thread = kzalloc(sizeof(mdk_thread_t), GFP_KERNEL);
6350 if (!thread)
6351 return NULL;
6353 init_waitqueue_head(&thread->wqueue);
6355 thread->run = run;
6356 thread->mddev = mddev;
6357 thread->timeout = MAX_SCHEDULE_TIMEOUT;
6358 thread->tsk = kthread_run(md_thread, thread,
6359 "%s_%s",
6360 mdname(thread->mddev),
6361 name ?: mddev->pers->name);
6362 if (IS_ERR(thread->tsk)) {
6363 kfree(thread);
6364 return NULL;
6366 return thread;
6369 void md_unregister_thread(mdk_thread_t *thread)
6371 if (!thread)
6372 return;
6373 dprintk("interrupting MD-thread pid %d\n", task_pid_nr(thread->tsk));
6375 kthread_stop(thread->tsk);
6376 kfree(thread);
6379 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
6381 if (!mddev) {
6382 MD_BUG();
6383 return;
6386 if (!rdev || test_bit(Faulty, &rdev->flags))
6387 return;
6389 if (mddev->external)
6390 set_bit(Blocked, &rdev->flags);
6392 dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
6393 mdname(mddev),
6394 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
6395 __builtin_return_address(0),__builtin_return_address(1),
6396 __builtin_return_address(2),__builtin_return_address(3));
6398 if (!mddev->pers)
6399 return;
6400 if (!mddev->pers->error_handler)
6401 return;
6402 mddev->pers->error_handler(mddev,rdev);
6403 if (mddev->degraded)
6404 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
6405 sysfs_notify_dirent_safe(rdev->sysfs_state);
6406 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6407 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6408 md_wakeup_thread(mddev->thread);
6409 if (mddev->event_work.func)
6410 queue_work(md_misc_wq, &mddev->event_work);
6411 md_new_event_inintr(mddev);
6414 /* seq_file implementation /proc/mdstat */
6416 static void status_unused(struct seq_file *seq)
6418 int i = 0;
6419 mdk_rdev_t *rdev;
6421 seq_printf(seq, "unused devices: ");
6423 list_for_each_entry(rdev, &pending_raid_disks, same_set) {
6424 char b[BDEVNAME_SIZE];
6425 i++;
6426 seq_printf(seq, "%s ",
6427 bdevname(rdev->bdev,b));
6429 if (!i)
6430 seq_printf(seq, "<none>");
6432 seq_printf(seq, "\n");
6436 static void status_resync(struct seq_file *seq, mddev_t * mddev)
6438 sector_t max_sectors, resync, res;
6439 unsigned long dt, db;
6440 sector_t rt;
6441 int scale;
6442 unsigned int per_milli;
6444 resync = mddev->curr_resync - atomic_read(&mddev->recovery_active);
6446 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
6447 max_sectors = mddev->resync_max_sectors;
6448 else
6449 max_sectors = mddev->dev_sectors;
6452 * Should not happen.
6454 if (!max_sectors) {
6455 MD_BUG();
6456 return;
6458 /* Pick 'scale' such that (resync>>scale)*1000 will fit
6459 * in a sector_t, and (max_sectors>>scale) will fit in a
6460 * u32, as those are the requirements for sector_div.
6461 * Thus 'scale' must be at least 10
6463 scale = 10;
6464 if (sizeof(sector_t) > sizeof(unsigned long)) {
6465 while ( max_sectors/2 > (1ULL<<(scale+32)))
6466 scale++;
6468 res = (resync>>scale)*1000;
6469 sector_div(res, (u32)((max_sectors>>scale)+1));
6471 per_milli = res;
6473 int i, x = per_milli/50, y = 20-x;
6474 seq_printf(seq, "[");
6475 for (i = 0; i < x; i++)
6476 seq_printf(seq, "=");
6477 seq_printf(seq, ">");
6478 for (i = 0; i < y; i++)
6479 seq_printf(seq, ".");
6480 seq_printf(seq, "] ");
6482 seq_printf(seq, " %s =%3u.%u%% (%llu/%llu)",
6483 (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery)?
6484 "reshape" :
6485 (test_bit(MD_RECOVERY_CHECK, &mddev->recovery)?
6486 "check" :
6487 (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
6488 "resync" : "recovery"))),
6489 per_milli/10, per_milli % 10,
6490 (unsigned long long) resync/2,
6491 (unsigned long long) max_sectors/2);
6494 * dt: time from mark until now
6495 * db: blocks written from mark until now
6496 * rt: remaining time
6498 * rt is a sector_t, so could be 32bit or 64bit.
6499 * So we divide before multiply in case it is 32bit and close
6500 * to the limit.
6501 * We scale the divisor (db) by 32 to avoid losing precision
6502 * near the end of resync when the number of remaining sectors
6503 * is close to 'db'.
6504 * We then divide rt by 32 after multiplying by db to compensate.
6505 * The '+1' avoids division by zero if db is very small.
6507 dt = ((jiffies - mddev->resync_mark) / HZ);
6508 if (!dt) dt++;
6509 db = (mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active))
6510 - mddev->resync_mark_cnt;
6512 rt = max_sectors - resync; /* number of remaining sectors */
6513 sector_div(rt, db/32+1);
6514 rt *= dt;
6515 rt >>= 5;
6517 seq_printf(seq, " finish=%lu.%lumin", (unsigned long)rt / 60,
6518 ((unsigned long)rt % 60)/6);
6520 seq_printf(seq, " speed=%ldK/sec", db/2/dt);
6523 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
6525 struct list_head *tmp;
6526 loff_t l = *pos;
6527 mddev_t *mddev;
6529 if (l >= 0x10000)
6530 return NULL;
6531 if (!l--)
6532 /* header */
6533 return (void*)1;
6535 spin_lock(&all_mddevs_lock);
6536 list_for_each(tmp,&all_mddevs)
6537 if (!l--) {
6538 mddev = list_entry(tmp, mddev_t, all_mddevs);
6539 mddev_get(mddev);
6540 spin_unlock(&all_mddevs_lock);
6541 return mddev;
6543 spin_unlock(&all_mddevs_lock);
6544 if (!l--)
6545 return (void*)2;/* tail */
6546 return NULL;
6549 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
6551 struct list_head *tmp;
6552 mddev_t *next_mddev, *mddev = v;
6554 ++*pos;
6555 if (v == (void*)2)
6556 return NULL;
6558 spin_lock(&all_mddevs_lock);
6559 if (v == (void*)1)
6560 tmp = all_mddevs.next;
6561 else
6562 tmp = mddev->all_mddevs.next;
6563 if (tmp != &all_mddevs)
6564 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
6565 else {
6566 next_mddev = (void*)2;
6567 *pos = 0x10000;
6569 spin_unlock(&all_mddevs_lock);
6571 if (v != (void*)1)
6572 mddev_put(mddev);
6573 return next_mddev;
6577 static void md_seq_stop(struct seq_file *seq, void *v)
6579 mddev_t *mddev = v;
6581 if (mddev && v != (void*)1 && v != (void*)2)
6582 mddev_put(mddev);
6585 struct mdstat_info {
6586 int event;
6589 static int md_seq_show(struct seq_file *seq, void *v)
6591 mddev_t *mddev = v;
6592 sector_t sectors;
6593 mdk_rdev_t *rdev;
6594 struct mdstat_info *mi = seq->private;
6595 struct bitmap *bitmap;
6597 if (v == (void*)1) {
6598 struct mdk_personality *pers;
6599 seq_printf(seq, "Personalities : ");
6600 spin_lock(&pers_lock);
6601 list_for_each_entry(pers, &pers_list, list)
6602 seq_printf(seq, "[%s] ", pers->name);
6604 spin_unlock(&pers_lock);
6605 seq_printf(seq, "\n");
6606 mi->event = atomic_read(&md_event_count);
6607 return 0;
6609 if (v == (void*)2) {
6610 status_unused(seq);
6611 return 0;
6614 if (mddev_lock(mddev) < 0)
6615 return -EINTR;
6617 if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
6618 seq_printf(seq, "%s : %sactive", mdname(mddev),
6619 mddev->pers ? "" : "in");
6620 if (mddev->pers) {
6621 if (mddev->ro==1)
6622 seq_printf(seq, " (read-only)");
6623 if (mddev->ro==2)
6624 seq_printf(seq, " (auto-read-only)");
6625 seq_printf(seq, " %s", mddev->pers->name);
6628 sectors = 0;
6629 list_for_each_entry(rdev, &mddev->disks, same_set) {
6630 char b[BDEVNAME_SIZE];
6631 seq_printf(seq, " %s[%d]",
6632 bdevname(rdev->bdev,b), rdev->desc_nr);
6633 if (test_bit(WriteMostly, &rdev->flags))
6634 seq_printf(seq, "(W)");
6635 if (test_bit(Faulty, &rdev->flags)) {
6636 seq_printf(seq, "(F)");
6637 continue;
6638 } else if (rdev->raid_disk < 0)
6639 seq_printf(seq, "(S)"); /* spare */
6640 sectors += rdev->sectors;
6643 if (!list_empty(&mddev->disks)) {
6644 if (mddev->pers)
6645 seq_printf(seq, "\n %llu blocks",
6646 (unsigned long long)
6647 mddev->array_sectors / 2);
6648 else
6649 seq_printf(seq, "\n %llu blocks",
6650 (unsigned long long)sectors / 2);
6652 if (mddev->persistent) {
6653 if (mddev->major_version != 0 ||
6654 mddev->minor_version != 90) {
6655 seq_printf(seq," super %d.%d",
6656 mddev->major_version,
6657 mddev->minor_version);
6659 } else if (mddev->external)
6660 seq_printf(seq, " super external:%s",
6661 mddev->metadata_type);
6662 else
6663 seq_printf(seq, " super non-persistent");
6665 if (mddev->pers) {
6666 mddev->pers->status(seq, mddev);
6667 seq_printf(seq, "\n ");
6668 if (mddev->pers->sync_request) {
6669 if (mddev->curr_resync > 2) {
6670 status_resync(seq, mddev);
6671 seq_printf(seq, "\n ");
6672 } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
6673 seq_printf(seq, "\tresync=DELAYED\n ");
6674 else if (mddev->recovery_cp < MaxSector)
6675 seq_printf(seq, "\tresync=PENDING\n ");
6677 } else
6678 seq_printf(seq, "\n ");
6680 if ((bitmap = mddev->bitmap)) {
6681 unsigned long chunk_kb;
6682 unsigned long flags;
6683 spin_lock_irqsave(&bitmap->lock, flags);
6684 chunk_kb = mddev->bitmap_info.chunksize >> 10;
6685 seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
6686 "%lu%s chunk",
6687 bitmap->pages - bitmap->missing_pages,
6688 bitmap->pages,
6689 (bitmap->pages - bitmap->missing_pages)
6690 << (PAGE_SHIFT - 10),
6691 chunk_kb ? chunk_kb : mddev->bitmap_info.chunksize,
6692 chunk_kb ? "KB" : "B");
6693 if (bitmap->file) {
6694 seq_printf(seq, ", file: ");
6695 seq_path(seq, &bitmap->file->f_path, " \t\n");
6698 seq_printf(seq, "\n");
6699 spin_unlock_irqrestore(&bitmap->lock, flags);
6702 seq_printf(seq, "\n");
6704 mddev_unlock(mddev);
6706 return 0;
6709 static const struct seq_operations md_seq_ops = {
6710 .start = md_seq_start,
6711 .next = md_seq_next,
6712 .stop = md_seq_stop,
6713 .show = md_seq_show,
6716 static int md_seq_open(struct inode *inode, struct file *file)
6718 int error;
6719 struct mdstat_info *mi = kmalloc(sizeof(*mi), GFP_KERNEL);
6720 if (mi == NULL)
6721 return -ENOMEM;
6723 error = seq_open(file, &md_seq_ops);
6724 if (error)
6725 kfree(mi);
6726 else {
6727 struct seq_file *p = file->private_data;
6728 p->private = mi;
6729 mi->event = atomic_read(&md_event_count);
6731 return error;
6734 static unsigned int mdstat_poll(struct file *filp, poll_table *wait)
6736 struct seq_file *m = filp->private_data;
6737 struct mdstat_info *mi = m->private;
6738 int mask;
6740 poll_wait(filp, &md_event_waiters, wait);
6742 /* always allow read */
6743 mask = POLLIN | POLLRDNORM;
6745 if (mi->event != atomic_read(&md_event_count))
6746 mask |= POLLERR | POLLPRI;
6747 return mask;
6750 static const struct file_operations md_seq_fops = {
6751 .owner = THIS_MODULE,
6752 .open = md_seq_open,
6753 .read = seq_read,
6754 .llseek = seq_lseek,
6755 .release = seq_release_private,
6756 .poll = mdstat_poll,
6759 int register_md_personality(struct mdk_personality *p)
6761 spin_lock(&pers_lock);
6762 list_add_tail(&p->list, &pers_list);
6763 printk(KERN_INFO "md: %s personality registered for level %d\n", p->name, p->level);
6764 spin_unlock(&pers_lock);
6765 return 0;
6768 int unregister_md_personality(struct mdk_personality *p)
6770 printk(KERN_INFO "md: %s personality unregistered\n", p->name);
6771 spin_lock(&pers_lock);
6772 list_del_init(&p->list);
6773 spin_unlock(&pers_lock);
6774 return 0;
6777 static int is_mddev_idle(mddev_t *mddev, int init)
6779 mdk_rdev_t * rdev;
6780 int idle;
6781 int curr_events;
6783 idle = 1;
6784 rcu_read_lock();
6785 rdev_for_each_rcu(rdev, mddev) {
6786 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
6787 curr_events = (int)part_stat_read(&disk->part0, sectors[0]) +
6788 (int)part_stat_read(&disk->part0, sectors[1]) -
6789 atomic_read(&disk->sync_io);
6790 /* sync IO will cause sync_io to increase before the disk_stats
6791 * as sync_io is counted when a request starts, and
6792 * disk_stats is counted when it completes.
6793 * So resync activity will cause curr_events to be smaller than
6794 * when there was no such activity.
6795 * non-sync IO will cause disk_stat to increase without
6796 * increasing sync_io so curr_events will (eventually)
6797 * be larger than it was before. Once it becomes
6798 * substantially larger, the test below will cause
6799 * the array to appear non-idle, and resync will slow
6800 * down.
6801 * If there is a lot of outstanding resync activity when
6802 * we set last_event to curr_events, then all that activity
6803 * completing might cause the array to appear non-idle
6804 * and resync will be slowed down even though there might
6805 * not have been non-resync activity. This will only
6806 * happen once though. 'last_events' will soon reflect
6807 * the state where there is little or no outstanding
6808 * resync requests, and further resync activity will
6809 * always make curr_events less than last_events.
6812 if (init || curr_events - rdev->last_events > 64) {
6813 rdev->last_events = curr_events;
6814 idle = 0;
6817 rcu_read_unlock();
6818 return idle;
6821 void md_done_sync(mddev_t *mddev, int blocks, int ok)
6823 /* another "blocks" (512byte) blocks have been synced */
6824 atomic_sub(blocks, &mddev->recovery_active);
6825 wake_up(&mddev->recovery_wait);
6826 if (!ok) {
6827 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6828 md_wakeup_thread(mddev->thread);
6829 // stop recovery, signal do_sync ....
6834 /* md_write_start(mddev, bi)
6835 * If we need to update some array metadata (e.g. 'active' flag
6836 * in superblock) before writing, schedule a superblock update
6837 * and wait for it to complete.
6839 void md_write_start(mddev_t *mddev, struct bio *bi)
6841 int did_change = 0;
6842 if (bio_data_dir(bi) != WRITE)
6843 return;
6845 BUG_ON(mddev->ro == 1);
6846 if (mddev->ro == 2) {
6847 /* need to switch to read/write */
6848 mddev->ro = 0;
6849 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
6850 md_wakeup_thread(mddev->thread);
6851 md_wakeup_thread(mddev->sync_thread);
6852 did_change = 1;
6854 atomic_inc(&mddev->writes_pending);
6855 if (mddev->safemode == 1)
6856 mddev->safemode = 0;
6857 if (mddev->in_sync) {
6858 spin_lock_irq(&mddev->write_lock);
6859 if (mddev->in_sync) {
6860 mddev->in_sync = 0;
6861 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
6862 set_bit(MD_CHANGE_PENDING, &mddev->flags);
6863 md_wakeup_thread(mddev->thread);
6864 did_change = 1;
6866 spin_unlock_irq(&mddev->write_lock);
6868 if (did_change)
6869 sysfs_notify_dirent_safe(mddev->sysfs_state);
6870 wait_event(mddev->sb_wait,
6871 !test_bit(MD_CHANGE_PENDING, &mddev->flags));
6874 void md_write_end(mddev_t *mddev)
6876 if (atomic_dec_and_test(&mddev->writes_pending)) {
6877 if (mddev->safemode == 2)
6878 md_wakeup_thread(mddev->thread);
6879 else if (mddev->safemode_delay)
6880 mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
6884 /* md_allow_write(mddev)
6885 * Calling this ensures that the array is marked 'active' so that writes
6886 * may proceed without blocking. It is important to call this before
6887 * attempting a GFP_KERNEL allocation while holding the mddev lock.
6888 * Must be called with mddev_lock held.
6890 * In the ->external case MD_CHANGE_CLEAN can not be cleared until mddev->lock
6891 * is dropped, so return -EAGAIN after notifying userspace.
6893 int md_allow_write(mddev_t *mddev)
6895 if (!mddev->pers)
6896 return 0;
6897 if (mddev->ro)
6898 return 0;
6899 if (!mddev->pers->sync_request)
6900 return 0;
6902 spin_lock_irq(&mddev->write_lock);
6903 if (mddev->in_sync) {
6904 mddev->in_sync = 0;
6905 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
6906 set_bit(MD_CHANGE_PENDING, &mddev->flags);
6907 if (mddev->safemode_delay &&
6908 mddev->safemode == 0)
6909 mddev->safemode = 1;
6910 spin_unlock_irq(&mddev->write_lock);
6911 md_update_sb(mddev, 0);
6912 sysfs_notify_dirent_safe(mddev->sysfs_state);
6913 } else
6914 spin_unlock_irq(&mddev->write_lock);
6916 if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
6917 return -EAGAIN;
6918 else
6919 return 0;
6921 EXPORT_SYMBOL_GPL(md_allow_write);
6923 #define SYNC_MARKS 10
6924 #define SYNC_MARK_STEP (3*HZ)
6925 void md_do_sync(mddev_t *mddev)
6927 mddev_t *mddev2;
6928 unsigned int currspeed = 0,
6929 window;
6930 sector_t max_sectors,j, io_sectors;
6931 unsigned long mark[SYNC_MARKS];
6932 sector_t mark_cnt[SYNC_MARKS];
6933 int last_mark,m;
6934 struct list_head *tmp;
6935 sector_t last_check;
6936 int skipped = 0;
6937 mdk_rdev_t *rdev;
6938 char *desc;
6940 /* just incase thread restarts... */
6941 if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
6942 return;
6943 if (mddev->ro) /* never try to sync a read-only array */
6944 return;
6946 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
6947 if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
6948 desc = "data-check";
6949 else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
6950 desc = "requested-resync";
6951 else
6952 desc = "resync";
6953 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
6954 desc = "reshape";
6955 else
6956 desc = "recovery";
6958 /* we overload curr_resync somewhat here.
6959 * 0 == not engaged in resync at all
6960 * 2 == checking that there is no conflict with another sync
6961 * 1 == like 2, but have yielded to allow conflicting resync to
6962 * commense
6963 * other == active in resync - this many blocks
6965 * Before starting a resync we must have set curr_resync to
6966 * 2, and then checked that every "conflicting" array has curr_resync
6967 * less than ours. When we find one that is the same or higher
6968 * we wait on resync_wait. To avoid deadlock, we reduce curr_resync
6969 * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
6970 * This will mean we have to start checking from the beginning again.
6974 do {
6975 mddev->curr_resync = 2;
6977 try_again:
6978 if (kthread_should_stop())
6979 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
6981 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
6982 goto skip;
6983 for_each_mddev(mddev2, tmp) {
6984 if (mddev2 == mddev)
6985 continue;
6986 if (!mddev->parallel_resync
6987 && mddev2->curr_resync
6988 && match_mddev_units(mddev, mddev2)) {
6989 DEFINE_WAIT(wq);
6990 if (mddev < mddev2 && mddev->curr_resync == 2) {
6991 /* arbitrarily yield */
6992 mddev->curr_resync = 1;
6993 wake_up(&resync_wait);
6995 if (mddev > mddev2 && mddev->curr_resync == 1)
6996 /* no need to wait here, we can wait the next
6997 * time 'round when curr_resync == 2
6999 continue;
7000 /* We need to wait 'interruptible' so as not to
7001 * contribute to the load average, and not to
7002 * be caught by 'softlockup'
7004 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
7005 if (!kthread_should_stop() &&
7006 mddev2->curr_resync >= mddev->curr_resync) {
7007 printk(KERN_INFO "md: delaying %s of %s"
7008 " until %s has finished (they"
7009 " share one or more physical units)\n",
7010 desc, mdname(mddev), mdname(mddev2));
7011 mddev_put(mddev2);
7012 if (signal_pending(current))
7013 flush_signals(current);
7014 schedule();
7015 finish_wait(&resync_wait, &wq);
7016 goto try_again;
7018 finish_wait(&resync_wait, &wq);
7021 } while (mddev->curr_resync < 2);
7023 j = 0;
7024 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7025 /* resync follows the size requested by the personality,
7026 * which defaults to physical size, but can be virtual size
7028 max_sectors = mddev->resync_max_sectors;
7029 mddev->resync_mismatches = 0;
7030 /* we don't use the checkpoint if there's a bitmap */
7031 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7032 j = mddev->resync_min;
7033 else if (!mddev->bitmap)
7034 j = mddev->recovery_cp;
7036 } else if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
7037 max_sectors = mddev->dev_sectors;
7038 else {
7039 /* recovery follows the physical size of devices */
7040 max_sectors = mddev->dev_sectors;
7041 j = MaxSector;
7042 rcu_read_lock();
7043 list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
7044 if (rdev->raid_disk >= 0 &&
7045 !test_bit(Faulty, &rdev->flags) &&
7046 !test_bit(In_sync, &rdev->flags) &&
7047 rdev->recovery_offset < j)
7048 j = rdev->recovery_offset;
7049 rcu_read_unlock();
7052 printk(KERN_INFO "md: %s of RAID array %s\n", desc, mdname(mddev));
7053 printk(KERN_INFO "md: minimum _guaranteed_ speed:"
7054 " %d KB/sec/disk.\n", speed_min(mddev));
7055 printk(KERN_INFO "md: using maximum available idle IO bandwidth "
7056 "(but not more than %d KB/sec) for %s.\n",
7057 speed_max(mddev), desc);
7059 is_mddev_idle(mddev, 1); /* this initializes IO event counters */
7061 io_sectors = 0;
7062 for (m = 0; m < SYNC_MARKS; m++) {
7063 mark[m] = jiffies;
7064 mark_cnt[m] = io_sectors;
7066 last_mark = 0;
7067 mddev->resync_mark = mark[last_mark];
7068 mddev->resync_mark_cnt = mark_cnt[last_mark];
7071 * Tune reconstruction:
7073 window = 32*(PAGE_SIZE/512);
7074 printk(KERN_INFO "md: using %dk window, over a total of %lluk.\n",
7075 window/2, (unsigned long long)max_sectors/2);
7077 atomic_set(&mddev->recovery_active, 0);
7078 last_check = 0;
7080 if (j>2) {
7081 printk(KERN_INFO
7082 "md: resuming %s of %s from checkpoint.\n",
7083 desc, mdname(mddev));
7084 mddev->curr_resync = j;
7086 mddev->curr_resync_completed = j;
7088 while (j < max_sectors) {
7089 sector_t sectors;
7091 skipped = 0;
7093 if (!test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7094 ((mddev->curr_resync > mddev->curr_resync_completed &&
7095 (mddev->curr_resync - mddev->curr_resync_completed)
7096 > (max_sectors >> 4)) ||
7097 (j - mddev->curr_resync_completed)*2
7098 >= mddev->resync_max - mddev->curr_resync_completed
7099 )) {
7100 /* time to update curr_resync_completed */
7101 wait_event(mddev->recovery_wait,
7102 atomic_read(&mddev->recovery_active) == 0);
7103 mddev->curr_resync_completed = j;
7104 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7105 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
7108 while (j >= mddev->resync_max && !kthread_should_stop()) {
7109 /* As this condition is controlled by user-space,
7110 * we can block indefinitely, so use '_interruptible'
7111 * to avoid triggering warnings.
7113 flush_signals(current); /* just in case */
7114 wait_event_interruptible(mddev->recovery_wait,
7115 mddev->resync_max > j
7116 || kthread_should_stop());
7119 if (kthread_should_stop())
7120 goto interrupted;
7122 sectors = mddev->pers->sync_request(mddev, j, &skipped,
7123 currspeed < speed_min(mddev));
7124 if (sectors == 0) {
7125 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7126 goto out;
7129 if (!skipped) { /* actual IO requested */
7130 io_sectors += sectors;
7131 atomic_add(sectors, &mddev->recovery_active);
7134 j += sectors;
7135 if (j>1) mddev->curr_resync = j;
7136 mddev->curr_mark_cnt = io_sectors;
7137 if (last_check == 0)
7138 /* this is the earliers that rebuilt will be
7139 * visible in /proc/mdstat
7141 md_new_event(mddev);
7143 if (last_check + window > io_sectors || j == max_sectors)
7144 continue;
7146 last_check = io_sectors;
7148 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7149 break;
7151 repeat:
7152 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
7153 /* step marks */
7154 int next = (last_mark+1) % SYNC_MARKS;
7156 mddev->resync_mark = mark[next];
7157 mddev->resync_mark_cnt = mark_cnt[next];
7158 mark[next] = jiffies;
7159 mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
7160 last_mark = next;
7164 if (kthread_should_stop())
7165 goto interrupted;
7169 * this loop exits only if either when we are slower than
7170 * the 'hard' speed limit, or the system was IO-idle for
7171 * a jiffy.
7172 * the system might be non-idle CPU-wise, but we only care
7173 * about not overloading the IO subsystem. (things like an
7174 * e2fsck being done on the RAID array should execute fast)
7176 cond_resched();
7178 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
7179 /((jiffies-mddev->resync_mark)/HZ +1) +1;
7181 if (currspeed > speed_min(mddev)) {
7182 if ((currspeed > speed_max(mddev)) ||
7183 !is_mddev_idle(mddev, 0)) {
7184 msleep(500);
7185 goto repeat;
7189 printk(KERN_INFO "md: %s: %s done.\n",mdname(mddev), desc);
7191 * this also signals 'finished resyncing' to md_stop
7193 out:
7194 wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
7196 /* tell personality that we are finished */
7197 mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
7199 if (!test_bit(MD_RECOVERY_CHECK, &mddev->recovery) &&
7200 mddev->curr_resync > 2) {
7201 if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
7202 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7203 if (mddev->curr_resync >= mddev->recovery_cp) {
7204 printk(KERN_INFO
7205 "md: checkpointing %s of %s.\n",
7206 desc, mdname(mddev));
7207 mddev->recovery_cp = mddev->curr_resync;
7209 } else
7210 mddev->recovery_cp = MaxSector;
7211 } else {
7212 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery))
7213 mddev->curr_resync = MaxSector;
7214 rcu_read_lock();
7215 list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
7216 if (rdev->raid_disk >= 0 &&
7217 mddev->delta_disks >= 0 &&
7218 !test_bit(Faulty, &rdev->flags) &&
7219 !test_bit(In_sync, &rdev->flags) &&
7220 rdev->recovery_offset < mddev->curr_resync)
7221 rdev->recovery_offset = mddev->curr_resync;
7222 rcu_read_unlock();
7225 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7227 skip:
7228 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
7229 /* We completed so min/max setting can be forgotten if used. */
7230 if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7231 mddev->resync_min = 0;
7232 mddev->resync_max = MaxSector;
7233 } else if (test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
7234 mddev->resync_min = mddev->curr_resync_completed;
7235 mddev->curr_resync = 0;
7236 wake_up(&resync_wait);
7237 set_bit(MD_RECOVERY_DONE, &mddev->recovery);
7238 md_wakeup_thread(mddev->thread);
7239 return;
7241 interrupted:
7243 * got a signal, exit.
7245 printk(KERN_INFO
7246 "md: md_do_sync() got signal ... exiting\n");
7247 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
7248 goto out;
7251 EXPORT_SYMBOL_GPL(md_do_sync);
7253 static int remove_and_add_spares(mddev_t *mddev)
7255 mdk_rdev_t *rdev;
7256 int spares = 0;
7258 mddev->curr_resync_completed = 0;
7260 list_for_each_entry(rdev, &mddev->disks, same_set)
7261 if (rdev->raid_disk >= 0 &&
7262 !test_bit(Blocked, &rdev->flags) &&
7263 (test_bit(Faulty, &rdev->flags) ||
7264 ! test_bit(In_sync, &rdev->flags)) &&
7265 atomic_read(&rdev->nr_pending)==0) {
7266 if (mddev->pers->hot_remove_disk(
7267 mddev, rdev->raid_disk)==0) {
7268 sysfs_unlink_rdev(mddev, rdev);
7269 rdev->raid_disk = -1;
7273 if (mddev->degraded) {
7274 list_for_each_entry(rdev, &mddev->disks, same_set) {
7275 if (rdev->raid_disk >= 0 &&
7276 !test_bit(In_sync, &rdev->flags) &&
7277 !test_bit(Faulty, &rdev->flags) &&
7278 !test_bit(Blocked, &rdev->flags))
7279 spares++;
7280 if (rdev->raid_disk < 0
7281 && !test_bit(Faulty, &rdev->flags)) {
7282 rdev->recovery_offset = 0;
7283 if (mddev->pers->
7284 hot_add_disk(mddev, rdev) == 0) {
7285 if (sysfs_link_rdev(mddev, rdev))
7286 /* failure here is OK */;
7287 spares++;
7288 md_new_event(mddev);
7289 set_bit(MD_CHANGE_DEVS, &mddev->flags);
7290 } else
7291 break;
7295 return spares;
7298 static void reap_sync_thread(mddev_t *mddev)
7300 mdk_rdev_t *rdev;
7302 /* resync has finished, collect result */
7303 md_unregister_thread(mddev->sync_thread);
7304 mddev->sync_thread = NULL;
7305 if (!test_bit(MD_RECOVERY_INTR, &mddev->recovery) &&
7306 !test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery)) {
7307 /* success...*/
7308 /* activate any spares */
7309 if (mddev->pers->spare_active(mddev))
7310 sysfs_notify(&mddev->kobj, NULL,
7311 "degraded");
7313 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery) &&
7314 mddev->pers->finish_reshape)
7315 mddev->pers->finish_reshape(mddev);
7316 md_update_sb(mddev, 1);
7318 /* if array is no-longer degraded, then any saved_raid_disk
7319 * information must be scrapped
7321 if (!mddev->degraded)
7322 list_for_each_entry(rdev, &mddev->disks, same_set)
7323 rdev->saved_raid_disk = -1;
7325 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7326 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7327 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7328 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7329 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7330 /* flag recovery needed just to double check */
7331 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7332 sysfs_notify_dirent_safe(mddev->sysfs_action);
7333 md_new_event(mddev);
7334 if (mddev->event_work.func)
7335 queue_work(md_misc_wq, &mddev->event_work);
7339 * This routine is regularly called by all per-raid-array threads to
7340 * deal with generic issues like resync and super-block update.
7341 * Raid personalities that don't have a thread (linear/raid0) do not
7342 * need this as they never do any recovery or update the superblock.
7344 * It does not do any resync itself, but rather "forks" off other threads
7345 * to do that as needed.
7346 * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
7347 * "->recovery" and create a thread at ->sync_thread.
7348 * When the thread finishes it sets MD_RECOVERY_DONE
7349 * and wakeups up this thread which will reap the thread and finish up.
7350 * This thread also removes any faulty devices (with nr_pending == 0).
7352 * The overall approach is:
7353 * 1/ if the superblock needs updating, update it.
7354 * 2/ If a recovery thread is running, don't do anything else.
7355 * 3/ If recovery has finished, clean up, possibly marking spares active.
7356 * 4/ If there are any faulty devices, remove them.
7357 * 5/ If array is degraded, try to add spares devices
7358 * 6/ If array has spares or is not in-sync, start a resync thread.
7360 void md_check_recovery(mddev_t *mddev)
7362 if (mddev->suspended)
7363 return;
7365 if (mddev->bitmap)
7366 bitmap_daemon_work(mddev);
7368 if (signal_pending(current)) {
7369 if (mddev->pers->sync_request && !mddev->external) {
7370 printk(KERN_INFO "md: %s in immediate safe mode\n",
7371 mdname(mddev));
7372 mddev->safemode = 2;
7374 flush_signals(current);
7377 if (mddev->ro && !test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
7378 return;
7379 if ( ! (
7380 (mddev->flags & ~ (1<<MD_CHANGE_PENDING)) ||
7381 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
7382 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
7383 (mddev->external == 0 && mddev->safemode == 1) ||
7384 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
7385 && !mddev->in_sync && mddev->recovery_cp == MaxSector)
7387 return;
7389 if (mddev_trylock(mddev)) {
7390 int spares = 0;
7392 if (mddev->ro) {
7393 /* Only thing we do on a ro array is remove
7394 * failed devices.
7396 mdk_rdev_t *rdev;
7397 list_for_each_entry(rdev, &mddev->disks, same_set)
7398 if (rdev->raid_disk >= 0 &&
7399 !test_bit(Blocked, &rdev->flags) &&
7400 test_bit(Faulty, &rdev->flags) &&
7401 atomic_read(&rdev->nr_pending)==0) {
7402 if (mddev->pers->hot_remove_disk(
7403 mddev, rdev->raid_disk)==0) {
7404 sysfs_unlink_rdev(mddev, rdev);
7405 rdev->raid_disk = -1;
7408 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7409 goto unlock;
7412 if (!mddev->external) {
7413 int did_change = 0;
7414 spin_lock_irq(&mddev->write_lock);
7415 if (mddev->safemode &&
7416 !atomic_read(&mddev->writes_pending) &&
7417 !mddev->in_sync &&
7418 mddev->recovery_cp == MaxSector) {
7419 mddev->in_sync = 1;
7420 did_change = 1;
7421 set_bit(MD_CHANGE_CLEAN, &mddev->flags);
7423 if (mddev->safemode == 1)
7424 mddev->safemode = 0;
7425 spin_unlock_irq(&mddev->write_lock);
7426 if (did_change)
7427 sysfs_notify_dirent_safe(mddev->sysfs_state);
7430 if (mddev->flags)
7431 md_update_sb(mddev, 0);
7433 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
7434 !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
7435 /* resync/recovery still happening */
7436 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7437 goto unlock;
7439 if (mddev->sync_thread) {
7440 reap_sync_thread(mddev);
7441 goto unlock;
7443 /* Set RUNNING before clearing NEEDED to avoid
7444 * any transients in the value of "sync_action".
7446 set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7447 clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
7448 /* Clear some bits that don't mean anything, but
7449 * might be left set
7451 clear_bit(MD_RECOVERY_INTR, &mddev->recovery);
7452 clear_bit(MD_RECOVERY_DONE, &mddev->recovery);
7454 if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
7455 goto unlock;
7456 /* no recovery is running.
7457 * remove any failed drives, then
7458 * add spares if possible.
7459 * Spare are also removed and re-added, to allow
7460 * the personality to fail the re-add.
7463 if (mddev->reshape_position != MaxSector) {
7464 if (mddev->pers->check_reshape == NULL ||
7465 mddev->pers->check_reshape(mddev) != 0)
7466 /* Cannot proceed */
7467 goto unlock;
7468 set_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7469 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7470 } else if ((spares = remove_and_add_spares(mddev))) {
7471 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7472 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7473 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7474 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7475 } else if (mddev->recovery_cp < MaxSector) {
7476 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7477 clear_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
7478 } else if (!test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
7479 /* nothing to be done ... */
7480 goto unlock;
7482 if (mddev->pers->sync_request) {
7483 if (spares && mddev->bitmap && ! mddev->bitmap->file) {
7484 /* We are adding a device or devices to an array
7485 * which has the bitmap stored on all devices.
7486 * So make sure all bitmap pages get written
7488 bitmap_write_all(mddev->bitmap);
7490 mddev->sync_thread = md_register_thread(md_do_sync,
7491 mddev,
7492 "resync");
7493 if (!mddev->sync_thread) {
7494 printk(KERN_ERR "%s: could not start resync"
7495 " thread...\n",
7496 mdname(mddev));
7497 /* leave the spares where they are, it shouldn't hurt */
7498 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7499 clear_bit(MD_RECOVERY_SYNC, &mddev->recovery);
7500 clear_bit(MD_RECOVERY_RESHAPE, &mddev->recovery);
7501 clear_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
7502 clear_bit(MD_RECOVERY_CHECK, &mddev->recovery);
7503 } else
7504 md_wakeup_thread(mddev->sync_thread);
7505 sysfs_notify_dirent_safe(mddev->sysfs_action);
7506 md_new_event(mddev);
7508 unlock:
7509 if (!mddev->sync_thread) {
7510 clear_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
7511 if (test_and_clear_bit(MD_RECOVERY_RECOVER,
7512 &mddev->recovery))
7513 if (mddev->sysfs_action)
7514 sysfs_notify_dirent_safe(mddev->sysfs_action);
7516 mddev_unlock(mddev);
7520 void md_wait_for_blocked_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
7522 sysfs_notify_dirent_safe(rdev->sysfs_state);
7523 wait_event_timeout(rdev->blocked_wait,
7524 !test_bit(Blocked, &rdev->flags),
7525 msecs_to_jiffies(5000));
7526 rdev_dec_pending(rdev, mddev);
7528 EXPORT_SYMBOL(md_wait_for_blocked_rdev);
7531 /* Bad block management.
7532 * We can record which blocks on each device are 'bad' and so just
7533 * fail those blocks, or that stripe, rather than the whole device.
7534 * Entries in the bad-block table are 64bits wide. This comprises:
7535 * Length of bad-range, in sectors: 0-511 for lengths 1-512
7536 * Start of bad-range, sector offset, 54 bits (allows 8 exbibytes)
7537 * A 'shift' can be set so that larger blocks are tracked and
7538 * consequently larger devices can be covered.
7539 * 'Acknowledged' flag - 1 bit. - the most significant bit.
7541 * Locking of the bad-block table uses a seqlock so md_is_badblock
7542 * might need to retry if it is very unlucky.
7543 * We will sometimes want to check for bad blocks in a bi_end_io function,
7544 * so we use the write_seqlock_irq variant.
7546 * When looking for a bad block we specify a range and want to
7547 * know if any block in the range is bad. So we binary-search
7548 * to the last range that starts at-or-before the given endpoint,
7549 * (or "before the sector after the target range")
7550 * then see if it ends after the given start.
7551 * We return
7552 * 0 if there are no known bad blocks in the range
7553 * 1 if there are known bad block which are all acknowledged
7554 * -1 if there are bad blocks which have not yet been acknowledged in metadata.
7555 * plus the start/length of the first bad section we overlap.
7557 int md_is_badblock(struct badblocks *bb, sector_t s, int sectors,
7558 sector_t *first_bad, int *bad_sectors)
7560 int hi;
7561 int lo = 0;
7562 u64 *p = bb->page;
7563 int rv = 0;
7564 sector_t target = s + sectors;
7565 unsigned seq;
7567 if (bb->shift > 0) {
7568 /* round the start down, and the end up */
7569 s >>= bb->shift;
7570 target += (1<<bb->shift) - 1;
7571 target >>= bb->shift;
7572 sectors = target - s;
7574 /* 'target' is now the first block after the bad range */
7576 retry:
7577 seq = read_seqbegin(&bb->lock);
7579 hi = bb->count;
7581 /* Binary search between lo and hi for 'target'
7582 * i.e. for the last range that starts before 'target'
7584 /* INVARIANT: ranges before 'lo' and at-or-after 'hi'
7585 * are known not to be the last range before target.
7586 * VARIANT: hi-lo is the number of possible
7587 * ranges, and decreases until it reaches 1
7589 while (hi - lo > 1) {
7590 int mid = (lo + hi) / 2;
7591 sector_t a = BB_OFFSET(p[mid]);
7592 if (a < target)
7593 /* This could still be the one, earlier ranges
7594 * could not. */
7595 lo = mid;
7596 else
7597 /* This and later ranges are definitely out. */
7598 hi = mid;
7600 /* 'lo' might be the last that started before target, but 'hi' isn't */
7601 if (hi > lo) {
7602 /* need to check all range that end after 's' to see if
7603 * any are unacknowledged.
7605 while (lo >= 0 &&
7606 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
7607 if (BB_OFFSET(p[lo]) < target) {
7608 /* starts before the end, and finishes after
7609 * the start, so they must overlap
7611 if (rv != -1 && BB_ACK(p[lo]))
7612 rv = 1;
7613 else
7614 rv = -1;
7615 *first_bad = BB_OFFSET(p[lo]);
7616 *bad_sectors = BB_LEN(p[lo]);
7618 lo--;
7622 if (read_seqretry(&bb->lock, seq))
7623 goto retry;
7625 return rv;
7627 EXPORT_SYMBOL_GPL(md_is_badblock);
7630 * Add a range of bad blocks to the table.
7631 * This might extend the table, or might contract it
7632 * if two adjacent ranges can be merged.
7633 * We binary-search to find the 'insertion' point, then
7634 * decide how best to handle it.
7636 static int md_set_badblocks(struct badblocks *bb, sector_t s, int sectors,
7637 int acknowledged)
7639 u64 *p;
7640 int lo, hi;
7641 int rv = 1;
7643 if (bb->shift < 0)
7644 /* badblocks are disabled */
7645 return 0;
7647 if (bb->shift) {
7648 /* round the start down, and the end up */
7649 sector_t next = s + sectors;
7650 s >>= bb->shift;
7651 next += (1<<bb->shift) - 1;
7652 next >>= bb->shift;
7653 sectors = next - s;
7656 write_seqlock_irq(&bb->lock);
7658 p = bb->page;
7659 lo = 0;
7660 hi = bb->count;
7661 /* Find the last range that starts at-or-before 's' */
7662 while (hi - lo > 1) {
7663 int mid = (lo + hi) / 2;
7664 sector_t a = BB_OFFSET(p[mid]);
7665 if (a <= s)
7666 lo = mid;
7667 else
7668 hi = mid;
7670 if (hi > lo && BB_OFFSET(p[lo]) > s)
7671 hi = lo;
7673 if (hi > lo) {
7674 /* we found a range that might merge with the start
7675 * of our new range
7677 sector_t a = BB_OFFSET(p[lo]);
7678 sector_t e = a + BB_LEN(p[lo]);
7679 int ack = BB_ACK(p[lo]);
7680 if (e >= s) {
7681 /* Yes, we can merge with a previous range */
7682 if (s == a && s + sectors >= e)
7683 /* new range covers old */
7684 ack = acknowledged;
7685 else
7686 ack = ack && acknowledged;
7688 if (e < s + sectors)
7689 e = s + sectors;
7690 if (e - a <= BB_MAX_LEN) {
7691 p[lo] = BB_MAKE(a, e-a, ack);
7692 s = e;
7693 } else {
7694 /* does not all fit in one range,
7695 * make p[lo] maximal
7697 if (BB_LEN(p[lo]) != BB_MAX_LEN)
7698 p[lo] = BB_MAKE(a, BB_MAX_LEN, ack);
7699 s = a + BB_MAX_LEN;
7701 sectors = e - s;
7704 if (sectors && hi < bb->count) {
7705 /* 'hi' points to the first range that starts after 's'.
7706 * Maybe we can merge with the start of that range */
7707 sector_t a = BB_OFFSET(p[hi]);
7708 sector_t e = a + BB_LEN(p[hi]);
7709 int ack = BB_ACK(p[hi]);
7710 if (a <= s + sectors) {
7711 /* merging is possible */
7712 if (e <= s + sectors) {
7713 /* full overlap */
7714 e = s + sectors;
7715 ack = acknowledged;
7716 } else
7717 ack = ack && acknowledged;
7719 a = s;
7720 if (e - a <= BB_MAX_LEN) {
7721 p[hi] = BB_MAKE(a, e-a, ack);
7722 s = e;
7723 } else {
7724 p[hi] = BB_MAKE(a, BB_MAX_LEN, ack);
7725 s = a + BB_MAX_LEN;
7727 sectors = e - s;
7728 lo = hi;
7729 hi++;
7732 if (sectors == 0 && hi < bb->count) {
7733 /* we might be able to combine lo and hi */
7734 /* Note: 's' is at the end of 'lo' */
7735 sector_t a = BB_OFFSET(p[hi]);
7736 int lolen = BB_LEN(p[lo]);
7737 int hilen = BB_LEN(p[hi]);
7738 int newlen = lolen + hilen - (s - a);
7739 if (s >= a && newlen < BB_MAX_LEN) {
7740 /* yes, we can combine them */
7741 int ack = BB_ACK(p[lo]) && BB_ACK(p[hi]);
7742 p[lo] = BB_MAKE(BB_OFFSET(p[lo]), newlen, ack);
7743 memmove(p + hi, p + hi + 1,
7744 (bb->count - hi - 1) * 8);
7745 bb->count--;
7748 while (sectors) {
7749 /* didn't merge (it all).
7750 * Need to add a range just before 'hi' */
7751 if (bb->count >= MD_MAX_BADBLOCKS) {
7752 /* No room for more */
7753 rv = 0;
7754 break;
7755 } else {
7756 int this_sectors = sectors;
7757 memmove(p + hi + 1, p + hi,
7758 (bb->count - hi) * 8);
7759 bb->count++;
7761 if (this_sectors > BB_MAX_LEN)
7762 this_sectors = BB_MAX_LEN;
7763 p[hi] = BB_MAKE(s, this_sectors, acknowledged);
7764 sectors -= this_sectors;
7765 s += this_sectors;
7769 bb->changed = 1;
7770 write_sequnlock_irq(&bb->lock);
7772 return rv;
7775 int rdev_set_badblocks(mdk_rdev_t *rdev, sector_t s, int sectors,
7776 int acknowledged)
7778 int rv = md_set_badblocks(&rdev->badblocks,
7779 s + rdev->data_offset, sectors, acknowledged);
7780 if (rv) {
7781 /* Make sure they get written out promptly */
7782 set_bit(MD_CHANGE_CLEAN, &rdev->mddev->flags);
7783 md_wakeup_thread(rdev->mddev->thread);
7785 return rv;
7787 EXPORT_SYMBOL_GPL(rdev_set_badblocks);
7790 * Remove a range of bad blocks from the table.
7791 * This may involve extending the table if we spilt a region,
7792 * but it must not fail. So if the table becomes full, we just
7793 * drop the remove request.
7795 static int md_clear_badblocks(struct badblocks *bb, sector_t s, int sectors)
7797 u64 *p;
7798 int lo, hi;
7799 sector_t target = s + sectors;
7800 int rv = 0;
7802 if (bb->shift > 0) {
7803 /* When clearing we round the start up and the end down.
7804 * This should not matter as the shift should align with
7805 * the block size and no rounding should ever be needed.
7806 * However it is better the think a block is bad when it
7807 * isn't than to think a block is not bad when it is.
7809 s += (1<<bb->shift) - 1;
7810 s >>= bb->shift;
7811 target >>= bb->shift;
7812 sectors = target - s;
7815 write_seqlock_irq(&bb->lock);
7817 p = bb->page;
7818 lo = 0;
7819 hi = bb->count;
7820 /* Find the last range that starts before 'target' */
7821 while (hi - lo > 1) {
7822 int mid = (lo + hi) / 2;
7823 sector_t a = BB_OFFSET(p[mid]);
7824 if (a < target)
7825 lo = mid;
7826 else
7827 hi = mid;
7829 if (hi > lo) {
7830 /* p[lo] is the last range that could overlap the
7831 * current range. Earlier ranges could also overlap,
7832 * but only this one can overlap the end of the range.
7834 if (BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > target) {
7835 /* Partial overlap, leave the tail of this range */
7836 int ack = BB_ACK(p[lo]);
7837 sector_t a = BB_OFFSET(p[lo]);
7838 sector_t end = a + BB_LEN(p[lo]);
7840 if (a < s) {
7841 /* we need to split this range */
7842 if (bb->count >= MD_MAX_BADBLOCKS) {
7843 rv = 0;
7844 goto out;
7846 memmove(p+lo+1, p+lo, (bb->count - lo) * 8);
7847 bb->count++;
7848 p[lo] = BB_MAKE(a, s-a, ack);
7849 lo++;
7851 p[lo] = BB_MAKE(target, end - target, ack);
7852 /* there is no longer an overlap */
7853 hi = lo;
7854 lo--;
7856 while (lo >= 0 &&
7857 BB_OFFSET(p[lo]) + BB_LEN(p[lo]) > s) {
7858 /* This range does overlap */
7859 if (BB_OFFSET(p[lo]) < s) {
7860 /* Keep the early parts of this range. */
7861 int ack = BB_ACK(p[lo]);
7862 sector_t start = BB_OFFSET(p[lo]);
7863 p[lo] = BB_MAKE(start, s - start, ack);
7864 /* now low doesn't overlap, so.. */
7865 break;
7867 lo--;
7869 /* 'lo' is strictly before, 'hi' is strictly after,
7870 * anything between needs to be discarded
7872 if (hi - lo > 1) {
7873 memmove(p+lo+1, p+hi, (bb->count - hi) * 8);
7874 bb->count -= (hi - lo - 1);
7878 bb->changed = 1;
7879 out:
7880 write_sequnlock_irq(&bb->lock);
7881 return rv;
7884 int rdev_clear_badblocks(mdk_rdev_t *rdev, sector_t s, int sectors)
7886 return md_clear_badblocks(&rdev->badblocks,
7887 s + rdev->data_offset,
7888 sectors);
7890 EXPORT_SYMBOL_GPL(rdev_clear_badblocks);
7893 * Acknowledge all bad blocks in a list.
7894 * This only succeeds if ->changed is clear. It is used by
7895 * in-kernel metadata updates
7897 void md_ack_all_badblocks(struct badblocks *bb)
7899 if (bb->page == NULL || bb->changed)
7900 /* no point even trying */
7901 return;
7902 write_seqlock_irq(&bb->lock);
7904 if (bb->changed == 0) {
7905 u64 *p = bb->page;
7906 int i;
7907 for (i = 0; i < bb->count ; i++) {
7908 if (!BB_ACK(p[i])) {
7909 sector_t start = BB_OFFSET(p[i]);
7910 int len = BB_LEN(p[i]);
7911 p[i] = BB_MAKE(start, len, 1);
7915 write_sequnlock_irq(&bb->lock);
7917 EXPORT_SYMBOL_GPL(md_ack_all_badblocks);
7919 /* sysfs access to bad-blocks list.
7920 * We present two files.
7921 * 'bad-blocks' lists sector numbers and lengths of ranges that
7922 * are recorded as bad. The list is truncated to fit within
7923 * the one-page limit of sysfs.
7924 * Writing "sector length" to this file adds an acknowledged
7925 * bad block list.
7926 * 'unacknowledged-bad-blocks' lists bad blocks that have not yet
7927 * been acknowledged. Writing to this file adds bad blocks
7928 * without acknowledging them. This is largely for testing.
7931 static ssize_t
7932 badblocks_show(struct badblocks *bb, char *page, int unack)
7934 size_t len;
7935 int i;
7936 u64 *p = bb->page;
7937 unsigned seq;
7939 if (bb->shift < 0)
7940 return 0;
7942 retry:
7943 seq = read_seqbegin(&bb->lock);
7945 len = 0;
7946 i = 0;
7948 while (len < PAGE_SIZE && i < bb->count) {
7949 sector_t s = BB_OFFSET(p[i]);
7950 unsigned int length = BB_LEN(p[i]);
7951 int ack = BB_ACK(p[i]);
7952 i++;
7954 if (unack && ack)
7955 continue;
7957 len += snprintf(page+len, PAGE_SIZE-len, "%llu %u\n",
7958 (unsigned long long)s << bb->shift,
7959 length << bb->shift);
7962 if (read_seqretry(&bb->lock, seq))
7963 goto retry;
7965 return len;
7968 #define DO_DEBUG 1
7970 static ssize_t
7971 badblocks_store(struct badblocks *bb, const char *page, size_t len, int unack)
7973 unsigned long long sector;
7974 int length;
7975 char newline;
7976 #ifdef DO_DEBUG
7977 /* Allow clearing via sysfs *only* for testing/debugging.
7978 * Normally only a successful write may clear a badblock
7980 int clear = 0;
7981 if (page[0] == '-') {
7982 clear = 1;
7983 page++;
7985 #endif /* DO_DEBUG */
7987 switch (sscanf(page, "%llu %d%c", &sector, &length, &newline)) {
7988 case 3:
7989 if (newline != '\n')
7990 return -EINVAL;
7991 case 2:
7992 if (length <= 0)
7993 return -EINVAL;
7994 break;
7995 default:
7996 return -EINVAL;
7999 #ifdef DO_DEBUG
8000 if (clear) {
8001 md_clear_badblocks(bb, sector, length);
8002 return len;
8004 #endif /* DO_DEBUG */
8005 if (md_set_badblocks(bb, sector, length, !unack))
8006 return len;
8007 else
8008 return -ENOSPC;
8011 static int md_notify_reboot(struct notifier_block *this,
8012 unsigned long code, void *x)
8014 struct list_head *tmp;
8015 mddev_t *mddev;
8017 if ((code == SYS_DOWN) || (code == SYS_HALT) || (code == SYS_POWER_OFF)) {
8019 printk(KERN_INFO "md: stopping all md devices.\n");
8021 for_each_mddev(mddev, tmp)
8022 if (mddev_trylock(mddev)) {
8023 /* Force a switch to readonly even array
8024 * appears to still be in use. Hence
8025 * the '100'.
8027 md_set_readonly(mddev, 100);
8028 mddev_unlock(mddev);
8031 * certain more exotic SCSI devices are known to be
8032 * volatile wrt too early system reboots. While the
8033 * right place to handle this issue is the given
8034 * driver, we do want to have a safe RAID driver ...
8036 mdelay(1000*1);
8038 return NOTIFY_DONE;
8041 static struct notifier_block md_notifier = {
8042 .notifier_call = md_notify_reboot,
8043 .next = NULL,
8044 .priority = INT_MAX, /* before any real devices */
8047 static void md_geninit(void)
8049 dprintk("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
8051 proc_create("mdstat", S_IRUGO, NULL, &md_seq_fops);
8054 static int __init md_init(void)
8056 int ret = -ENOMEM;
8058 md_wq = alloc_workqueue("md", WQ_MEM_RECLAIM, 0);
8059 if (!md_wq)
8060 goto err_wq;
8062 md_misc_wq = alloc_workqueue("md_misc", 0, 0);
8063 if (!md_misc_wq)
8064 goto err_misc_wq;
8066 if ((ret = register_blkdev(MD_MAJOR, "md")) < 0)
8067 goto err_md;
8069 if ((ret = register_blkdev(0, "mdp")) < 0)
8070 goto err_mdp;
8071 mdp_major = ret;
8073 blk_register_region(MKDEV(MD_MAJOR, 0), 1UL<<MINORBITS, THIS_MODULE,
8074 md_probe, NULL, NULL);
8075 blk_register_region(MKDEV(mdp_major, 0), 1UL<<MINORBITS, THIS_MODULE,
8076 md_probe, NULL, NULL);
8078 register_reboot_notifier(&md_notifier);
8079 raid_table_header = register_sysctl_table(raid_root_table);
8081 md_geninit();
8082 return 0;
8084 err_mdp:
8085 unregister_blkdev(MD_MAJOR, "md");
8086 err_md:
8087 destroy_workqueue(md_misc_wq);
8088 err_misc_wq:
8089 destroy_workqueue(md_wq);
8090 err_wq:
8091 return ret;
8094 #ifndef MODULE
8097 * Searches all registered partitions for autorun RAID arrays
8098 * at boot time.
8101 static LIST_HEAD(all_detected_devices);
8102 struct detected_devices_node {
8103 struct list_head list;
8104 dev_t dev;
8107 void md_autodetect_dev(dev_t dev)
8109 struct detected_devices_node *node_detected_dev;
8111 node_detected_dev = kzalloc(sizeof(*node_detected_dev), GFP_KERNEL);
8112 if (node_detected_dev) {
8113 node_detected_dev->dev = dev;
8114 list_add_tail(&node_detected_dev->list, &all_detected_devices);
8115 } else {
8116 printk(KERN_CRIT "md: md_autodetect_dev: kzalloc failed"
8117 ", skipping dev(%d,%d)\n", MAJOR(dev), MINOR(dev));
8122 static void autostart_arrays(int part)
8124 mdk_rdev_t *rdev;
8125 struct detected_devices_node *node_detected_dev;
8126 dev_t dev;
8127 int i_scanned, i_passed;
8129 i_scanned = 0;
8130 i_passed = 0;
8132 printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
8134 while (!list_empty(&all_detected_devices) && i_scanned < INT_MAX) {
8135 i_scanned++;
8136 node_detected_dev = list_entry(all_detected_devices.next,
8137 struct detected_devices_node, list);
8138 list_del(&node_detected_dev->list);
8139 dev = node_detected_dev->dev;
8140 kfree(node_detected_dev);
8141 rdev = md_import_device(dev,0, 90);
8142 if (IS_ERR(rdev))
8143 continue;
8145 if (test_bit(Faulty, &rdev->flags)) {
8146 MD_BUG();
8147 continue;
8149 set_bit(AutoDetected, &rdev->flags);
8150 list_add(&rdev->same_set, &pending_raid_disks);
8151 i_passed++;
8154 printk(KERN_INFO "md: Scanned %d and added %d devices.\n",
8155 i_scanned, i_passed);
8157 autorun_devices(part);
8160 #endif /* !MODULE */
8162 static __exit void md_exit(void)
8164 mddev_t *mddev;
8165 struct list_head *tmp;
8167 blk_unregister_region(MKDEV(MD_MAJOR,0), 1U << MINORBITS);
8168 blk_unregister_region(MKDEV(mdp_major,0), 1U << MINORBITS);
8170 unregister_blkdev(MD_MAJOR,"md");
8171 unregister_blkdev(mdp_major, "mdp");
8172 unregister_reboot_notifier(&md_notifier);
8173 unregister_sysctl_table(raid_table_header);
8174 remove_proc_entry("mdstat", NULL);
8175 for_each_mddev(mddev, tmp) {
8176 export_array(mddev);
8177 mddev->hold_active = 0;
8179 destroy_workqueue(md_misc_wq);
8180 destroy_workqueue(md_wq);
8183 subsys_initcall(md_init);
8184 module_exit(md_exit)
8186 static int get_ro(char *buffer, struct kernel_param *kp)
8188 return sprintf(buffer, "%d", start_readonly);
8190 static int set_ro(const char *val, struct kernel_param *kp)
8192 char *e;
8193 int num = simple_strtoul(val, &e, 10);
8194 if (*val && (*e == '\0' || *e == '\n')) {
8195 start_readonly = num;
8196 return 0;
8198 return -EINVAL;
8201 module_param_call(start_ro, set_ro, get_ro, NULL, S_IRUSR|S_IWUSR);
8202 module_param(start_dirty_degraded, int, S_IRUGO|S_IWUSR);
8204 module_param_call(new_array, add_named_array, NULL, NULL, S_IWUSR);
8206 EXPORT_SYMBOL(register_md_personality);
8207 EXPORT_SYMBOL(unregister_md_personality);
8208 EXPORT_SYMBOL(md_error);
8209 EXPORT_SYMBOL(md_done_sync);
8210 EXPORT_SYMBOL(md_write_start);
8211 EXPORT_SYMBOL(md_write_end);
8212 EXPORT_SYMBOL(md_register_thread);
8213 EXPORT_SYMBOL(md_unregister_thread);
8214 EXPORT_SYMBOL(md_wakeup_thread);
8215 EXPORT_SYMBOL(md_check_recovery);
8216 MODULE_LICENSE("GPL");
8217 MODULE_DESCRIPTION("MD RAID framework");
8218 MODULE_ALIAS("md");
8219 MODULE_ALIAS_BLOCKDEV_MAJOR(MD_MAJOR);