block: make blkdev_get/put() handle exclusive access
[linux-2.6.git] / drivers / md / md.c
1 /*
2    md.c : Multiple Devices driver for Linux
3           Copyright (C) 1998, 1999, 2000 Ingo Molnar
4
5      completely rewritten, based on the MD driver code from Marc Zyngier
6
7    Changes:
8
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>
16
17    - lots of fixes and improvements to the RAID1/RAID5 and generic
18      RAID code (such as request based resynchronization):
19
20      Neil Brown <neilb@cse.unsw.edu.au>.
21
22    - persistent bitmap code
23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
24
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.
29
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.
33 */
34
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"
56
57 #define DEBUG 0
58 #define dprintk(x...) ((void)(DEBUG && printk(x)))
59
60 #ifndef MODULE
61 static void autostart_arrays(int part);
62 #endif
63
64 static LIST_HEAD(pers_list);
65 static DEFINE_SPINLOCK(pers_lock);
66
67 static void md_print_devices(void);
68
69 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
70 static struct workqueue_struct *md_wq;
71 static struct workqueue_struct *md_misc_wq;
72
73 #define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
74
75 /*
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.
79  */
80 #define MD_DEFAULT_MAX_CORRECTED_READ_ERRORS 20
81 /*
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.
89  *
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}
92  */
93
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)
97 {
98         return mddev->sync_speed_min ?
99                 mddev->sync_speed_min : sysctl_speed_limit_min;
100 }
101
102 static inline int speed_max(mddev_t *mddev)
103 {
104         return mddev->sync_speed_max ?
105                 mddev->sync_speed_max : sysctl_speed_limit_max;
106 }
107
108 static struct ctl_table_header *raid_table_header;
109
110 static ctl_table raid_table[] = {
111         {
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,
117         },
118         {
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,
124         },
125         { }
126 };
127
128 static ctl_table raid_dir_table[] = {
129         {
130                 .procname       = "raid",
131                 .maxlen         = 0,
132                 .mode           = S_IRUGO|S_IXUGO,
133                 .child          = raid_table,
134         },
135         { }
136 };
137
138 static ctl_table raid_root_table[] = {
139         {
140                 .procname       = "dev",
141                 .maxlen         = 0,
142                 .mode           = 0555,
143                 .child          = raid_dir_table,
144         },
145         {  }
146 };
147
148 static const struct block_device_operations md_fops;
149
150 static int start_readonly;
151
152 /* bio_clone_mddev
153  * like bio_clone, but with a local bio set
154  */
155
156 static void mddev_bio_destructor(struct bio *bio)
157 {
158         mddev_t *mddev, **mddevp;
159
160         mddevp = (void*)bio;
161         mddev = mddevp[-1];
162
163         bio_free(bio, mddev->bio_set);
164 }
165
166 struct bio *bio_alloc_mddev(gfp_t gfp_mask, int nr_iovecs,
167                             mddev_t *mddev)
168 {
169         struct bio *b;
170         mddev_t **mddevp;
171
172         if (!mddev || !mddev->bio_set)
173                 return bio_alloc(gfp_mask, nr_iovecs);
174
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;
183 }
184 EXPORT_SYMBOL_GPL(bio_alloc_mddev);
185
186 struct bio *bio_clone_mddev(struct bio *bio, gfp_t gfp_mask,
187                             mddev_t *mddev)
188 {
189         struct bio *b;
190         mddev_t **mddevp;
191
192         if (!mddev || !mddev->bio_set)
193                 return bio_clone(bio, gfp_mask);
194
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;
205
206                 ret = bio_integrity_clone(b, bio, gfp_mask, mddev->bio_set);
207
208                 if (ret < 0) {
209                         bio_put(b);
210                         return NULL;
211                 }
212         }
213
214         return b;
215 }
216 EXPORT_SYMBOL_GPL(bio_clone_mddev);
217
218 /*
219  * We have a system wide 'event count' that is incremented
220  * on any 'interesting' event, and readers of /proc/mdstat
221  * can use 'poll' or 'select' to find out when the event
222  * count increases.
223  *
224  * Events are:
225  *  start array, stop array, error, add device, remove device,
226  *  start build, activate spare
227  */
228 static DECLARE_WAIT_QUEUE_HEAD(md_event_waiters);
229 static atomic_t md_event_count;
230 void md_new_event(mddev_t *mddev)
231 {
232         atomic_inc(&md_event_count);
233         wake_up(&md_event_waiters);
234 }
235 EXPORT_SYMBOL_GPL(md_new_event);
236
237 /* Alternate version that can be called from interrupts
238  * when calling sysfs_notify isn't needed.
239  */
240 static void md_new_event_inintr(mddev_t *mddev)
241 {
242         atomic_inc(&md_event_count);
243         wake_up(&md_event_waiters);
244 }
245
246 /*
247  * Enables to iterate over all existing md arrays
248  * all_mddevs_lock protects this list.
249  */
250 static LIST_HEAD(all_mddevs);
251 static DEFINE_SPINLOCK(all_mddevs_lock);
252
253
254 /*
255  * iterates through all used mddevs in the system.
256  * We take care to grab the all_mddevs_lock whenever navigating
257  * the list, and to always hold a refcount when unlocked.
258  * Any code which breaks out of this loop while own
259  * a reference to the current mddev and must mddev_put it.
260  */
261 #define for_each_mddev(mddev,tmp)                                       \
262                                                                         \
263         for (({ spin_lock(&all_mddevs_lock);                            \
264                 tmp = all_mddevs.next;                                  \
265                 mddev = NULL;});                                        \
266              ({ if (tmp != &all_mddevs)                                 \
267                         mddev_get(list_entry(tmp, mddev_t, all_mddevs));\
268                 spin_unlock(&all_mddevs_lock);                          \
269                 if (mddev) mddev_put(mddev);                            \
270                 mddev = list_entry(tmp, mddev_t, all_mddevs);           \
271                 tmp != &all_mddevs;});                                  \
272              ({ spin_lock(&all_mddevs_lock);                            \
273                 tmp = tmp->next;})                                      \
274                 )
275
276
277 /* Rather than calling directly into the personality make_request function,
278  * IO requests come here first so that we can check if the device is
279  * being suspended pending a reconfiguration.
280  * We hold a refcount over the call to ->make_request.  By the time that
281  * call has finished, the bio has been linked into some internal structure
282  * and so is visible to ->quiesce(), so we don't need the refcount any more.
283  */
284 static int md_make_request(struct request_queue *q, struct bio *bio)
285 {
286         const int rw = bio_data_dir(bio);
287         mddev_t *mddev = q->queuedata;
288         int rv;
289         int cpu;
290
291         if (mddev == NULL || mddev->pers == NULL) {
292                 bio_io_error(bio);
293                 return 0;
294         }
295         rcu_read_lock();
296         if (mddev->suspended) {
297                 DEFINE_WAIT(__wait);
298                 for (;;) {
299                         prepare_to_wait(&mddev->sb_wait, &__wait,
300                                         TASK_UNINTERRUPTIBLE);
301                         if (!mddev->suspended)
302                                 break;
303                         rcu_read_unlock();
304                         schedule();
305                         rcu_read_lock();
306                 }
307                 finish_wait(&mddev->sb_wait, &__wait);
308         }
309         atomic_inc(&mddev->active_io);
310         rcu_read_unlock();
311
312         rv = mddev->pers->make_request(mddev, bio);
313
314         cpu = part_stat_lock();
315         part_stat_inc(cpu, &mddev->gendisk->part0, ios[rw]);
316         part_stat_add(cpu, &mddev->gendisk->part0, sectors[rw],
317                       bio_sectors(bio));
318         part_stat_unlock();
319
320         if (atomic_dec_and_test(&mddev->active_io) && mddev->suspended)
321                 wake_up(&mddev->sb_wait);
322
323         return rv;
324 }
325
326 /* mddev_suspend makes sure no new requests are submitted
327  * to the device, and that any requests that have been submitted
328  * are completely handled.
329  * Once ->stop is called and completes, the module will be completely
330  * unused.
331  */
332 void mddev_suspend(mddev_t *mddev)
333 {
334         BUG_ON(mddev->suspended);
335         mddev->suspended = 1;
336         synchronize_rcu();
337         wait_event(mddev->sb_wait, atomic_read(&mddev->active_io) == 0);
338         mddev->pers->quiesce(mddev, 1);
339 }
340 EXPORT_SYMBOL_GPL(mddev_suspend);
341
342 void mddev_resume(mddev_t *mddev)
343 {
344         mddev->suspended = 0;
345         wake_up(&mddev->sb_wait);
346         mddev->pers->quiesce(mddev, 0);
347 }
348 EXPORT_SYMBOL_GPL(mddev_resume);
349
350 int mddev_congested(mddev_t *mddev, int bits)
351 {
352         return mddev->suspended;
353 }
354 EXPORT_SYMBOL(mddev_congested);
355
356 /*
357  * Generic flush handling for md
358  */
359
360 static void md_end_flush(struct bio *bio, int err)
361 {
362         mdk_rdev_t *rdev = bio->bi_private;
363         mddev_t *mddev = rdev->mddev;
364
365         rdev_dec_pending(rdev, mddev);
366
367         if (atomic_dec_and_test(&mddev->flush_pending)) {
368                 /* The pre-request flush has finished */
369                 queue_work(md_wq, &mddev->flush_work);
370         }
371         bio_put(bio);
372 }
373
374 static void submit_flushes(mddev_t *mddev)
375 {
376         mdk_rdev_t *rdev;
377
378         rcu_read_lock();
379         list_for_each_entry_rcu(rdev, &mddev->disks, same_set)
380                 if (rdev->raid_disk >= 0 &&
381                     !test_bit(Faulty, &rdev->flags)) {
382                         /* Take two references, one is dropped
383                          * when request finishes, one after
384                          * we reclaim rcu_read_lock
385                          */
386                         struct bio *bi;
387                         atomic_inc(&rdev->nr_pending);
388                         atomic_inc(&rdev->nr_pending);
389                         rcu_read_unlock();
390                         bi = bio_alloc_mddev(GFP_KERNEL, 0, mddev);
391                         bi->bi_end_io = md_end_flush;
392                         bi->bi_private = rdev;
393                         bi->bi_bdev = rdev->bdev;
394                         atomic_inc(&mddev->flush_pending);
395                         submit_bio(WRITE_FLUSH, bi);
396                         rcu_read_lock();
397                         rdev_dec_pending(rdev, mddev);
398                 }
399         rcu_read_unlock();
400 }
401
402 static void md_submit_flush_data(struct work_struct *ws)
403 {
404         mddev_t *mddev = container_of(ws, mddev_t, flush_work);
405         struct bio *bio = mddev->flush_bio;
406
407         atomic_set(&mddev->flush_pending, 1);
408
409         if (bio->bi_size == 0)
410                 /* an empty barrier - all done */
411                 bio_endio(bio, 0);
412         else {
413                 bio->bi_rw &= ~REQ_FLUSH;
414                 if (mddev->pers->make_request(mddev, bio))
415                         generic_make_request(bio);
416         }
417         if (atomic_dec_and_test(&mddev->flush_pending)) {
418                 mddev->flush_bio = NULL;
419                 wake_up(&mddev->sb_wait);
420         }
421 }
422
423 void md_flush_request(mddev_t *mddev, struct bio *bio)
424 {
425         spin_lock_irq(&mddev->write_lock);
426         wait_event_lock_irq(mddev->sb_wait,
427                             !mddev->flush_bio,
428                             mddev->write_lock, /*nothing*/);
429         mddev->flush_bio = bio;
430         spin_unlock_irq(&mddev->write_lock);
431
432         atomic_set(&mddev->flush_pending, 1);
433         INIT_WORK(&mddev->flush_work, md_submit_flush_data);
434
435         submit_flushes(mddev);
436
437         if (atomic_dec_and_test(&mddev->flush_pending))
438                 queue_work(md_wq, &mddev->flush_work);
439 }
440 EXPORT_SYMBOL(md_flush_request);
441
442 /* Support for plugging.
443  * This mirrors the plugging support in request_queue, but does not
444  * require having a whole queue
445  */
446 static void plugger_work(struct work_struct *work)
447 {
448         struct plug_handle *plug =
449                 container_of(work, struct plug_handle, unplug_work);
450         plug->unplug_fn(plug);
451 }
452 static void plugger_timeout(unsigned long data)
453 {
454         struct plug_handle *plug = (void *)data;
455         kblockd_schedule_work(NULL, &plug->unplug_work);
456 }
457 void plugger_init(struct plug_handle *plug,
458                   void (*unplug_fn)(struct plug_handle *))
459 {
460         plug->unplug_flag = 0;
461         plug->unplug_fn = unplug_fn;
462         init_timer(&plug->unplug_timer);
463         plug->unplug_timer.function = plugger_timeout;
464         plug->unplug_timer.data = (unsigned long)plug;
465         INIT_WORK(&plug->unplug_work, plugger_work);
466 }
467 EXPORT_SYMBOL_GPL(plugger_init);
468
469 void plugger_set_plug(struct plug_handle *plug)
470 {
471         if (!test_and_set_bit(PLUGGED_FLAG, &plug->unplug_flag))
472                 mod_timer(&plug->unplug_timer, jiffies + msecs_to_jiffies(3)+1);
473 }
474 EXPORT_SYMBOL_GPL(plugger_set_plug);
475
476 int plugger_remove_plug(struct plug_handle *plug)
477 {
478         if (test_and_clear_bit(PLUGGED_FLAG, &plug->unplug_flag)) {
479                 del_timer(&plug->unplug_timer);
480                 return 1;
481         } else
482                 return 0;
483 }
484 EXPORT_SYMBOL_GPL(plugger_remove_plug);
485
486
487 static inline mddev_t *mddev_get(mddev_t *mddev)
488 {
489         atomic_inc(&mddev->active);
490         return mddev;
491 }
492
493 static void mddev_delayed_delete(struct work_struct *ws);
494
495 static void mddev_put(mddev_t *mddev)
496 {
497         struct bio_set *bs = NULL;
498
499         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
500                 return;
501         if (!mddev->raid_disks && list_empty(&mddev->disks) &&
502             mddev->ctime == 0 && !mddev->hold_active) {
503                 /* Array is not configured at all, and not held active,
504                  * so destroy it */
505                 list_del(&mddev->all_mddevs);
506                 bs = mddev->bio_set;
507                 mddev->bio_set = NULL;
508                 if (mddev->gendisk) {
509                         /* We did a probe so need to clean up.  Call
510                          * queue_work inside the spinlock so that
511                          * flush_workqueue() after mddev_find will
512                          * succeed in waiting for the work to be done.
513                          */
514                         INIT_WORK(&mddev->del_work, mddev_delayed_delete);
515                         queue_work(md_misc_wq, &mddev->del_work);
516                 } else
517                         kfree(mddev);
518         }
519         spin_unlock(&all_mddevs_lock);
520         if (bs)
521                 bioset_free(bs);
522 }
523
524 void mddev_init(mddev_t *mddev)
525 {
526         mutex_init(&mddev->open_mutex);
527         mutex_init(&mddev->reconfig_mutex);
528         mutex_init(&mddev->bitmap_info.mutex);
529         INIT_LIST_HEAD(&mddev->disks);
530         INIT_LIST_HEAD(&mddev->all_mddevs);
531         init_timer(&mddev->safemode_timer);
532         atomic_set(&mddev->active, 1);
533         atomic_set(&mddev->openers, 0);
534         atomic_set(&mddev->active_io, 0);
535         spin_lock_init(&mddev->write_lock);
536         atomic_set(&mddev->flush_pending, 0);
537         init_waitqueue_head(&mddev->sb_wait);
538         init_waitqueue_head(&mddev->recovery_wait);
539         mddev->reshape_position = MaxSector;
540         mddev->resync_min = 0;
541         mddev->resync_max = MaxSector;
542         mddev->level = LEVEL_NONE;
543 }
544 EXPORT_SYMBOL_GPL(mddev_init);
545
546 static mddev_t * mddev_find(dev_t unit)
547 {
548         mddev_t *mddev, *new = NULL;
549
550  retry:
551         spin_lock(&all_mddevs_lock);
552
553         if (unit) {
554                 list_for_each_entry(mddev, &all_mddevs, all_mddevs)
555                         if (mddev->unit == unit) {
556                                 mddev_get(mddev);
557                                 spin_unlock(&all_mddevs_lock);
558                                 kfree(new);
559                                 return mddev;
560                         }
561
562                 if (new) {
563                         list_add(&new->all_mddevs, &all_mddevs);
564                         spin_unlock(&all_mddevs_lock);
565                         new->hold_active = UNTIL_IOCTL;
566                         return new;
567                 }
568         } else if (new) {
569                 /* find an unused unit number */
570                 static int next_minor = 512;
571                 int start = next_minor;
572                 int is_free = 0;
573                 int dev = 0;
574                 while (!is_free) {
575                         dev = MKDEV(MD_MAJOR, next_minor);
576                         next_minor++;
577                         if (next_minor > MINORMASK)
578                                 next_minor = 0;
579                         if (next_minor == start) {
580                                 /* Oh dear, all in use. */
581                                 spin_unlock(&all_mddevs_lock);
582                                 kfree(new);
583                                 return NULL;
584                         }
585                                 
586                         is_free = 1;
587                         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
588                                 if (mddev->unit == dev) {
589                                         is_free = 0;
590                                         break;
591                                 }
592                 }
593                 new->unit = dev;
594                 new->md_minor = MINOR(dev);
595                 new->hold_active = UNTIL_STOP;
596                 list_add(&new->all_mddevs, &all_mddevs);
597                 spin_unlock(&all_mddevs_lock);
598                 return new;
599         }
600         spin_unlock(&all_mddevs_lock);
601
602         new = kzalloc(sizeof(*new), GFP_KERNEL);
603         if (!new)
604                 return NULL;
605
606         new->unit = unit;
607         if (MAJOR(unit) == MD_MAJOR)
608                 new->md_minor = MINOR(unit);
609         else
610                 new->md_minor = MINOR(unit) >> MdpMinorShift;
611
612         mddev_init(new);
613
614         goto retry;
615 }
616
617 static inline int mddev_lock(mddev_t * mddev)
618 {
619         return mutex_lock_interruptible(&mddev->reconfig_mutex);
620 }
621
622 static inline int mddev_is_locked(mddev_t *mddev)
623 {
624         return mutex_is_locked(&mddev->reconfig_mutex);
625 }
626
627 static inline int mddev_trylock(mddev_t * mddev)
628 {
629         return mutex_trylock(&mddev->reconfig_mutex);
630 }
631
632 static struct attribute_group md_redundancy_group;
633
634 static void mddev_unlock(mddev_t * mddev)
635 {
636         if (mddev->to_remove) {
637                 /* These cannot be removed under reconfig_mutex as
638                  * an access to the files will try to take reconfig_mutex
639                  * while holding the file unremovable, which leads to
640                  * a deadlock.
641                  * So hold set sysfs_active while the remove in happeing,
642                  * and anything else which might set ->to_remove or my
643                  * otherwise change the sysfs namespace will fail with
644                  * -EBUSY if sysfs_active is still set.
645                  * We set sysfs_active under reconfig_mutex and elsewhere
646                  * test it under the same mutex to ensure its correct value
647                  * is seen.
648                  */
649                 struct attribute_group *to_remove = mddev->to_remove;
650                 mddev->to_remove = NULL;
651                 mddev->sysfs_active = 1;
652                 mutex_unlock(&mddev->reconfig_mutex);
653
654                 if (mddev->kobj.sd) {
655                         if (to_remove != &md_redundancy_group)
656                                 sysfs_remove_group(&mddev->kobj, to_remove);
657                         if (mddev->pers == NULL ||
658                             mddev->pers->sync_request == NULL) {
659                                 sysfs_remove_group(&mddev->kobj, &md_redundancy_group);
660                                 if (mddev->sysfs_action)
661                                         sysfs_put(mddev->sysfs_action);
662                                 mddev->sysfs_action = NULL;
663                         }
664                 }
665                 mddev->sysfs_active = 0;
666         } else
667                 mutex_unlock(&mddev->reconfig_mutex);
668
669         md_wakeup_thread(mddev->thread);
670 }
671
672 static mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
673 {
674         mdk_rdev_t *rdev;
675
676         list_for_each_entry(rdev, &mddev->disks, same_set)
677                 if (rdev->desc_nr == nr)
678                         return rdev;
679
680         return NULL;
681 }
682
683 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
684 {
685         mdk_rdev_t *rdev;
686
687         list_for_each_entry(rdev, &mddev->disks, same_set)
688                 if (rdev->bdev->bd_dev == dev)
689                         return rdev;
690
691         return NULL;
692 }
693
694 static struct mdk_personality *find_pers(int level, char *clevel)
695 {
696         struct mdk_personality *pers;
697         list_for_each_entry(pers, &pers_list, list) {
698                 if (level != LEVEL_NONE && pers->level == level)
699                         return pers;
700                 if (strcmp(pers->name, clevel)==0)
701                         return pers;
702         }
703         return NULL;
704 }
705
706 /* return the offset of the super block in 512byte sectors */
707 static inline sector_t calc_dev_sboffset(struct block_device *bdev)
708 {
709         sector_t num_sectors = bdev->bd_inode->i_size / 512;
710         return MD_NEW_SIZE_SECTORS(num_sectors);
711 }
712
713 static int alloc_disk_sb(mdk_rdev_t * rdev)
714 {
715         if (rdev->sb_page)
716                 MD_BUG();
717
718         rdev->sb_page = alloc_page(GFP_KERNEL);
719         if (!rdev->sb_page) {
720                 printk(KERN_ALERT "md: out of memory.\n");
721                 return -ENOMEM;
722         }
723
724         return 0;
725 }
726
727 static void free_disk_sb(mdk_rdev_t * rdev)
728 {
729         if (rdev->sb_page) {
730                 put_page(rdev->sb_page);
731                 rdev->sb_loaded = 0;
732                 rdev->sb_page = NULL;
733                 rdev->sb_start = 0;
734                 rdev->sectors = 0;
735         }
736 }
737
738
739 static void super_written(struct bio *bio, int error)
740 {
741         mdk_rdev_t *rdev = bio->bi_private;
742         mddev_t *mddev = rdev->mddev;
743
744         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags)) {
745                 printk("md: super_written gets error=%d, uptodate=%d\n",
746                        error, test_bit(BIO_UPTODATE, &bio->bi_flags));
747                 WARN_ON(test_bit(BIO_UPTODATE, &bio->bi_flags));
748                 md_error(mddev, rdev);
749         }
750
751         if (atomic_dec_and_test(&mddev->pending_writes))
752                 wake_up(&mddev->sb_wait);
753         bio_put(bio);
754 }
755
756 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
757                    sector_t sector, int size, struct page *page)
758 {
759         /* write first size bytes of page to sector of rdev
760          * Increment mddev->pending_writes before returning
761          * and decrement it on completion, waking up sb_wait
762          * if zero is reached.
763          * If an error occurred, call md_error
764          */
765         struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, mddev);
766
767         bio->bi_bdev = rdev->bdev;
768         bio->bi_sector = sector;
769         bio_add_page(bio, page, size, 0);
770         bio->bi_private = rdev;
771         bio->bi_end_io = super_written;
772
773         atomic_inc(&mddev->pending_writes);
774         submit_bio(REQ_WRITE | REQ_SYNC | REQ_UNPLUG | REQ_FLUSH | REQ_FUA,
775                    bio);
776 }
777
778 void md_super_wait(mddev_t *mddev)
779 {
780         /* wait for all superblock writes that were scheduled to complete */
781         DEFINE_WAIT(wq);
782         for(;;) {
783                 prepare_to_wait(&mddev->sb_wait, &wq, TASK_UNINTERRUPTIBLE);
784                 if (atomic_read(&mddev->pending_writes)==0)
785                         break;
786                 schedule();
787         }
788         finish_wait(&mddev->sb_wait, &wq);
789 }
790
791 static void bi_complete(struct bio *bio, int error)
792 {
793         complete((struct completion*)bio->bi_private);
794 }
795
796 int sync_page_io(mdk_rdev_t *rdev, sector_t sector, int size,
797                  struct page *page, int rw)
798 {
799         struct bio *bio = bio_alloc_mddev(GFP_NOIO, 1, rdev->mddev);
800         struct completion event;
801         int ret;
802
803         rw |= REQ_SYNC | REQ_UNPLUG;
804
805         bio->bi_bdev = rdev->bdev;
806         bio->bi_sector = sector;
807         bio_add_page(bio, page, size, 0);
808         init_completion(&event);
809         bio->bi_private = &event;
810         bio->bi_end_io = bi_complete;
811         submit_bio(rw, bio);
812         wait_for_completion(&event);
813
814         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
815         bio_put(bio);
816         return ret;
817 }
818 EXPORT_SYMBOL_GPL(sync_page_io);
819
820 static int read_disk_sb(mdk_rdev_t * rdev, int size)
821 {
822         char b[BDEVNAME_SIZE];
823         if (!rdev->sb_page) {
824                 MD_BUG();
825                 return -EINVAL;
826         }
827         if (rdev->sb_loaded)
828                 return 0;
829
830
831         if (!sync_page_io(rdev, rdev->sb_start, size, rdev->sb_page, READ))
832                 goto fail;
833         rdev->sb_loaded = 1;
834         return 0;
835
836 fail:
837         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
838                 bdevname(rdev->bdev,b));
839         return -EINVAL;
840 }
841
842 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
843 {
844         return  sb1->set_uuid0 == sb2->set_uuid0 &&
845                 sb1->set_uuid1 == sb2->set_uuid1 &&
846                 sb1->set_uuid2 == sb2->set_uuid2 &&
847                 sb1->set_uuid3 == sb2->set_uuid3;
848 }
849
850 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
851 {
852         int ret;
853         mdp_super_t *tmp1, *tmp2;
854
855         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
856         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
857
858         if (!tmp1 || !tmp2) {
859                 ret = 0;
860                 printk(KERN_INFO "md.c sb_equal(): failed to allocate memory!\n");
861                 goto abort;
862         }
863
864         *tmp1 = *sb1;
865         *tmp2 = *sb2;
866
867         /*
868          * nr_disks is not constant
869          */
870         tmp1->nr_disks = 0;
871         tmp2->nr_disks = 0;
872
873         ret = (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4) == 0);
874 abort:
875         kfree(tmp1);
876         kfree(tmp2);
877         return ret;
878 }
879
880
881 static u32 md_csum_fold(u32 csum)
882 {
883         csum = (csum & 0xffff) + (csum >> 16);
884         return (csum & 0xffff) + (csum >> 16);
885 }
886
887 static unsigned int calc_sb_csum(mdp_super_t * sb)
888 {
889         u64 newcsum = 0;
890         u32 *sb32 = (u32*)sb;
891         int i;
892         unsigned int disk_csum, csum;
893
894         disk_csum = sb->sb_csum;
895         sb->sb_csum = 0;
896
897         for (i = 0; i < MD_SB_BYTES/4 ; i++)
898                 newcsum += sb32[i];
899         csum = (newcsum & 0xffffffff) + (newcsum>>32);
900
901
902 #ifdef CONFIG_ALPHA
903         /* This used to use csum_partial, which was wrong for several
904          * reasons including that different results are returned on
905          * different architectures.  It isn't critical that we get exactly
906          * the same return value as before (we always csum_fold before
907          * testing, and that removes any differences).  However as we
908          * know that csum_partial always returned a 16bit value on
909          * alphas, do a fold to maximise conformity to previous behaviour.
910          */
911         sb->sb_csum = md_csum_fold(disk_csum);
912 #else
913         sb->sb_csum = disk_csum;
914 #endif
915         return csum;
916 }
917
918
919 /*
920  * Handle superblock details.
921  * We want to be able to handle multiple superblock formats
922  * so we have a common interface to them all, and an array of
923  * different handlers.
924  * We rely on user-space to write the initial superblock, and support
925  * reading and updating of superblocks.
926  * Interface methods are:
927  *   int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
928  *      loads and validates a superblock on dev.
929  *      if refdev != NULL, compare superblocks on both devices
930  *    Return:
931  *      0 - dev has a superblock that is compatible with refdev
932  *      1 - dev has a superblock that is compatible and newer than refdev
933  *          so dev should be used as the refdev in future
934  *     -EINVAL superblock incompatible or invalid
935  *     -othererror e.g. -EIO
936  *
937  *   int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
938  *      Verify that dev is acceptable into mddev.
939  *       The first time, mddev->raid_disks will be 0, and data from
940  *       dev should be merged in.  Subsequent calls check that dev
941  *       is new enough.  Return 0 or -EINVAL
942  *
943  *   void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
944  *     Update the superblock for rdev with data in mddev
945  *     This does not write to disc.
946  *
947  */
948
949 struct super_type  {
950         char                *name;
951         struct module       *owner;
952         int                 (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev,
953                                           int minor_version);
954         int                 (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
955         void                (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
956         unsigned long long  (*rdev_size_change)(mdk_rdev_t *rdev,
957                                                 sector_t num_sectors);
958 };
959
960 /*
961  * Check that the given mddev has no bitmap.
962  *
963  * This function is called from the run method of all personalities that do not
964  * support bitmaps. It prints an error message and returns non-zero if mddev
965  * has a bitmap. Otherwise, it returns 0.
966  *
967  */
968 int md_check_no_bitmap(mddev_t *mddev)
969 {
970         if (!mddev->bitmap_info.file && !mddev->bitmap_info.offset)
971                 return 0;
972         printk(KERN_ERR "%s: bitmaps are not supported for %s\n",
973                 mdname(mddev), mddev->pers->name);
974         return 1;
975 }
976 EXPORT_SYMBOL(md_check_no_bitmap);
977
978 /*
979  * load_super for 0.90.0 
980  */
981 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
982 {
983         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
984         mdp_super_t *sb;
985         int ret;
986
987         /*
988          * Calculate the position of the superblock (512byte sectors),
989          * it's at the end of the disk.
990          *
991          * It also happens to be a multiple of 4Kb.
992          */
993         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
994
995         ret = read_disk_sb(rdev, MD_SB_BYTES);
996         if (ret) return ret;
997
998         ret = -EINVAL;
999
1000         bdevname(rdev->bdev, b);
1001         sb = (mdp_super_t*)page_address(rdev->sb_page);
1002
1003         if (sb->md_magic != MD_SB_MAGIC) {
1004                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
1005                        b);
1006                 goto abort;
1007         }
1008
1009         if (sb->major_version != 0 ||
1010             sb->minor_version < 90 ||
1011             sb->minor_version > 91) {
1012                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
1013                         sb->major_version, sb->minor_version,
1014                         b);
1015                 goto abort;
1016         }
1017
1018         if (sb->raid_disks <= 0)
1019                 goto abort;
1020
1021         if (md_csum_fold(calc_sb_csum(sb)) != md_csum_fold(sb->sb_csum)) {
1022                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
1023                         b);
1024                 goto abort;
1025         }
1026
1027         rdev->preferred_minor = sb->md_minor;
1028         rdev->data_offset = 0;
1029         rdev->sb_size = MD_SB_BYTES;
1030
1031         if (sb->level == LEVEL_MULTIPATH)
1032                 rdev->desc_nr = -1;
1033         else
1034                 rdev->desc_nr = sb->this_disk.number;
1035
1036         if (!refdev) {
1037                 ret = 1;
1038         } else {
1039                 __u64 ev1, ev2;
1040                 mdp_super_t *refsb = (mdp_super_t*)page_address(refdev->sb_page);
1041                 if (!uuid_equal(refsb, sb)) {
1042                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
1043                                 b, bdevname(refdev->bdev,b2));
1044                         goto abort;
1045                 }
1046                 if (!sb_equal(refsb, sb)) {
1047                         printk(KERN_WARNING "md: %s has same UUID"
1048                                " but different superblock to %s\n",
1049                                b, bdevname(refdev->bdev, b2));
1050                         goto abort;
1051                 }
1052                 ev1 = md_event(sb);
1053                 ev2 = md_event(refsb);
1054                 if (ev1 > ev2)
1055                         ret = 1;
1056                 else 
1057                         ret = 0;
1058         }
1059         rdev->sectors = rdev->sb_start;
1060
1061         if (rdev->sectors < sb->size * 2 && sb->level > 1)
1062                 /* "this cannot possibly happen" ... */
1063                 ret = -EINVAL;
1064
1065  abort:
1066         return ret;
1067 }
1068
1069 /*
1070  * validate_super for 0.90.0
1071  */
1072 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1073 {
1074         mdp_disk_t *desc;
1075         mdp_super_t *sb = (mdp_super_t *)page_address(rdev->sb_page);
1076         __u64 ev1 = md_event(sb);
1077
1078         rdev->raid_disk = -1;
1079         clear_bit(Faulty, &rdev->flags);
1080         clear_bit(In_sync, &rdev->flags);
1081         clear_bit(WriteMostly, &rdev->flags);
1082
1083         if (mddev->raid_disks == 0) {
1084                 mddev->major_version = 0;
1085                 mddev->minor_version = sb->minor_version;
1086                 mddev->patch_version = sb->patch_version;
1087                 mddev->external = 0;
1088                 mddev->chunk_sectors = sb->chunk_size >> 9;
1089                 mddev->ctime = sb->ctime;
1090                 mddev->utime = sb->utime;
1091                 mddev->level = sb->level;
1092                 mddev->clevel[0] = 0;
1093                 mddev->layout = sb->layout;
1094                 mddev->raid_disks = sb->raid_disks;
1095                 mddev->dev_sectors = sb->size * 2;
1096                 mddev->events = ev1;
1097                 mddev->bitmap_info.offset = 0;
1098                 mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
1099
1100                 if (mddev->minor_version >= 91) {
1101                         mddev->reshape_position = sb->reshape_position;
1102                         mddev->delta_disks = sb->delta_disks;
1103                         mddev->new_level = sb->new_level;
1104                         mddev->new_layout = sb->new_layout;
1105                         mddev->new_chunk_sectors = sb->new_chunk >> 9;
1106                 } else {
1107                         mddev->reshape_position = MaxSector;
1108                         mddev->delta_disks = 0;
1109                         mddev->new_level = mddev->level;
1110                         mddev->new_layout = mddev->layout;
1111                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1112                 }
1113
1114                 if (sb->state & (1<<MD_SB_CLEAN))
1115                         mddev->recovery_cp = MaxSector;
1116                 else {
1117                         if (sb->events_hi == sb->cp_events_hi && 
1118                                 sb->events_lo == sb->cp_events_lo) {
1119                                 mddev->recovery_cp = sb->recovery_cp;
1120                         } else
1121                                 mddev->recovery_cp = 0;
1122                 }
1123
1124                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
1125                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
1126                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
1127                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
1128
1129                 mddev->max_disks = MD_SB_DISKS;
1130
1131                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
1132                     mddev->bitmap_info.file == NULL)
1133                         mddev->bitmap_info.offset =
1134                                 mddev->bitmap_info.default_offset;
1135
1136         } else if (mddev->pers == NULL) {
1137                 /* Insist on good event counter while assembling, except
1138                  * for spares (which don't need an event count) */
1139                 ++ev1;
1140                 if (sb->disks[rdev->desc_nr].state & (
1141                             (1<<MD_DISK_SYNC) | (1 << MD_DISK_ACTIVE)))
1142                         if (ev1 < mddev->events) 
1143                                 return -EINVAL;
1144         } else if (mddev->bitmap) {
1145                 /* if adding to array with a bitmap, then we can accept an
1146                  * older device ... but not too old.
1147                  */
1148                 if (ev1 < mddev->bitmap->events_cleared)
1149                         return 0;
1150         } else {
1151                 if (ev1 < mddev->events)
1152                         /* just a hot-add of a new device, leave raid_disk at -1 */
1153                         return 0;
1154         }
1155
1156         if (mddev->level != LEVEL_MULTIPATH) {
1157                 desc = sb->disks + rdev->desc_nr;
1158
1159                 if (desc->state & (1<<MD_DISK_FAULTY))
1160                         set_bit(Faulty, &rdev->flags);
1161                 else if (desc->state & (1<<MD_DISK_SYNC) /* &&
1162                             desc->raid_disk < mddev->raid_disks */) {
1163                         set_bit(In_sync, &rdev->flags);
1164                         rdev->raid_disk = desc->raid_disk;
1165                 } else if (desc->state & (1<<MD_DISK_ACTIVE)) {
1166                         /* active but not in sync implies recovery up to
1167                          * reshape position.  We don't know exactly where
1168                          * that is, so set to zero for now */
1169                         if (mddev->minor_version >= 91) {
1170                                 rdev->recovery_offset = 0;
1171                                 rdev->raid_disk = desc->raid_disk;
1172                         }
1173                 }
1174                 if (desc->state & (1<<MD_DISK_WRITEMOSTLY))
1175                         set_bit(WriteMostly, &rdev->flags);
1176         } else /* MULTIPATH are always insync */
1177                 set_bit(In_sync, &rdev->flags);
1178         return 0;
1179 }
1180
1181 /*
1182  * sync_super for 0.90.0
1183  */
1184 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1185 {
1186         mdp_super_t *sb;
1187         mdk_rdev_t *rdev2;
1188         int next_spare = mddev->raid_disks;
1189
1190
1191         /* make rdev->sb match mddev data..
1192          *
1193          * 1/ zero out disks
1194          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
1195          * 3/ any empty disks < next_spare become removed
1196          *
1197          * disks[0] gets initialised to REMOVED because
1198          * we cannot be sure from other fields if it has
1199          * been initialised or not.
1200          */
1201         int i;
1202         int active=0, working=0,failed=0,spare=0,nr_disks=0;
1203
1204         rdev->sb_size = MD_SB_BYTES;
1205
1206         sb = (mdp_super_t*)page_address(rdev->sb_page);
1207
1208         memset(sb, 0, sizeof(*sb));
1209
1210         sb->md_magic = MD_SB_MAGIC;
1211         sb->major_version = mddev->major_version;
1212         sb->patch_version = mddev->patch_version;
1213         sb->gvalid_words  = 0; /* ignored */
1214         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
1215         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
1216         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
1217         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
1218
1219         sb->ctime = mddev->ctime;
1220         sb->level = mddev->level;
1221         sb->size = mddev->dev_sectors / 2;
1222         sb->raid_disks = mddev->raid_disks;
1223         sb->md_minor = mddev->md_minor;
1224         sb->not_persistent = 0;
1225         sb->utime = mddev->utime;
1226         sb->state = 0;
1227         sb->events_hi = (mddev->events>>32);
1228         sb->events_lo = (u32)mddev->events;
1229
1230         if (mddev->reshape_position == MaxSector)
1231                 sb->minor_version = 90;
1232         else {
1233                 sb->minor_version = 91;
1234                 sb->reshape_position = mddev->reshape_position;
1235                 sb->new_level = mddev->new_level;
1236                 sb->delta_disks = mddev->delta_disks;
1237                 sb->new_layout = mddev->new_layout;
1238                 sb->new_chunk = mddev->new_chunk_sectors << 9;
1239         }
1240         mddev->minor_version = sb->minor_version;
1241         if (mddev->in_sync)
1242         {
1243                 sb->recovery_cp = mddev->recovery_cp;
1244                 sb->cp_events_hi = (mddev->events>>32);
1245                 sb->cp_events_lo = (u32)mddev->events;
1246                 if (mddev->recovery_cp == MaxSector)
1247                         sb->state = (1<< MD_SB_CLEAN);
1248         } else
1249                 sb->recovery_cp = 0;
1250
1251         sb->layout = mddev->layout;
1252         sb->chunk_size = mddev->chunk_sectors << 9;
1253
1254         if (mddev->bitmap && mddev->bitmap_info.file == NULL)
1255                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
1256
1257         sb->disks[0].state = (1<<MD_DISK_REMOVED);
1258         list_for_each_entry(rdev2, &mddev->disks, same_set) {
1259                 mdp_disk_t *d;
1260                 int desc_nr;
1261                 int is_active = test_bit(In_sync, &rdev2->flags);
1262
1263                 if (rdev2->raid_disk >= 0 &&
1264                     sb->minor_version >= 91)
1265                         /* we have nowhere to store the recovery_offset,
1266                          * but if it is not below the reshape_position,
1267                          * we can piggy-back on that.
1268                          */
1269                         is_active = 1;
1270                 if (rdev2->raid_disk < 0 ||
1271                     test_bit(Faulty, &rdev2->flags))
1272                         is_active = 0;
1273                 if (is_active)
1274                         desc_nr = rdev2->raid_disk;
1275                 else
1276                         desc_nr = next_spare++;
1277                 rdev2->desc_nr = desc_nr;
1278                 d = &sb->disks[rdev2->desc_nr];
1279                 nr_disks++;
1280                 d->number = rdev2->desc_nr;
1281                 d->major = MAJOR(rdev2->bdev->bd_dev);
1282                 d->minor = MINOR(rdev2->bdev->bd_dev);
1283                 if (is_active)
1284                         d->raid_disk = rdev2->raid_disk;
1285                 else
1286                         d->raid_disk = rdev2->desc_nr; /* compatibility */
1287                 if (test_bit(Faulty, &rdev2->flags))
1288                         d->state = (1<<MD_DISK_FAULTY);
1289                 else if (is_active) {
1290                         d->state = (1<<MD_DISK_ACTIVE);
1291                         if (test_bit(In_sync, &rdev2->flags))
1292                                 d->state |= (1<<MD_DISK_SYNC);
1293                         active++;
1294                         working++;
1295                 } else {
1296                         d->state = 0;
1297                         spare++;
1298                         working++;
1299                 }
1300                 if (test_bit(WriteMostly, &rdev2->flags))
1301                         d->state |= (1<<MD_DISK_WRITEMOSTLY);
1302         }
1303         /* now set the "removed" and "faulty" bits on any missing devices */
1304         for (i=0 ; i < mddev->raid_disks ; i++) {
1305                 mdp_disk_t *d = &sb->disks[i];
1306                 if (d->state == 0 && d->number == 0) {
1307                         d->number = i;
1308                         d->raid_disk = i;
1309                         d->state = (1<<MD_DISK_REMOVED);
1310                         d->state |= (1<<MD_DISK_FAULTY);
1311                         failed++;
1312                 }
1313         }
1314         sb->nr_disks = nr_disks;
1315         sb->active_disks = active;
1316         sb->working_disks = working;
1317         sb->failed_disks = failed;
1318         sb->spare_disks = spare;
1319
1320         sb->this_disk = sb->disks[rdev->desc_nr];
1321         sb->sb_csum = calc_sb_csum(sb);
1322 }
1323
1324 /*
1325  * rdev_size_change for 0.90.0
1326  */
1327 static unsigned long long
1328 super_90_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1329 {
1330         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1331                 return 0; /* component must fit device */
1332         if (rdev->mddev->bitmap_info.offset)
1333                 return 0; /* can't move bitmap */
1334         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
1335         if (!num_sectors || num_sectors > rdev->sb_start)
1336                 num_sectors = rdev->sb_start;
1337         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1338                        rdev->sb_page);
1339         md_super_wait(rdev->mddev);
1340         return num_sectors / 2; /* kB for sysfs */
1341 }
1342
1343
1344 /*
1345  * version 1 superblock
1346  */
1347
1348 static __le32 calc_sb_1_csum(struct mdp_superblock_1 * sb)
1349 {
1350         __le32 disk_csum;
1351         u32 csum;
1352         unsigned long long newcsum;
1353         int size = 256 + le32_to_cpu(sb->max_dev)*2;
1354         __le32 *isuper = (__le32*)sb;
1355         int i;
1356
1357         disk_csum = sb->sb_csum;
1358         sb->sb_csum = 0;
1359         newcsum = 0;
1360         for (i=0; size>=4; size -= 4 )
1361                 newcsum += le32_to_cpu(*isuper++);
1362
1363         if (size == 2)
1364                 newcsum += le16_to_cpu(*(__le16*) isuper);
1365
1366         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
1367         sb->sb_csum = disk_csum;
1368         return cpu_to_le32(csum);
1369 }
1370
1371 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
1372 {
1373         struct mdp_superblock_1 *sb;
1374         int ret;
1375         sector_t sb_start;
1376         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1377         int bmask;
1378
1379         /*
1380          * Calculate the position of the superblock in 512byte sectors.
1381          * It is always aligned to a 4K boundary and
1382          * depeding on minor_version, it can be:
1383          * 0: At least 8K, but less than 12K, from end of device
1384          * 1: At start of device
1385          * 2: 4K from start of device.
1386          */
1387         switch(minor_version) {
1388         case 0:
1389                 sb_start = rdev->bdev->bd_inode->i_size >> 9;
1390                 sb_start -= 8*2;
1391                 sb_start &= ~(sector_t)(4*2-1);
1392                 break;
1393         case 1:
1394                 sb_start = 0;
1395                 break;
1396         case 2:
1397                 sb_start = 8;
1398                 break;
1399         default:
1400                 return -EINVAL;
1401         }
1402         rdev->sb_start = sb_start;
1403
1404         /* superblock is rarely larger than 1K, but it can be larger,
1405          * and it is safe to read 4k, so we do that
1406          */
1407         ret = read_disk_sb(rdev, 4096);
1408         if (ret) return ret;
1409
1410
1411         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1412
1413         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
1414             sb->major_version != cpu_to_le32(1) ||
1415             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
1416             le64_to_cpu(sb->super_offset) != rdev->sb_start ||
1417             (le32_to_cpu(sb->feature_map) & ~MD_FEATURE_ALL) != 0)
1418                 return -EINVAL;
1419
1420         if (calc_sb_1_csum(sb) != sb->sb_csum) {
1421                 printk("md: invalid superblock checksum on %s\n",
1422                         bdevname(rdev->bdev,b));
1423                 return -EINVAL;
1424         }
1425         if (le64_to_cpu(sb->data_size) < 10) {
1426                 printk("md: data_size too small on %s\n",
1427                        bdevname(rdev->bdev,b));
1428                 return -EINVAL;
1429         }
1430
1431         rdev->preferred_minor = 0xffff;
1432         rdev->data_offset = le64_to_cpu(sb->data_offset);
1433         atomic_set(&rdev->corrected_errors, le32_to_cpu(sb->cnt_corrected_read));
1434
1435         rdev->sb_size = le32_to_cpu(sb->max_dev) * 2 + 256;
1436         bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1437         if (rdev->sb_size & bmask)
1438                 rdev->sb_size = (rdev->sb_size | bmask) + 1;
1439
1440         if (minor_version
1441             && rdev->data_offset < sb_start + (rdev->sb_size/512))
1442                 return -EINVAL;
1443
1444         if (sb->level == cpu_to_le32(LEVEL_MULTIPATH))
1445                 rdev->desc_nr = -1;
1446         else
1447                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
1448
1449         if (!refdev) {
1450                 ret = 1;
1451         } else {
1452                 __u64 ev1, ev2;
1453                 struct mdp_superblock_1 *refsb = 
1454                         (struct mdp_superblock_1*)page_address(refdev->sb_page);
1455
1456                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
1457                     sb->level != refsb->level ||
1458                     sb->layout != refsb->layout ||
1459                     sb->chunksize != refsb->chunksize) {
1460                         printk(KERN_WARNING "md: %s has strangely different"
1461                                 " superblock to %s\n",
1462                                 bdevname(rdev->bdev,b),
1463                                 bdevname(refdev->bdev,b2));
1464                         return -EINVAL;
1465                 }
1466                 ev1 = le64_to_cpu(sb->events);
1467                 ev2 = le64_to_cpu(refsb->events);
1468
1469                 if (ev1 > ev2)
1470                         ret = 1;
1471                 else
1472                         ret = 0;
1473         }
1474         if (minor_version)
1475                 rdev->sectors = (rdev->bdev->bd_inode->i_size >> 9) -
1476                         le64_to_cpu(sb->data_offset);
1477         else
1478                 rdev->sectors = rdev->sb_start;
1479         if (rdev->sectors < le64_to_cpu(sb->data_size))
1480                 return -EINVAL;
1481         rdev->sectors = le64_to_cpu(sb->data_size);
1482         if (le64_to_cpu(sb->size) > rdev->sectors)
1483                 return -EINVAL;
1484         return ret;
1485 }
1486
1487 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
1488 {
1489         struct mdp_superblock_1 *sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1490         __u64 ev1 = le64_to_cpu(sb->events);
1491
1492         rdev->raid_disk = -1;
1493         clear_bit(Faulty, &rdev->flags);
1494         clear_bit(In_sync, &rdev->flags);
1495         clear_bit(WriteMostly, &rdev->flags);
1496
1497         if (mddev->raid_disks == 0) {
1498                 mddev->major_version = 1;
1499                 mddev->patch_version = 0;
1500                 mddev->external = 0;
1501                 mddev->chunk_sectors = le32_to_cpu(sb->chunksize);
1502                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
1503                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
1504                 mddev->level = le32_to_cpu(sb->level);
1505                 mddev->clevel[0] = 0;
1506                 mddev->layout = le32_to_cpu(sb->layout);
1507                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
1508                 mddev->dev_sectors = le64_to_cpu(sb->size);
1509                 mddev->events = ev1;
1510                 mddev->bitmap_info.offset = 0;
1511                 mddev->bitmap_info.default_offset = 1024 >> 9;
1512                 
1513                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
1514                 memcpy(mddev->uuid, sb->set_uuid, 16);
1515
1516                 mddev->max_disks =  (4096-256)/2;
1517
1518                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_BITMAP_OFFSET) &&
1519                     mddev->bitmap_info.file == NULL )
1520                         mddev->bitmap_info.offset =
1521                                 (__s32)le32_to_cpu(sb->bitmap_offset);
1522
1523                 if ((le32_to_cpu(sb->feature_map) & MD_FEATURE_RESHAPE_ACTIVE)) {
1524                         mddev->reshape_position = le64_to_cpu(sb->reshape_position);
1525                         mddev->delta_disks = le32_to_cpu(sb->delta_disks);
1526                         mddev->new_level = le32_to_cpu(sb->new_level);
1527                         mddev->new_layout = le32_to_cpu(sb->new_layout);
1528                         mddev->new_chunk_sectors = le32_to_cpu(sb->new_chunk);
1529                 } else {
1530                         mddev->reshape_position = MaxSector;
1531                         mddev->delta_disks = 0;
1532                         mddev->new_level = mddev->level;
1533                         mddev->new_layout = mddev->layout;
1534                         mddev->new_chunk_sectors = mddev->chunk_sectors;
1535                 }
1536
1537         } else if (mddev->pers == NULL) {
1538                 /* Insist of good event counter while assembling, except for
1539                  * spares (which don't need an event count) */
1540                 ++ev1;
1541                 if (rdev->desc_nr >= 0 &&
1542                     rdev->desc_nr < le32_to_cpu(sb->max_dev) &&
1543                     le16_to_cpu(sb->dev_roles[rdev->desc_nr]) < 0xfffe)
1544                         if (ev1 < mddev->events)
1545                                 return -EINVAL;
1546         } else if (mddev->bitmap) {
1547                 /* If adding to array with a bitmap, then we can accept an
1548                  * older device, but not too old.
1549                  */
1550                 if (ev1 < mddev->bitmap->events_cleared)
1551                         return 0;
1552         } else {
1553                 if (ev1 < mddev->events)
1554                         /* just a hot-add of a new device, leave raid_disk at -1 */
1555                         return 0;
1556         }
1557         if (mddev->level != LEVEL_MULTIPATH) {
1558                 int role;
1559                 if (rdev->desc_nr < 0 ||
1560                     rdev->desc_nr >= le32_to_cpu(sb->max_dev)) {
1561                         role = 0xffff;
1562                         rdev->desc_nr = -1;
1563                 } else
1564                         role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
1565                 switch(role) {
1566                 case 0xffff: /* spare */
1567                         break;
1568                 case 0xfffe: /* faulty */
1569                         set_bit(Faulty, &rdev->flags);
1570                         break;
1571                 default:
1572                         if ((le32_to_cpu(sb->feature_map) &
1573                              MD_FEATURE_RECOVERY_OFFSET))
1574                                 rdev->recovery_offset = le64_to_cpu(sb->recovery_offset);
1575                         else
1576                                 set_bit(In_sync, &rdev->flags);
1577                         rdev->raid_disk = role;
1578                         break;
1579                 }
1580                 if (sb->devflags & WriteMostly1)
1581                         set_bit(WriteMostly, &rdev->flags);
1582         } else /* MULTIPATH are always insync */
1583                 set_bit(In_sync, &rdev->flags);
1584
1585         return 0;
1586 }
1587
1588 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
1589 {
1590         struct mdp_superblock_1 *sb;
1591         mdk_rdev_t *rdev2;
1592         int max_dev, i;
1593         /* make rdev->sb match mddev and rdev data. */
1594
1595         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1596
1597         sb->feature_map = 0;
1598         sb->pad0 = 0;
1599         sb->recovery_offset = cpu_to_le64(0);
1600         memset(sb->pad1, 0, sizeof(sb->pad1));
1601         memset(sb->pad2, 0, sizeof(sb->pad2));
1602         memset(sb->pad3, 0, sizeof(sb->pad3));
1603
1604         sb->utime = cpu_to_le64((__u64)mddev->utime);
1605         sb->events = cpu_to_le64(mddev->events);
1606         if (mddev->in_sync)
1607                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1608         else
1609                 sb->resync_offset = cpu_to_le64(0);
1610
1611         sb->cnt_corrected_read = cpu_to_le32(atomic_read(&rdev->corrected_errors));
1612
1613         sb->raid_disks = cpu_to_le32(mddev->raid_disks);
1614         sb->size = cpu_to_le64(mddev->dev_sectors);
1615         sb->chunksize = cpu_to_le32(mddev->chunk_sectors);
1616         sb->level = cpu_to_le32(mddev->level);
1617         sb->layout = cpu_to_le32(mddev->layout);
1618
1619         if (mddev->bitmap && mddev->bitmap_info.file == NULL) {
1620                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_info.offset);
1621                 sb->feature_map = cpu_to_le32(MD_FEATURE_BITMAP_OFFSET);
1622         }
1623
1624         if (rdev->raid_disk >= 0 &&
1625             !test_bit(In_sync, &rdev->flags)) {
1626                 sb->feature_map |=
1627                         cpu_to_le32(MD_FEATURE_RECOVERY_OFFSET);
1628                 sb->recovery_offset =
1629                         cpu_to_le64(rdev->recovery_offset);
1630         }
1631
1632         if (mddev->reshape_position != MaxSector) {
1633                 sb->feature_map |= cpu_to_le32(MD_FEATURE_RESHAPE_ACTIVE);
1634                 sb->reshape_position = cpu_to_le64(mddev->reshape_position);
1635                 sb->new_layout = cpu_to_le32(mddev->new_layout);
1636                 sb->delta_disks = cpu_to_le32(mddev->delta_disks);
1637                 sb->new_level = cpu_to_le32(mddev->new_level);
1638                 sb->new_chunk = cpu_to_le32(mddev->new_chunk_sectors);
1639         }
1640
1641         max_dev = 0;
1642         list_for_each_entry(rdev2, &mddev->disks, same_set)
1643                 if (rdev2->desc_nr+1 > max_dev)
1644                         max_dev = rdev2->desc_nr+1;
1645
1646         if (max_dev > le32_to_cpu(sb->max_dev)) {
1647                 int bmask;
1648                 sb->max_dev = cpu_to_le32(max_dev);
1649                 rdev->sb_size = max_dev * 2 + 256;
1650                 bmask = queue_logical_block_size(rdev->bdev->bd_disk->queue)-1;
1651                 if (rdev->sb_size & bmask)
1652                         rdev->sb_size = (rdev->sb_size | bmask) + 1;
1653         } else
1654                 max_dev = le32_to_cpu(sb->max_dev);
1655
1656         for (i=0; i<max_dev;i++)
1657                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1658         
1659         list_for_each_entry(rdev2, &mddev->disks, same_set) {
1660                 i = rdev2->desc_nr;
1661                 if (test_bit(Faulty, &rdev2->flags))
1662                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1663                 else if (test_bit(In_sync, &rdev2->flags))
1664                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1665                 else if (rdev2->raid_disk >= 0)
1666                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1667                 else
1668                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1669         }
1670
1671         sb->sb_csum = calc_sb_1_csum(sb);
1672 }
1673
1674 static unsigned long long
1675 super_1_rdev_size_change(mdk_rdev_t *rdev, sector_t num_sectors)
1676 {
1677         struct mdp_superblock_1 *sb;
1678         sector_t max_sectors;
1679         if (num_sectors && num_sectors < rdev->mddev->dev_sectors)
1680                 return 0; /* component must fit device */
1681         if (rdev->sb_start < rdev->data_offset) {
1682                 /* minor versions 1 and 2; superblock before data */
1683                 max_sectors = rdev->bdev->bd_inode->i_size >> 9;
1684                 max_sectors -= rdev->data_offset;
1685                 if (!num_sectors || num_sectors > max_sectors)
1686                         num_sectors = max_sectors;
1687         } else if (rdev->mddev->bitmap_info.offset) {
1688                 /* minor version 0 with bitmap we can't move */
1689                 return 0;
1690         } else {
1691                 /* minor version 0; superblock after data */
1692                 sector_t sb_start;
1693                 sb_start = (rdev->bdev->bd_inode->i_size >> 9) - 8*2;
1694                 sb_start &= ~(sector_t)(4*2 - 1);
1695                 max_sectors = rdev->sectors + sb_start - rdev->sb_start;
1696                 if (!num_sectors || num_sectors > max_sectors)
1697                         num_sectors = max_sectors;
1698                 rdev->sb_start = sb_start;
1699         }
1700         sb = (struct mdp_superblock_1 *) page_address(rdev->sb_page);
1701         sb->data_size = cpu_to_le64(num_sectors);
1702         sb->super_offset = rdev->sb_start;
1703         sb->sb_csum = calc_sb_1_csum(sb);
1704         md_super_write(rdev->mddev, rdev, rdev->sb_start, rdev->sb_size,
1705                        rdev->sb_page);
1706         md_super_wait(rdev->mddev);
1707         return num_sectors / 2; /* kB for sysfs */
1708 }
1709
1710 static struct super_type super_types[] = {
1711         [0] = {
1712                 .name   = "0.90.0",
1713                 .owner  = THIS_MODULE,
1714                 .load_super         = super_90_load,
1715                 .validate_super     = super_90_validate,
1716                 .sync_super         = super_90_sync,
1717                 .rdev_size_change   = super_90_rdev_size_change,
1718         },
1719         [1] = {
1720                 .name   = "md-1",
1721                 .owner  = THIS_MODULE,
1722                 .load_super         = super_1_load,
1723                 .validate_super     = super_1_validate,
1724                 .sync_super         = super_1_sync,
1725                 .rdev_size_change   = super_1_rdev_size_change,
1726         },
1727 };
1728
1729 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1730 {
1731         mdk_rdev_t *rdev, *rdev2;
1732
1733         rcu_read_lock();
1734         rdev_for_each_rcu(rdev, mddev1)
1735                 rdev_for_each_rcu(rdev2, mddev2)
1736                         if (rdev->bdev->bd_contains ==
1737                             rdev2->bdev->bd_contains) {
1738                                 rcu_read_unlock();
1739                                 return 1;
1740                         }
1741         rcu_read_unlock();
1742         return 0;
1743 }
1744
1745 static LIST_HEAD(pending_raid_disks);
1746
1747 /*
1748  * Try to register data integrity profile for an mddev
1749  *
1750  * This is called when an array is started and after a disk has been kicked
1751  * from the array. It only succeeds if all working and active component devices
1752  * are integrity capable with matching profiles.
1753  */
1754 int md_integrity_register(mddev_t *mddev)
1755 {
1756         mdk_rdev_t *rdev, *reference = NULL;
1757
1758         if (list_empty(&mddev->disks))
1759                 return 0; /* nothing to do */
1760         if (blk_get_integrity(mddev->gendisk))
1761                 return 0; /* already registered */
1762         list_for_each_entry(rdev, &mddev->disks, same_set) {
1763                 /* skip spares and non-functional disks */
1764                 if (test_bit(Faulty, &rdev->flags))
1765                         continue;
1766                 if (rdev->raid_disk < 0)
1767                         continue;
1768                 /*
1769                  * If at least one rdev is not integrity capable, we can not
1770                  * enable data integrity for the md device.
1771                  */
1772                 if (!bdev_get_integrity(rdev->bdev))
1773                         return -EINVAL;
1774                 if (!reference) {
1775                         /* Use the first rdev as the reference */
1776                         reference = rdev;
1777                         continue;
1778                 }
1779                 /* does this rdev's profile match the reference profile? */
1780                 if (blk_integrity_compare(reference->bdev->bd_disk,
1781                                 rdev->bdev->bd_disk) < 0)
1782                         return -EINVAL;
1783         }
1784         /*
1785          * All component devices are integrity capable and have matching
1786          * profiles, register the common profile for the md device.
1787          */
1788         if (blk_integrity_register(mddev->gendisk,
1789                         bdev_get_integrity(reference->bdev)) != 0) {
1790                 printk(KERN_ERR "md: failed to register integrity for %s\n",
1791                         mdname(mddev));
1792                 return -EINVAL;
1793         }
1794         printk(KERN_NOTICE "md: data integrity on %s enabled\n",
1795                 mdname(mddev));
1796         return 0;
1797 }
1798 EXPORT_SYMBOL(md_integrity_register);
1799
1800 /* Disable data integrity if non-capable/non-matching disk is being added */
1801 void md_integrity_add_rdev(mdk_rdev_t *rdev, mddev_t *mddev)
1802 {
1803         struct blk_integrity *bi_rdev = bdev_get_integrity(rdev->bdev);
1804         struct blk_integrity *bi_mddev = blk_get_integrity(mddev->gendisk);
1805
1806         if (!bi_mddev) /* nothing to do */
1807                 return;
1808         if (rdev->raid_disk < 0) /* skip spares */
1809                 return;
1810         if (bi_rdev && blk_integrity_compare(mddev->gendisk,
1811                                              rdev->bdev->bd_disk) >= 0)
1812                 return;
1813         printk(KERN_NOTICE "disabling data integrity on %s\n", mdname(mddev));
1814         blk_integrity_unregister(mddev->gendisk);
1815 }
1816 EXPORT_SYMBOL(md_integrity_add_rdev);
1817
1818 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1819 {
1820         char b[BDEVNAME_SIZE];
1821         struct kobject *ko;
1822         char *s;
1823         int err;
1824
1825         if (rdev->mddev) {
1826                 MD_BUG();
1827                 return -EINVAL;
1828         }
1829
1830         /* prevent duplicates */
1831         if (find_rdev(mddev, rdev->bdev->bd_dev))
1832                 return -EEXIST;
1833
1834         /* make sure rdev->sectors exceeds mddev->dev_sectors */
1835         if (rdev->sectors && (mddev->dev_sectors == 0 ||
1836                         rdev->sectors < mddev->dev_sectors)) {
1837                 if (mddev->pers) {
1838                         /* Cannot change size, so fail
1839                          * If mddev->level <= 0, then we don't care
1840                          * about aligning sizes (e.g. linear)
1841                          */
1842                         if (mddev->level > 0)
1843                                 return -ENOSPC;
1844                 } else
1845                         mddev->dev_sectors = rdev->sectors;
1846         }
1847
1848         /* Verify rdev->desc_nr is unique.
1849          * If it is -1, assign a free number, else
1850          * check number is not in use
1851          */
1852         if (rdev->desc_nr < 0) {
1853                 int choice = 0;
1854                 if (mddev->pers) choice = mddev->raid_disks;
1855                 while (find_rdev_nr(mddev, choice))
1856                         choice++;
1857                 rdev->desc_nr = choice;
1858         } else {
1859                 if (find_rdev_nr(mddev, rdev->desc_nr))
1860                         return -EBUSY;
1861         }
1862         if (mddev->max_disks && rdev->desc_nr >= mddev->max_disks) {
1863                 printk(KERN_WARNING "md: %s: array is limited to %d devices\n",
1864                        mdname(mddev), mddev->max_disks);
1865                 return -EBUSY;
1866         }
1867         bdevname(rdev->bdev,b);
1868         while ( (s=strchr(b, '/')) != NULL)
1869                 *s = '!';
1870
1871         rdev->mddev = mddev;
1872         printk(KERN_INFO "md: bind<%s>\n", b);
1873
1874         if ((err = kobject_add(&rdev->kobj, &mddev->kobj, "dev-%s", b)))
1875                 goto fail;
1876
1877         ko = &part_to_dev(rdev->bdev->bd_part)->kobj;
1878         if (sysfs_create_link(&rdev->kobj, ko, "block"))
1879                 /* failure here is OK */;
1880         rdev->sysfs_state = sysfs_get_dirent_safe(rdev->kobj.sd, "state");
1881
1882         list_add_rcu(&rdev->same_set, &mddev->disks);
1883         bd_link_disk_holder(rdev->bdev, mddev->gendisk);
1884
1885         /* May as well allow recovery to be retried once */
1886         mddev->recovery_disabled = 0;
1887
1888         return 0;
1889
1890  fail:
1891         printk(KERN_WARNING "md: failed to register dev-%s for %s\n",
1892                b, mdname(mddev));
1893         return err;
1894 }
1895
1896 static void md_delayed_delete(struct work_struct *ws)
1897 {
1898         mdk_rdev_t *rdev = container_of(ws, mdk_rdev_t, del_work);
1899         kobject_del(&rdev->kobj);
1900         kobject_put(&rdev->kobj);
1901 }
1902
1903 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
1904 {
1905         char b[BDEVNAME_SIZE];
1906         if (!rdev->mddev) {
1907                 MD_BUG();
1908                 return;
1909         }
1910         list_del_rcu(&rdev->same_set);
1911         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
1912         rdev->mddev = NULL;
1913         sysfs_remove_link(&rdev->kobj, "block");
1914         sysfs_put(rdev->sysfs_state);
1915         rdev->sysfs_state = NULL;
1916         /* We need to delay this, otherwise we can deadlock when
1917          * writing to 'remove' to "dev/state".  We also need
1918          * to delay it due to rcu usage.
1919          */
1920         synchronize_rcu();
1921         INIT_WORK(&rdev->del_work, md_delayed_delete);
1922         kobject_get(&rdev->kobj);
1923         queue_work(md_misc_wq, &rdev->del_work);
1924 }
1925
1926 /*
1927  * prevent the device from being mounted, repartitioned or
1928  * otherwise reused by a RAID array (or any other kernel
1929  * subsystem), by bd_claiming the device.
1930  */
1931 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev, int shared)
1932 {
1933         int err = 0;
1934         struct block_device *bdev;
1935         char b[BDEVNAME_SIZE];
1936
1937         bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE|FMODE_EXCL,
1938                               shared ? (mdk_rdev_t *)lock_rdev : rdev);
1939         if (IS_ERR(bdev)) {
1940                 printk(KERN_ERR "md: could not open %s.\n",
1941                         __bdevname(dev, b));
1942                 return PTR_ERR(bdev);
1943         }
1944         if (!shared)
1945                 set_bit(AllReserved, &rdev->flags);
1946         rdev->bdev = bdev;
1947         return err;
1948 }
1949
1950 static void unlock_rdev(mdk_rdev_t *rdev)
1951 {
1952         struct block_device *bdev = rdev->bdev;
1953         rdev->bdev = NULL;
1954         if (!bdev)
1955                 MD_BUG();
1956         blkdev_put(bdev, FMODE_READ|FMODE_WRITE|FMODE_EXCL);
1957 }
1958
1959 void md_autodetect_dev(dev_t dev);
1960
1961 static void export_rdev(mdk_rdev_t * rdev)
1962 {
1963         char b[BDEVNAME_SIZE];
1964         printk(KERN_INFO "md: export_rdev(%s)\n",
1965                 bdevname(rdev->bdev,b));
1966         if (rdev->mddev)
1967                 MD_BUG();
1968         free_disk_sb(rdev);
1969 #ifndef MODULE
1970         if (test_bit(AutoDetected, &rdev->flags))
1971                 md_autodetect_dev(rdev->bdev->bd_dev);
1972 #endif
1973         unlock_rdev(rdev);
1974         kobject_put(&rdev->kobj);
1975 }
1976
1977 static void kick_rdev_from_array(mdk_rdev_t * rdev)
1978 {
1979         unbind_rdev_from_array(rdev);
1980         export_rdev(rdev);
1981 }
1982
1983 static void export_array(mddev_t *mddev)
1984 {
1985         mdk_rdev_t *rdev, *tmp;
1986
1987         rdev_for_each(rdev, tmp, mddev) {
1988                 if (!rdev->mddev) {
1989                         MD_BUG();
1990                         continue;
1991                 }
1992                 kick_rdev_from_array(rdev);
1993         }
1994         if (!list_empty(&mddev->disks))
1995                 MD_BUG();
1996         mddev->raid_disks = 0;
1997         mddev->major_version = 0;
1998 }
1999
2000 static void print_desc(mdp_disk_t *desc)
2001 {
2002         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
2003                 desc->major,desc->minor,desc->raid_disk,desc->state);
2004 }
2005
2006 static void print_sb_90(mdp_super_t *sb)
2007 {
2008         int i;
2009
2010         printk(KERN_INFO 
2011                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
2012                 sb->major_version, sb->minor_version, sb->patch_version,
2013                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
2014                 sb->ctime);
2015         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
2016                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
2017                 sb->md_minor, sb->layout, sb->chunk_size);
2018         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
2019                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
2020                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
2021                 sb->failed_disks, sb->spare_disks,
2022                 sb->sb_csum, (unsigned long)sb->events_lo);
2023
2024         printk(KERN_INFO);
2025         for (i = 0; i < MD_SB_DISKS; i++) {
2026                 mdp_disk_t *desc;
2027
2028                 desc = sb->disks + i;
2029                 if (desc->number || desc->major || desc->minor ||
2030                     desc->raid_disk || (desc->state && (desc->state != 4))) {
2031                         printk("     D %2d: ", i);
2032                         print_desc(desc);
2033                 }
2034         }
2035         printk(KERN_INFO "md:     THIS: ");
2036         print_desc(&sb->this_disk);
2037 }
2038
2039 static void print_sb_1(struct mdp_superblock_1 *sb)
2040 {
2041         __u8 *uuid;
2042
2043         uuid = sb->set_uuid;
2044         printk(KERN_INFO
2045                "md:  SB: (V:%u) (F:0x%08x) Array-ID:<%pU>\n"
2046                "md:    Name: \"%s\" CT:%llu\n",
2047                 le32_to_cpu(sb->major_version),
2048                 le32_to_cpu(sb->feature_map),
2049                 uuid,
2050                 sb->set_name,
2051                 (unsigned long long)le64_to_cpu(sb->ctime)
2052                        & MD_SUPERBLOCK_1_TIME_SEC_MASK);
2053
2054         uuid = sb->device_uuid;
2055         printk(KERN_INFO
2056                "md:       L%u SZ%llu RD:%u LO:%u CS:%u DO:%llu DS:%llu SO:%llu"
2057                         " RO:%llu\n"
2058                "md:     Dev:%08x UUID: %pU\n"
2059                "md:       (F:0x%08x) UT:%llu Events:%llu ResyncOffset:%llu CSUM:0x%08x\n"
2060                "md:         (MaxDev:%u) \n",
2061                 le32_to_cpu(sb->level),
2062                 (unsigned long long)le64_to_cpu(sb->size),
2063                 le32_to_cpu(sb->raid_disks),
2064                 le32_to_cpu(sb->layout),
2065                 le32_to_cpu(sb->chunksize),
2066                 (unsigned long long)le64_to_cpu(sb->data_offset),
2067                 (unsigned long long)le64_to_cpu(sb->data_size),
2068                 (unsigned long long)le64_to_cpu(sb->super_offset),
2069                 (unsigned long long)le64_to_cpu(sb->recovery_offset),
2070                 le32_to_cpu(sb->dev_number),
2071                 uuid,
2072                 sb->devflags,
2073                 (unsigned long long)le64_to_cpu(sb->utime) & MD_SUPERBLOCK_1_TIME_SEC_MASK,
2074                 (unsigned long long)le64_to_cpu(sb->events),
2075                 (unsigned long long)le64_to_cpu(sb->resync_offset),
2076                 le32_to_cpu(sb->sb_csum),
2077                 le32_to_cpu(sb->max_dev)
2078                 );
2079 }
2080
2081 static void print_rdev(mdk_rdev_t *rdev, int major_version)
2082 {
2083         char b[BDEVNAME_SIZE];
2084         printk(KERN_INFO "md: rdev %s, Sect:%08llu F:%d S:%d DN:%u\n",
2085                 bdevname(rdev->bdev, b), (unsigned long long)rdev->sectors,
2086                 test_bit(Faulty, &rdev->flags), test_bit(In_sync, &rdev->flags),
2087                 rdev->desc_nr);
2088         if (rdev->sb_loaded) {
2089                 printk(KERN_INFO "md: rdev superblock (MJ:%d):\n", major_version);
2090                 switch (major_version) {
2091                 case 0:
2092                         print_sb_90((mdp_super_t*)page_address(rdev->sb_page));
2093                         break;
2094                 case 1:
2095                         print_sb_1((struct mdp_superblock_1 *)page_address(rdev->sb_page));
2096                         break;
2097                 }
2098         } else
2099                 printk(KERN_INFO "md: no rdev superblock!\n");
2100 }
2101
2102 static void md_print_devices(void)
2103 {
2104         struct list_head *tmp;
2105         mdk_rdev_t *rdev;
2106         mddev_t *mddev;
2107         char b[BDEVNAME_SIZE];
2108
2109         printk("\n");
2110         printk("md:     **********************************\n");
2111         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
2112         printk("md:     **********************************\n");
2113         for_each_mddev(mddev, tmp) {
2114
2115                 if (mddev->bitmap)
2116                         bitmap_print_sb(mddev->bitmap);
2117                 else
2118                         printk("%s: ", mdname(mddev));
2119                 list_for_each_entry(rdev, &mddev->disks, same_set)
2120                         printk("<%s>", bdevname(rdev->bdev,b));
2121                 printk("\n");
2122
2123                 list_for_each_entry(rdev, &mddev->disks, same_set)
2124                         print_rdev(rdev, mddev->major_version);
2125         }
2126         printk("md:     **********************************\n");
2127         printk("\n");
2128 }
2129
2130
2131 static void sync_sbs(mddev_t * mddev, int nospares)
2132 {
2133         /* Update each superblock (in-memory image), but
2134          * if we are allowed to, skip spares which already
2135          * have the right event counter, or have one earlier
2136          * (which would mean they aren't being marked as dirty
2137          * with the rest of the array)
2138          */
2139         mdk_rdev_t *rdev;
2140         list_for_each_entry(rdev, &mddev->disks, same_set) {
2141                 if (rdev->sb_events == mddev->events ||
2142                     (nospares &&
2143                      rdev->raid_disk < 0 &&
2144                      rdev->sb_events+1 == mddev->events)) {
2145                         /* Don't update this superblock */
2146                         rdev->sb_loaded = 2;
2147                 } else {
2148                         super_types[mddev->major_version].
2149                                 sync_super(mddev, rdev);
2150                         rdev->sb_loaded = 1;
2151                 }
2152         }
2153 }
2154
2155 static void md_update_sb(mddev_t * mddev, int force_change)
2156 {
2157         mdk_rdev_t *rdev;
2158         int sync_req;
2159         int nospares = 0;
2160
2161 repeat:
2162         /* First make sure individual recovery_offsets are correct */
2163         list_for_each_entry(rdev, &mddev->disks, same_set) {
2164                 if (rdev->raid_disk >= 0 &&
2165                     mddev->delta_disks >= 0 &&
2166                     !test_bit(In_sync, &rdev->flags) &&
2167                     mddev->curr_resync_completed > rdev->recovery_offset)
2168                                 rdev->recovery_offset = mddev->curr_resync_completed;
2169
2170         }       
2171         if (!mddev->persistent) {
2172                 clear_bit(MD_CHANGE_CLEAN, &mddev->flags);
2173                 clear_bit(MD_CHANGE_DEVS, &mddev->flags);
2174                 if (!mddev->external)
2175                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2176                 wake_up(&mddev->sb_wait);
2177                 return;
2178         }
2179
2180         spin_lock_irq(&mddev->write_lock);
2181
2182         mddev->utime = get_seconds();
2183
2184         if (test_and_clear_bit(MD_CHANGE_DEVS, &mddev->flags))
2185                 force_change = 1;
2186         if (test_and_clear_bit(MD_CHANGE_CLEAN, &mddev->flags))
2187                 /* just a clean<-> dirty transition, possibly leave spares alone,
2188                  * though if events isn't the right even/odd, we will have to do
2189                  * spares after all
2190                  */
2191                 nospares = 1;
2192         if (force_change)
2193                 nospares = 0;
2194         if (mddev->degraded)
2195                 /* If the array is degraded, then skipping spares is both
2196                  * dangerous and fairly pointless.
2197                  * Dangerous because a device that was removed from the array
2198                  * might have a event_count that still looks up-to-date,
2199                  * so it can be re-added without a resync.
2200                  * Pointless because if there are any spares to skip,
2201                  * then a recovery will happen and soon that array won't
2202                  * be degraded any more and the spare can go back to sleep then.
2203                  */
2204                 nospares = 0;
2205
2206         sync_req = mddev->in_sync;
2207
2208         /* If this is just a dirty<->clean transition, and the array is clean
2209          * and 'events' is odd, we can roll back to the previous clean state */
2210         if (nospares
2211             && (mddev->in_sync && mddev->recovery_cp == MaxSector)
2212             && mddev->can_decrease_events
2213             && mddev->events != 1) {
2214                 mddev->events--;
2215                 mddev->can_decrease_events = 0;
2216         } else {
2217                 /* otherwise we have to go forward and ... */
2218                 mddev->events ++;
2219                 mddev->can_decrease_events = nospares;
2220         }
2221
2222         if (!mddev->events) {
2223                 /*
2224                  * oops, this 64-bit counter should never wrap.
2225                  * Either we are in around ~1 trillion A.C., assuming
2226                  * 1 reboot per second, or we have a bug:
2227                  */
2228                 MD_BUG();
2229                 mddev->events --;
2230         }
2231         sync_sbs(mddev, nospares);
2232         spin_unlock_irq(&mddev->write_lock);
2233
2234         dprintk(KERN_INFO 
2235                 "md: updating %s RAID superblock on device (in sync %d)\n",
2236                 mdname(mddev),mddev->in_sync);
2237
2238         bitmap_update_sb(mddev->bitmap);
2239         list_for_each_entry(rdev, &mddev->disks, same_set) {
2240                 char b[BDEVNAME_SIZE];
2241                 dprintk(KERN_INFO "md: ");
2242                 if (rdev->sb_loaded != 1)
2243                         continue; /* no noise on spare devices */
2244                 if (test_bit(Faulty, &rdev->flags))
2245                         dprintk("(skipping faulty ");
2246
2247                 dprintk("%s ", bdevname(rdev->bdev,b));
2248                 if (!test_bit(Faulty, &rdev->flags)) {
2249                         md_super_write(mddev,rdev,
2250                                        rdev->sb_start, rdev->sb_size,
2251                                        rdev->sb_page);
2252                         dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
2253                                 bdevname(rdev->bdev,b),
2254                                 (unsigned long long)rdev->sb_start);
2255                         rdev->sb_events = mddev->events;
2256
2257                 } else
2258                         dprintk(")\n");
2259                 if (mddev->level == LEVEL_MULTIPATH)
2260                         /* only need to write one superblock... */
2261                         break;
2262         }
2263         md_super_wait(mddev);
2264         /* if there was a failure, MD_CHANGE_DEVS was set, and we re-write super */
2265
2266         spin_lock_irq(&mddev->write_lock);
2267         if (mddev->in_sync != sync_req ||
2268             test_bit(MD_CHANGE_DEVS, &mddev->flags)) {
2269                 /* have to write it out again */
2270                 spin_unlock_irq(&mddev->write_lock);
2271                 goto repeat;
2272         }
2273         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
2274         spin_unlock_irq(&mddev->write_lock);
2275         wake_up(&mddev->sb_wait);
2276         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
2277                 sysfs_notify(&mddev->kobj, NULL, "sync_completed");
2278
2279 }
2280
2281 /* words written to sysfs files may, or may not, be \n terminated.
2282  * We want to accept with case. For this we use cmd_match.
2283  */
2284 static int cmd_match(const char *cmd, const char *str)
2285 {
2286         /* See if cmd, written into a sysfs file, matches
2287          * str.  They must either be the same, or cmd can
2288          * have a trailing newline
2289          */
2290         while (*cmd && *str && *cmd == *str) {
2291                 cmd++;
2292                 str++;
2293         }
2294         if (*cmd == '\n')
2295                 cmd++;
2296         if (*str || *cmd)
2297                 return 0;
2298         return 1;
2299 }
2300
2301 struct rdev_sysfs_entry {
2302         struct attribute attr;
2303         ssize_t (*show)(mdk_rdev_t *, char *);
2304         ssize_t (*store)(mdk_rdev_t *, const char *, size_t);
2305 };
2306
2307 static ssize_t
2308 state_show(mdk_rdev_t *rdev, char *page)
2309 {
2310         char *sep = "";
2311         size_t len = 0;
2312
2313         if (test_bit(Faulty, &rdev->flags)) {
2314                 len+= sprintf(page+len, "%sfaulty",sep);
2315                 sep = ",";
2316         }
2317         if (test_bit(In_sync, &rdev->flags)) {
2318                 len += sprintf(page+len, "%sin_sync",sep);
2319                 sep = ",";
2320         }
2321         if (test_bit(WriteMostly, &rdev->flags)) {
2322                 len += sprintf(page+len, "%swrite_mostly",sep);
2323                 sep = ",";
2324         }
2325         if (test_bit(Blocked, &rdev->flags)) {
2326                 len += sprintf(page+len, "%sblocked", sep);
2327                 sep = ",";
2328         }
2329         if (!test_bit(Faulty, &rdev->flags) &&
2330             !test_bit(In_sync, &rdev->flags)) {
2331                 len += sprintf(page+len, "%sspare", sep);
2332                 sep = ",";
2333         }
2334         return len+sprintf(page+len, "\n");
2335 }
2336
2337 static ssize_t
2338 state_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2339 {
2340         /* can write
2341          *  faulty  - simulates and error
2342          *  remove  - disconnects the device
2343          *  writemostly - sets write_mostly
2344          *  -writemostly - clears write_mostly
2345          *  blocked - sets the Blocked flag
2346          *  -blocked - clears the Blocked flag
2347          *  insync - sets Insync providing device isn't active
2348          */
2349         int err = -EINVAL;
2350         if (cmd_match(buf, "faulty") && rdev->mddev->pers) {
2351                 md_error(rdev->mddev, rdev);
2352                 err = 0;
2353         } else if (cmd_match(buf, "remove")) {
2354                 if (rdev->raid_disk >= 0)
2355                         err = -EBUSY;
2356                 else {
2357                         mddev_t *mddev = rdev->mddev;
2358                         kick_rdev_from_array(rdev);
2359                         if (mddev->pers)
2360                                 md_update_sb(mddev, 1);
2361                         md_new_event(mddev);
2362                         err = 0;
2363                 }
2364         } else if (cmd_match(buf, "writemostly")) {
2365                 set_bit(WriteMostly, &rdev->flags);
2366                 err = 0;
2367         } else if (cmd_match(buf, "-writemostly")) {
2368                 clear_bit(WriteMostly, &rdev->flags);
2369                 err = 0;
2370         } else if (cmd_match(buf, "blocked")) {
2371                 set_bit(Blocked, &rdev->flags);
2372                 err = 0;
2373         } else if (cmd_match(buf, "-blocked")) {
2374                 clear_bit(Blocked, &rdev->flags);
2375                 wake_up(&rdev->blocked_wait);
2376                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2377                 md_wakeup_thread(rdev->mddev->thread);
2378
2379                 err = 0;
2380         } else if (cmd_match(buf, "insync") && rdev->raid_disk == -1) {
2381                 set_bit(In_sync, &rdev->flags);
2382                 err = 0;
2383         }
2384         if (!err)
2385                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2386         return err ? err : len;
2387 }
2388 static struct rdev_sysfs_entry rdev_state =
2389 __ATTR(state, S_IRUGO|S_IWUSR, state_show, state_store);
2390
2391 static ssize_t
2392 errors_show(mdk_rdev_t *rdev, char *page)
2393 {
2394         return sprintf(page, "%d\n", atomic_read(&rdev->corrected_errors));
2395 }
2396
2397 static ssize_t
2398 errors_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2399 {
2400         char *e;
2401         unsigned long n = simple_strtoul(buf, &e, 10);
2402         if (*buf && (*e == 0 || *e == '\n')) {
2403                 atomic_set(&rdev->corrected_errors, n);
2404                 return len;
2405         }
2406         return -EINVAL;
2407 }
2408 static struct rdev_sysfs_entry rdev_errors =
2409 __ATTR(errors, S_IRUGO|S_IWUSR, errors_show, errors_store);
2410
2411 static ssize_t
2412 slot_show(mdk_rdev_t *rdev, char *page)
2413 {
2414         if (rdev->raid_disk < 0)
2415                 return sprintf(page, "none\n");
2416         else
2417                 return sprintf(page, "%d\n", rdev->raid_disk);
2418 }
2419
2420 static ssize_t
2421 slot_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2422 {
2423         char *e;
2424         int err;
2425         char nm[20];
2426         int slot = simple_strtoul(buf, &e, 10);
2427         if (strncmp(buf, "none", 4)==0)
2428                 slot = -1;
2429         else if (e==buf || (*e && *e!= '\n'))
2430                 return -EINVAL;
2431         if (rdev->mddev->pers && slot == -1) {
2432                 /* Setting 'slot' on an active array requires also
2433                  * updating the 'rd%d' link, and communicating
2434                  * with the personality with ->hot_*_disk.
2435                  * For now we only support removing
2436                  * failed/spare devices.  This normally happens automatically,
2437                  * but not when the metadata is externally managed.
2438                  */
2439                 if (rdev->raid_disk == -1)
2440                         return -EEXIST;
2441                 /* personality does all needed checks */
2442                 if (rdev->mddev->pers->hot_add_disk == NULL)
2443                         return -EINVAL;
2444                 err = rdev->mddev->pers->
2445                         hot_remove_disk(rdev->mddev, rdev->raid_disk);
2446                 if (err)
2447                         return err;
2448                 sprintf(nm, "rd%d", rdev->raid_disk);
2449                 sysfs_remove_link(&rdev->mddev->kobj, nm);
2450                 rdev->raid_disk = -1;
2451                 set_bit(MD_RECOVERY_NEEDED, &rdev->mddev->recovery);
2452                 md_wakeup_thread(rdev->mddev->thread);
2453         } else if (rdev->mddev->pers) {
2454                 mdk_rdev_t *rdev2;
2455                 /* Activating a spare .. or possibly reactivating
2456                  * if we ever get bitmaps working here.
2457                  */
2458
2459                 if (rdev->raid_disk != -1)
2460                         return -EBUSY;
2461
2462                 if (rdev->mddev->pers->hot_add_disk == NULL)
2463                         return -EINVAL;
2464
2465                 list_for_each_entry(rdev2, &rdev->mddev->disks, same_set)
2466                         if (rdev2->raid_disk == slot)
2467                                 return -EEXIST;
2468
2469                 rdev->raid_disk = slot;
2470                 if (test_bit(In_sync, &rdev->flags))
2471                         rdev->saved_raid_disk = slot;
2472                 else
2473                         rdev->saved_raid_disk = -1;
2474                 err = rdev->mddev->pers->
2475                         hot_add_disk(rdev->mddev, rdev);
2476                 if (err) {
2477                         rdev->raid_disk = -1;
2478                         return err;
2479                 } else
2480                         sysfs_notify_dirent_safe(rdev->sysfs_state);
2481                 sprintf(nm, "rd%d", rdev->raid_disk);
2482                 if (sysfs_create_link(&rdev->mddev->kobj, &rdev->kobj, nm))
2483                         /* failure here is OK */;
2484                 /* don't wakeup anyone, leave that to userspace. */
2485         } else {
2486                 if (slot >= rdev->mddev->raid_disks)
2487                         return -ENOSPC;
2488                 rdev->raid_disk = slot;
2489                 /* assume it is working */
2490                 clear_bit(Faulty, &rdev->flags);
2491                 clear_bit(WriteMostly, &rdev->flags);
2492                 set_bit(In_sync, &rdev->flags);
2493                 sysfs_notify_dirent_safe(rdev->sysfs_state);
2494         }
2495         return len;
2496 }
2497
2498
2499 static struct rdev_sysfs_entry rdev_slot =
2500 __ATTR(slot, S_IRUGO|S_IWUSR, slot_show, slot_store);
2501
2502 static ssize_t
2503 offset_show(mdk_rdev_t *rdev, char *page)
2504 {
2505         return sprintf(page, "%llu\n", (unsigned long long)rdev->data_offset);
2506 }
2507
2508 static ssize_t
2509 offset_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2510 {
2511         char *e;
2512         unsigned long long offset = simple_strtoull(buf, &e, 10);
2513         if (e==buf || (*e && *e != '\n'))
2514                 return -EINVAL;
2515         if (rdev->mddev->pers && rdev->raid_disk >= 0)
2516                 return -EBUSY;
2517         if (rdev->sectors && rdev->mddev->external)
2518                 /* Must set offset before size, so overlap checks
2519                  * can be sane */
2520                 return -EBUSY;
2521         rdev->data_offset = offset;
2522         return len;
2523 }
2524
2525 static struct rdev_sysfs_entry rdev_offset =
2526 __ATTR(offset, S_IRUGO|S_IWUSR, offset_show, offset_store);
2527
2528 static ssize_t
2529 rdev_size_show(mdk_rdev_t *rdev, char *page)
2530 {
2531         return sprintf(page, "%llu\n", (unsigned long long)rdev->sectors / 2);
2532 }
2533
2534 static int overlaps(sector_t s1, sector_t l1, sector_t s2, sector_t l2)
2535 {
2536         /* check if two start/length pairs overlap */
2537         if (s1+l1 <= s2)
2538                 return 0;
2539         if (s2+l2 <= s1)
2540                 return 0;
2541         return 1;
2542 }
2543
2544 static int strict_blocks_to_sectors(const char *buf, sector_t *sectors)
2545 {
2546         unsigned long long blocks;
2547         sector_t new;
2548
2549         if (strict_strtoull(buf, 10, &blocks) < 0)
2550                 return -EINVAL;
2551
2552         if (blocks & 1ULL << (8 * sizeof(blocks) - 1))
2553                 return -EINVAL; /* sector conversion overflow */
2554
2555         new = blocks * 2;
2556         if (new != blocks * 2)
2557                 return -EINVAL; /* unsigned long long to sector_t overflow */
2558
2559         *sectors = new;
2560         return 0;
2561 }
2562
2563 static ssize_t
2564 rdev_size_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2565 {
2566         mddev_t *my_mddev = rdev->mddev;
2567         sector_t oldsectors = rdev->sectors;
2568         sector_t sectors;
2569
2570         if (strict_blocks_to_sectors(buf, &sectors) < 0)
2571                 return -EINVAL;
2572         if (my_mddev->pers && rdev->raid_disk >= 0) {
2573                 if (my_mddev->persistent) {
2574                         sectors = super_types[my_mddev->major_version].
2575                                 rdev_size_change(rdev, sectors);
2576                         if (!sectors)
2577                                 return -EBUSY;
2578                 } else if (!sectors)
2579                         sectors = (rdev->bdev->bd_inode->i_size >> 9) -
2580                                 rdev->data_offset;
2581         }
2582         if (sectors < my_mddev->dev_sectors)
2583                 return -EINVAL; /* component must fit device */
2584
2585         rdev->sectors = sectors;
2586         if (sectors > oldsectors && my_mddev->external) {
2587                 /* need to check that all other rdevs with the same ->bdev
2588                  * do not overlap.  We need to unlock the mddev to avoid
2589                  * a deadlock.  We have already changed rdev->sectors, and if
2590                  * we have to change it back, we will have the lock again.
2591                  */
2592                 mddev_t *mddev;
2593                 int overlap = 0;
2594                 struct list_head *tmp;
2595
2596                 mddev_unlock(my_mddev);
2597                 for_each_mddev(mddev, tmp) {
2598                         mdk_rdev_t *rdev2;
2599
2600                         mddev_lock(mddev);
2601                         list_for_each_entry(rdev2, &mddev->disks, same_set)
2602                                 if (test_bit(AllReserved, &rdev2->flags) ||
2603                                     (rdev->bdev == rdev2->bdev &&
2604                                      rdev != rdev2 &&
2605                                      overlaps(rdev->data_offset, rdev->sectors,
2606                                               rdev2->data_offset,
2607                                               rdev2->sectors))) {
2608                                         overlap = 1;
2609                                         break;
2610                                 }
2611                         mddev_unlock(mddev);
2612                         if (overlap) {
2613                                 mddev_put(mddev);
2614                                 break;
2615                         }
2616                 }
2617                 mddev_lock(my_mddev);
2618                 if (overlap) {
2619                         /* Someone else could have slipped in a size
2620                          * change here, but doing so is just silly.
2621                          * We put oldsectors back because we *know* it is
2622                          * safe, and trust userspace not to race with
2623                          * itself
2624                          */
2625                         rdev->sectors = oldsectors;
2626                         return -EBUSY;
2627                 }
2628         }
2629         return len;
2630 }
2631
2632 static struct rdev_sysfs_entry rdev_size =
2633 __ATTR(size, S_IRUGO|S_IWUSR, rdev_size_show, rdev_size_store);
2634
2635
2636 static ssize_t recovery_start_show(mdk_rdev_t *rdev, char *page)
2637 {
2638         unsigned long long recovery_start = rdev->recovery_offset;
2639
2640         if (test_bit(In_sync, &rdev->flags) ||
2641             recovery_start == MaxSector)
2642                 return sprintf(page, "none\n");
2643
2644         return sprintf(page, "%llu\n", recovery_start);
2645 }
2646
2647 static ssize_t recovery_start_store(mdk_rdev_t *rdev, const char *buf, size_t len)
2648 {
2649         unsigned long long recovery_start;
2650
2651         if (cmd_match(buf, "none"))
2652                 recovery_start = MaxSector;
2653         else if (strict_strtoull(buf, 10, &recovery_start))
2654                 return -EINVAL;
2655
2656         if (rdev->mddev->pers &&
2657             rdev->raid_disk >= 0)
2658                 return -EBUSY;
2659
2660         rdev->recovery_offset = recovery_start;
2661         if (recovery_start == MaxSector)
2662                 set_bit(In_sync, &rdev->flags);
2663         else
2664                 clear_bit(In_sync, &rdev->flags);
2665         return len;
2666 }
2667
2668 static struct rdev_sysfs_entry rdev_recovery_start =
2669 __ATTR(recovery_start, S_IRUGO|S_IWUSR, recovery_start_show, recovery_start_store);
2670
2671 static struct attribute *rdev_default_attrs[] = {
2672         &rdev_state.attr,
2673         &rdev_errors.attr,
2674         &rdev_slot.attr,
2675         &rdev_offset.attr,
2676         &rdev_size.attr,
2677         &rdev_recovery_start.attr,
2678         NULL,
2679 };
2680 static ssize_t
2681 rdev_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
2682 {
2683         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2684         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2685         mddev_t *mddev = rdev->mddev;
2686         ssize_t rv;
2687
2688         if (!entry->show)
2689                 return -EIO;
2690
2691         rv = mddev ? mddev_lock(mddev) : -EBUSY;
2692         if (!rv) {
2693                 if (rdev->mddev == NULL)
2694                         rv = -EBUSY;
2695                 else
2696                         rv = entry->show(rdev, page);
2697                 mddev_unlock(mddev);
2698         }
2699         return rv;
2700 }
2701
2702 static ssize_t
2703 rdev_attr_store(struct kobject *kobj, struct attribute *attr,
2704               const char *page, size_t length)
2705 {
2706         struct rdev_sysfs_entry *entry = container_of(attr, struct rdev_sysfs_entry, attr);
2707         mdk_rdev_t *rdev = container_of(kobj, mdk_rdev_t, kobj);
2708         ssize_t rv;
2709         mddev_t *mddev = rdev->mddev;
2710
2711         if (!entry->store)
2712                 return -EIO;
2713         if (!capable(CAP_SYS_ADMIN))
2714                 return -EACCES;
2715         rv = mddev ? mddev_lock(mddev): -EBUSY;
2716         if (!rv) {
2717                 if (rdev->mddev == NULL)
2718                         rv = -EBUSY;
2719                 else
2720                         rv = entry->store(rdev, page, length);
2721                 mddev_unlock(mddev);
2722         }
2723         return rv;
2724 }
2725
2726 static void rdev_free(struct kobject *ko)
2727 {
2728         mdk_rdev_t *rdev = container_of(ko, mdk_rdev_t, kobj);
2729         kfree(rdev);
2730 }
2731 static const struct sysfs_ops rdev_sysfs_ops = {
2732         .show           = rdev_attr_show,
2733         .store          = rdev_attr_store,
2734 };
2735 static struct kobj_type rdev_ktype = {
2736         .release        = rdev_free,
2737         .sysfs_ops      = &rdev_sysfs_ops,
2738         .default_attrs  = rdev_default_attrs,
2739 };
2740
2741 void md_rdev_init(mdk_rdev_t *rdev)
2742 {
2743         rdev->desc_nr = -1;
2744         rdev->saved_raid_disk = -1;
2745         rdev->raid_disk = -1;
2746         rdev->flags = 0;
2747         rdev->data_offset = 0;
2748         rdev->sb_events = 0;
2749         rdev->last_read_error.tv_sec  = 0;
2750         rdev->last_read_error.tv_nsec = 0;
2751         atomic_set(&rdev->nr_pending, 0);
2752         atomic_set(&rdev->read_errors, 0);
2753         atomic_set(&rdev->corrected_errors, 0);
2754
2755         INIT_LIST_HEAD(&rdev->same_set);
2756         init_waitqueue_head(&rdev->blocked_wait);
2757 }
2758 EXPORT_SYMBOL_GPL(md_rdev_init);
2759 /*
2760  * Import a device. If 'super_format' >= 0, then sanity check the superblock
2761  *
2762  * mark the device faulty if:
2763  *
2764  *   - the device is nonexistent (zero size)
2765  *   - the device has no valid superblock
2766  *
2767  * a faulty rdev _never_ has rdev->sb set.
2768  */
2769 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
2770 {
2771         char b[BDEVNAME_SIZE];
2772         int err;
2773         mdk_rdev_t *rdev;
2774         sector_t size;
2775
2776         rdev = kzalloc(sizeof(*rdev), GFP_KERNEL);
2777         if (!rdev) {
2778                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
2779                 return ERR_PTR(-ENOMEM);
2780         }
2781
2782         md_rdev_init(rdev);
2783         if ((err = alloc_disk_sb(rdev)))
2784                 goto abort_free;
2785
2786         err = lock_rdev(rdev, newdev, super_format == -2);
2787         if (err)
2788                 goto abort_free;
2789
2790         kobject_init(&rdev->kobj, &rdev_ktype);
2791
2792         size = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
2793         if (!size) {
2794                 printk(KERN_WARNING 
2795                         "md: %s has zero or unknown size, marking faulty!\n",
2796                         bdevname(rdev->bdev,b));
2797                 err = -EINVAL;
2798                 goto abort_free;
2799         }
2800
2801         if (super_format >= 0) {
2802                 err = super_types[super_format].
2803                         load_super(rdev, NULL, super_minor);
2804                 if (err == -EINVAL) {
2805                         printk(KERN_WARNING
2806                                 "md: %s does not have a valid v%d.%d "
2807                                "superblock, not importing!\n",
2808                                 bdevname(rdev->bdev,b),
2809                                super_format, super_minor);
2810                         goto abort_free;
2811                 }
2812                 if (err < 0) {
2813                         printk(KERN_WARNING 
2814                                 "md: could not read %s's sb, not importing!\n",
2815                                 bdevname(rdev->bdev,b));
2816                         goto abort_free;
2817                 }
2818         }
2819
2820         return rdev;
2821
2822 abort_free:
2823         if (rdev->sb_page) {
2824                 if (rdev->bdev)
2825                         unlock_rdev(rdev);
2826                 free_disk_sb(rdev);
2827         }
2828         kfree(rdev);
2829         return ERR_PTR(err);
2830 }
2831
2832 /*
2833  * Check a full RAID array for plausibility
2834  */
2835
2836
2837 static void analyze_sbs(mddev_t * mddev)
2838 {
2839         int i;
2840         mdk_rdev_t *rdev, *freshest, *tmp;
2841         char b[BDEVNAME_SIZE];
2842
2843         freshest = NULL;
2844         rdev_for_each(rdev, tmp, mddev)
2845                 switch (super_types[mddev->major_version].
2846                         load_super(rdev, freshest, mddev->minor_version)) {
2847                 case 1:
2848                         freshest = rdev;
2849                         break;
2850                 case 0:
2851                         break;
2852                 default:
2853                         printk( KERN_ERR \
2854                                 "md: fatal superblock inconsistency in %s"
2855                                 " -- removing from array\n", 
2856                                 bdevname(rdev->bdev,b));
2857                         kick_rdev_from_array(rdev);
2858                 }
2859
2860
2861         super_types[mddev->major_version].
2862                 validate_super(mddev, freshest);
2863
2864         i = 0;
2865         rdev_for_each(rdev, tmp, mddev) {
2866                 if (mddev->max_disks &&
2867                     (rdev->desc_nr >= mddev->max_disks ||
2868                      i > mddev->max_disks)) {
2869                         printk(KERN_WARNING
2870                                "md: %s: %s: only %d devices permitted\n",
2871                                mdname(mddev), bdevname(rdev->bdev, b),
2872                                mddev->max_disks);
2873                         kick_rdev_from_array(rdev);
2874                         continue;
2875                 }
2876                 if (rdev != freshest)
2877                         if (super_types[mddev->major_version].
2878                             validate_super(mddev, rdev)) {
2879                                 printk(KERN_WARNING "md: kicking non-fresh %s"
2880                                         " from array!\n",
2881                                         bdevname(rdev->bdev,b));
2882                                 kick_rdev_from_array(rdev);
2883                                 continue;
2884                         }
2885                 if (mddev->level == LEVEL_MULTIPATH) {
2886                         rdev->desc_nr = i++;
2887                         rdev->raid_disk = rdev->desc_nr;
2888                         set_bit(In_sync, &rdev->flags);
2889                 } else if (rdev->raid_disk >= (mddev->raid_disks - min(0, mddev->delta_disks))) {
2890                         rdev->raid_disk = -1;
2891                         clear_bit(In_sync, &rdev->flags);
2892                 }
2893         }
2894 }
2895
2896 /* Read a fixed-point number.
2897  * Numbers in sysfs attributes should be in "standard" units where
2898  * possible, so time should be in seconds.
2899  * However we internally use a a much smaller unit such as 
2900  * milliseconds or jiffies.
2901  * This function takes a decimal number with a possible fractional
2902  * component, and produces an integer which is the result of
2903  * multiplying that number by 10^'scale'.
2904  * all without any floating-point arithmetic.
2905  */
2906 int strict_strtoul_scaled(const char *cp, unsigned long *res, int scale)
2907 {
2908         unsigned long result = 0;
2909         long decimals = -1;
2910         while (isdigit(*cp) || (*cp == '.' && decimals < 0)) {
2911                 if (*cp == '.')
2912                         decimals = 0;
2913                 else if (decimals < scale) {
2914                         unsigned int value;
2915                         value = *cp - '0';
2916                         result = result * 10 + value;
2917                         if (decimals >= 0)
2918                                 decimals++;
2919                 }
2920                 cp++;
2921         }
2922         if (*cp == '\n')
2923                 cp++;
2924         if (*cp)
2925                 return -EINVAL;
2926         if (decimals < 0)
2927                 decimals = 0;
2928         while (decimals < scale) {
2929                 result *= 10;
2930                 decimals ++;
2931         }
2932         *res = result;
2933         return 0;
2934 }
2935
2936
2937 static void md_safemode_timeout(unsigned long data);
2938
2939 static ssize_t
2940 safe_delay_show(mddev_t *mddev, char *page)
2941 {
2942         int msec = (mddev->safemode_delay*1000)/HZ;
2943         return sprintf(page, "%d.%03d\n", msec/1000, msec%1000);
2944 }
2945 static ssize_t
2946 safe_delay_store(mddev_t *mddev, const char *cbuf, size_t len)
2947 {
2948         unsigned long msec;
2949
2950         if (strict_strtoul_scaled(cbuf, &msec, 3) < 0)
2951                 return -EINVAL;
2952         if (msec == 0)
2953                 mddev->safemode_delay = 0;
2954         else {
2955                 unsigned long old_delay = mddev->safemode_delay;
2956                 mddev->safemode_delay = (msec*HZ)/1000;
2957                 if (mddev->safemode_delay == 0)
2958                         mddev->safemode_delay = 1;
2959                 if (mddev->safemode_delay < old_delay)
2960                         md_safemode_timeout((unsigned long)mddev);
2961         }
2962         return len;
2963 }
2964 static struct md_sysfs_entry md_safe_delay =
2965 __ATTR(safe_mode_delay, S_IRUGO|S_IWUSR,safe_delay_show, safe_delay_store);
2966
2967 static ssize_t
2968 level_show(mddev_t *mddev, char *page)
2969 {
2970         struct mdk_personality *p = mddev->pers;
2971         if (p)
2972                 return sprintf(page, "%s\n", p->name);
2973         else if (mddev->clevel[0])
2974                 return sprintf(page, "%s\n", mddev->clevel);
2975         else if (mddev->level != LEVEL_NONE)
2976                 return sprintf(page, "%d\n", mddev->level);
2977         else
2978                 return 0;
2979 }
2980
2981 static ssize_t
2982 level_store(mddev_t *mddev, const char *buf, size_t len)
2983 {
2984         char clevel[16];
2985         ssize_t rv = len;
2986         struct mdk_personality *pers;
2987         long level;
2988         void *priv;
2989         mdk_rdev_t *rdev;
2990
2991         if (mddev->pers == NULL) {
2992                 if (len == 0)
2993                         return 0;
2994                 if (len >= sizeof(mddev->clevel))
2995                         return -ENOSPC;
2996                 strncpy(mddev->clevel, buf, len);
2997                 if (mddev->clevel[len-1] == '\n')
2998                         len--;
2999                 mddev->clevel[len] = 0;
3000                 mddev->level = LEVEL_NONE;
3001                 return rv;
3002         }
3003
3004         /* request to change the personality.  Need to ensure:
3005          *  - array is not engaged in resync/recovery/reshape
3006          *  - old personality can be suspended
3007          *  - new personality will access other array.
3008          */
3009
3010         if (mddev->sync_thread ||
3011             mddev->reshape_position != MaxSector ||
3012             mddev->sysfs_active)
3013                 return -EBUSY;
3014
3015         if (!mddev->pers->quiesce) {
3016                 printk(KERN_WARNING "md: %s: %s does not support online personality change\n",
3017                        mdname(mddev), mddev->pers->name);
3018                 return -EINVAL;
3019         }
3020
3021         /* Now find the new personality */
3022         if (len == 0 || len >= sizeof(clevel))
3023                 return -EINVAL;
3024         strncpy(clevel, buf, len);
3025         if (clevel[len-1] == '\n')
3026                 len--;
3027         clevel[len] = 0;
3028         if (strict_strtol(clevel, 10, &level))
3029                 level = LEVEL_NONE;
3030
3031         if (request_module("md-%s", clevel) != 0)
3032                 request_module("md-level-%s", clevel);
3033         spin_lock(&pers_lock);
3034         pers = find_pers(level, clevel);
3035         if (!pers || !try_module_get(pers->owner)) {
3036                 spin_unlock(&pers_lock);
3037                 printk(KERN_WARNING "md: personality %s not loaded\n", clevel);
3038                 return -EINVAL;
3039         }
3040         spin_unlock(&pers_lock);
3041
3042         if (pers == mddev->pers) {
3043                 /* Nothing to do! */
3044                 module_put(pers->owner);
3045                 return rv;
3046         }
3047         if (!pers->takeover) {
3048                 module_put(pers->owner);
3049                 printk(KERN_WARNING "md: %s: %s does not support personality takeover\n",
3050                        mdname(mddev), clevel);
3051                 return -EINVAL;
3052         }
3053
3054         list_for_each_entry(rdev, &mddev->disks, same_set)
3055                 rdev->new_raid_disk = rdev->raid_disk;
3056
3057         /* ->takeover must set new_* and/or delta_disks
3058          * if it succeeds, and may set them when it fails.
3059          */
3060         priv = pers->takeover(mddev);
3061         if (IS_ERR(priv)) {
3062                 mddev->new_level = mddev->level;
3063                 mddev->new_layout = mddev->layout;
3064                 mddev->new_chunk_sectors = mddev->chunk_sectors;
3065                 mddev->raid_disks -= mddev->delta_disks;
3066                 mddev->delta_disks = 0;
3067                 module_put(pers->owner);
3068                 printk(KERN_WARNING "md: %s: %s would not accept array\n",
3069                        mdname(mddev), clevel);
3070                 return PTR_ERR(priv);
3071         }
3072
3073         /* Looks like we have a winner */
3074         mddev_suspend(mddev);
3075         mddev->pers->stop(mddev);
3076         
3077         if (mddev->pers->sync_request == NULL &&
3078             pers->sync_request != NULL) {
3079                 /* need to add the md_redundancy_group */
3080                 if (sysfs_create_group(&mddev->kobj, &md_redundancy_group))
3081                         printk(KERN_WARNING
3082                                "md: cannot register extra attributes for %s\n",
3083                                mdname(mddev));
3084                 mddev->sysfs_action = sysfs_get_dirent(mddev->kobj.sd, NULL, "sync_action");
3085         }               
3086         if (mddev->pers->sync_request != NULL &&
3087             pers->sync_request == NULL) {
3088                 /* need to remove the md_redundancy_group */
3089                 if (mddev->to_remove == NULL)
3090                         mddev->to_remove = &md_redundancy_group;
3091         }
3092
3093         if (mddev->pers->sync_request == NULL &&
3094             mddev->external) {
3095                 /* We are converting from a no-redundancy array
3096                  * to a redundancy array and metadata is managed
3097                  * externally so we need to be sure that writes
3098                  * won't block due to a need to transition
3099                  *      clean->dirty
3100                  * until external management is started.
3101                  */
3102                 mddev->in_sync = 0;
3103                 mddev->safemode_delay = 0;
3104                 mddev->safemode = 0;
3105         }
3106
3107         list_for_each_entry(rdev, &mddev->disks, same_set) {
3108                 char nm[20];
3109                 if (rdev->raid_disk < 0)
3110                         continue;
3111                 if (rdev->new_raid_disk > mddev->raid_disks)
3112                         rdev->new_raid_disk = -1;
3113                 if (rdev->new_raid_disk == rdev->raid_disk)
3114                         continue;
3115                 sprintf(nm, "rd%d", rdev->raid_disk);
3116                 sysfs_remove_link(&mddev->kobj, nm);
3117         }
3118         list_for_each_entry(rdev, &mddev->disks, same_set) {
3119                 if (rdev->raid_disk < 0)
3120                         continue;
3121                 if (rdev->new_raid_disk == rdev->raid_disk)
3122                         continue;
3123                 rdev->raid_disk = rdev->new_raid_disk;
3124                 if (rdev->raid_disk < 0)
3125                         clear_bit(In_sync, &rdev->flags);
3126                 else {
3127                         char nm[20];
3128                         sprintf(nm, "rd%d", rdev->raid_disk);
3129                         if(sysfs_create_link(&mddev->kobj, &rdev->kobj, nm))
3130                                 printk("md: cannot register %s for %s after level change\n",
3131                                        nm, mdname(mddev));
3132                 }
3133         }
3134
3135         module_put(mddev->pers->owner);
3136         mddev->pers = pers;
3137         mddev->private = priv;
3138         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
3139         mddev->level = mddev->new_level;
3140         mddev->layout = mddev->new_layout;
3141         mddev->chunk_sectors = mddev->new_chunk_sectors;
3142         mddev->delta_disks = 0;
3143         if (mddev->pers->sync_request == NULL) {
3144                 /* this is now an array without redundancy, so
3145                  * it must always be in_sync
3146                  */
3147                 mddev->in_sync = 1;
3148                 del_timer_sync(&mddev->safemode_timer);
3149         }
3150         pers->run(mddev);
3151         mddev_resume(mddev);
3152         set_bit(MD_CHANGE_DEVS, &mddev->flags);
3153         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3154         md_wakeup_thread(mddev->thread);
3155         sysfs_notify(&mddev->kobj, NULL, "level");
3156         md_new_event(mddev);
3157         return rv;
3158 }
3159
3160 static struct md_sysfs_entry md_level =
3161 __ATTR(level, S_IRUGO|S_IWUSR, level_show, level_store);
3162
3163
3164 static ssize_t
3165 layout_show(mddev_t *mddev, char *page)
3166 {
3167         /* just a number, not meaningful for all levels */
3168         if (mddev->reshape_position != MaxSector &&
3169             mddev->layout != mddev->new_layout)
3170                 return sprintf(page, "%d (%d)\n",
3171                                mddev->new_layout, mddev->layout);
3172         return sprintf(page, "%d\n", mddev->layout);
3173 }
3174
3175 static ssize_t
3176 layout_store(mddev_t *mddev, const char *buf, size_t len)
3177 {
3178         char *e;
3179         unsigned long n = simple_strtoul(buf, &e, 10);
3180
3181         if (!*buf || (*e && *e != '\n'))
3182                 return -EINVAL;
3183
3184         if (mddev->pers) {
3185                 int err;
3186                 if (mddev->pers->check_reshape == NULL)
3187                         return -EBUSY;
3188                 mddev->new_layout = n;
3189                 err = mddev->pers->check_reshape(mddev);
3190                 if (err) {
3191                         mddev->new_layout = mddev->layout;
3192                         return err;
3193                 }
3194         } else {
3195                 mddev->new_layout = n;
3196                 if (mddev->reshape_position == MaxSector)
3197                         mddev->layout = n;
3198         }
3199         return len;
3200 }
3201 static struct md_sysfs_entry md_layout =
3202 __ATTR(layout, S_IRUGO|S_IWUSR, layout_show, layout_store);
3203
3204
3205 static ssize_t
3206 raid_disks_show(mddev_t *mddev, char *page)
3207 {
3208         if (mddev->raid_disks == 0)
3209                 return 0;
3210         if (mddev->reshape_position != MaxSector &&
3211             mddev->delta_disks != 0)
3212                 return sprintf(page, "%d (%d)\n", mddev->raid_disks,
3213                                mddev->raid_disks - mddev->delta_disks);
3214         return sprintf(page, "%d\n", mddev->raid_disks);
3215 }
3216
3217 static int update_raid_disks(mddev_t *mddev, int raid_disks);
3218
3219 static ssize_t
3220 raid_disks_store(mddev_t *mddev, const char *buf, size_t len)
3221 {
3222         char *e;
3223         int rv = 0;
3224         unsigned long n = simple_strtoul(buf, &e, 10);
3225
3226         if (!*buf || (*e && *e != '\n'))
3227                 return -EINVAL;
3228
3229         if (mddev->pers)
3230                 rv = update_raid_disks(mddev, n);
3231         else if (mddev->reshape_position != MaxSector) {
3232                 int olddisks = mddev->raid_disks - mddev->delta_disks;
3233                 mddev->delta_disks = n - olddisks;
3234                 mddev->raid_disks = n;
3235         } else
3236                 mddev->raid_disks = n;
3237         return rv ? rv : len;
3238 }
3239 static struct md_sysfs_entry md_raid_disks =
3240 __ATTR(raid_disks, S_IRUGO|S_IWUSR, raid_disks_show, raid_disks_store);
3241
3242 static ssize_t
3243 chunk_size_show(mddev_t *mddev, char *page)
3244 {
3245         if (mddev->reshape_position != MaxSector &&
3246             mddev->chunk_sectors != mddev->new_chunk_sectors)
3247                 return sprintf(page, "%d (%d)\n",
3248                                mddev->new_chunk_sectors << 9,
3249                                mddev->chunk_sectors << 9);
3250         return sprintf(page, "%d\n", mddev->chunk_sectors << 9);
3251 }
3252
3253 static ssize_t
3254 chunk_size_store(mddev_t *mddev, const char *buf, size_t len)
3255 {
3256         char *e;
3257         unsigned long n = simple_strtoul(buf, &e, 10);
3258
3259         if (!*buf || (*e && *e != '\n'))
3260                 return -EINVAL;
3261
3262         if (mddev->pers) {
3263                 int err;
3264                 if (mddev->pers->check_reshape == NULL)
3265                         return -EBUSY;
3266                 mddev->new_chunk_sectors = n >> 9;
3267                 err = mddev->pers->check_reshape(mddev);
3268                 if (err) {
3269                         mddev->new_chunk_sectors = mddev->chunk_sectors;
3270                         return err;
3271                 }
3272         } else {
3273                 mddev->new_chunk_sectors = n >> 9;
3274                 if (mddev->reshape_position == MaxSector)
3275                         mddev->chunk_sectors = n >> 9;
3276         }
3277         return len;
3278 }
3279 static struct md_sysfs_entry md_chunk_size =
3280 __ATTR(chunk_size, S_IRUGO|S_IWUSR, chunk_size_show, chunk_size_store);
3281
3282 static ssize_t
3283 resync_start_show(mddev_t *mddev, char *page)
3284 {
3285         if (mddev->recovery_cp == MaxSector)
3286                 return sprintf(page, "none\n");
3287         return sprintf(page, "%llu\n", (unsigned long long)mddev->recovery_cp);
3288 }
3289
3290 static ssize_t
3291 resync_start_store(mddev_t *mddev, const char *buf, size_t len)
3292 {
3293         char *e;
3294         unsigned long long n = simple_strtoull(buf, &e, 10);
3295
3296         if (mddev->pers)
3297                 return -EBUSY;
3298         if (cmd_match(buf, "none"))
3299                 n = MaxSector;
3300         else if (!*buf || (*e && *e != '\n'))
3301                 return -EINVAL;
3302
3303         mddev->recovery_cp = n;
3304         return len;
3305 }
3306 static struct md_sysfs_entry md_resync_start =
3307 __ATTR(resync_start, S_IRUGO|S_IWUSR, resync_start_show, resync_start_store);
3308
3309 /*
3310  * The array state can be:
3311  *
3312  * clear
3313  *     No devices, no size, no level
3314  *     Equivalent to STOP_ARRAY ioctl
3315  * inactive
3316  *     May have some settings, but array is not active
3317  *        all IO results in error
3318  *     When written, doesn't tear down array, but just stops it
3319  * suspended (not supported yet)
3320  *     All IO requests will block. The array can be reconfigured.
3321  *     Writing this, if accepted, will block until array is quiescent
3322  * readonly
3323  *     no resync can happen.  no superblocks get written.
3324  *     write requests fail
3325  * read-auto
3326  *     like readonly, but behaves like 'clean' on a write request.
3327  *
3328  * clean - no pending writes, but otherwise active.
3329  *     When written to inactive array, starts without resync
3330  *     If a write request arrives then
3331  *       if metadata is known, mark 'dirty' and switch to 'active'.
3332  *       if not known, block and switch to write-pending
3333  *     If written to an active array that has pending writes, then fails.
3334  * active
3335  *     fully active: IO and resync can be happening.
3336  *     When written to inactive array, starts with resync
3337  *
3338  * write-pending
3339  *     clean, but writes are blocked waiting for 'active' to be written.
3340  *
3341  * active-idle
3342  *     like active, but no writes have been seen for a while (100msec).
3343  *
3344  */
3345 enum array_state { clear, inactive, suspended, readonly, read_auto, clean, active,
3346                    write_pending, active_idle, bad_word};
3347 static char *array_states[] = {
3348         "clear", "inactive", "suspended", "readonly", "read-auto", "clean", "active",
3349         "write-pending", "active-idle", NULL };
3350
3351 static int match_word(const char *word, char **list)
3352 {
3353         int n;
3354         for (n=0; list[n]; n++)
3355                 if (cmd_match(word, list[n]))
3356                         break;
3357         return n;
3358 }
3359
3360 static ssize_t
3361 array_state_show(mddev_t *mddev, char *page)
3362 {
3363         enum array_state st = inactive;
3364
3365         if (mddev->pers)
3366                 switch(mddev->ro) {
3367                 case 1:
3368                         st = readonly;
3369                         break;
3370                 case 2:
3371                         st = read_auto;
3372                         break;
3373                 case 0:
3374                         if (mddev->in_sync)
3375                                 st = clean;
3376                         else if (test_bit(MD_CHANGE_PENDING, &mddev->flags))
3377                                 st = write_pending;
3378                         else if (mddev->safemode)
3379                                 st = active_idle;
3380                         else
3381                                 st = active;
3382                 }
3383         else {
3384                 if (list_empty(&mddev->disks) &&
3385                     mddev->raid_disks == 0 &&
3386                     mddev->dev_sectors == 0)
3387                         st = clear;
3388                 else
3389                         st = inactive;
3390         }
3391         return sprintf(page, "%s\n", array_states[st]);
3392 }
3393
3394 static int do_md_stop(mddev_t * mddev, int ro, int is_open);
3395 static int md_set_readonly(mddev_t * mddev, int is_open);
3396 static int do_md_run(mddev_t * mddev);
3397 static int restart_array(mddev_t *mddev);
3398
3399 static ssize_t
3400 array_state_store(mddev_t *mddev, const char *buf, size_t len)
3401 {
3402         int err = -EINVAL;
3403         enum array_state st = match_word(buf, array_states);
3404         switch(st) {
3405         case bad_word:
3406                 break;
3407         case clear:
3408                 /* stopping an active array */
3409                 if (atomic_read(&mddev->openers) > 0)
3410                         return -EBUSY;
3411                 err = do_md_stop(mddev, 0, 0);
3412                 break;
3413         case inactive:
3414                 /* stopping an active array */
3415                 if (mddev->pers) {
3416                         if (atomic_read(&mddev->openers) > 0)
3417                                 return -EBUSY;
3418                         err = do_md_stop(mddev, 2, 0);
3419                 } else
3420                         err = 0; /* already inactive */
3421                 break;
3422         case suspended:
3423                 break; /* not supported yet */
3424         case readonly:
3425                 if (mddev->pers)
3426                         err = md_set_readonly(mddev, 0);
3427                 else {
3428                         mddev->ro = 1;
3429                         set_disk_ro(mddev->gendisk, 1);
3430                         err = do_md_run(mddev);
3431                 }
3432                 break;
3433         case read_auto:
3434                 if (mddev->pers) {
3435                         if (mddev->ro == 0)
3436                                 err = md_set_readonly(mddev, 0);
3437                         else if (mddev->ro == 1)
3438                                 err = restart_array(mddev);
3439                         if (err == 0) {
3440                                 mddev->ro = 2;
3441                                 set_disk_ro(mddev->gendisk, 0);
3442                         }
3443                 } else {
3444                         mddev->ro = 2;
3445                         err = do_md_run(mddev);
3446                 }
3447                 break;
3448         case clean:
3449                 if (mddev->pers) {
3450                         restart_array(mddev);
3451                         spin_lock_irq(&mddev->write_lock);
3452                         if (atomic_read(&mddev->writes_pending) == 0) {
3453                                 if (mddev->in_sync == 0) {
3454                                         mddev->in_sync = 1;
3455                                         if (mddev->safemode == 1)
3456                                                 mddev->safemode = 0;
3457                                         set_bit(MD_CHANGE_CLEAN, &mddev->flags);
3458                                 }
3459                                 err = 0;
3460                         } else
3461                                 err = -EBUSY;
3462                         spin_unlock_irq(&mddev->write_lock);
3463                 } else
3464                         err = -EINVAL;
3465                 break;
3466         case active:
3467                 if (mddev->pers) {
3468                         restart_array(mddev);
3469                         clear_bit(MD_CHANGE_PENDING, &mddev->flags);
3470                         wake_up(&mddev->sb_wait);
3471                         err = 0;
3472                 } else {
3473                         mddev->ro = 0;
3474                         set_disk_ro(mddev->gendisk, 0);
3475                         err = do_md_run(mddev);
3476                 }
3477                 break;
3478         case write_pending:
3479         case active_idle:
3480                 /* these cannot be set */
3481                 break;
3482         }
3483         if (err)
3484                 return err;
3485         else {
3486                 sysfs_notify_dirent_safe(mddev->sysfs_state);
3487                 return len;
3488         }
3489 }
3490 static struct md_sysfs_entry md_array_state =
3491 __ATTR(array_state, S_IRUGO|S_IWUSR, array_state_show, array_state_store);
3492
3493 static ssize_t
3494 max_corrected_read_errors_show(mddev_t *mddev, char *page) {
3495         return sprintf(page, "%d\n",
3496                        atomic_read(&mddev->max_corr_read_errors));
3497 }
3498
3499 static ssize_t
3500 max_corrected_read_errors_store(mddev_t *mddev, const char *buf, size_t len)
3501 {
3502         char *e;
3503         unsigned long n = simple_strtoul(buf, &e, 10);
3504
3505         if (*buf && (*e == 0 || *e == '\n')) {
3506                 atomic_set(&mddev->max_corr_read_errors, n);
3507                 return len;
3508         }
3509         return -EINVAL;
3510 }
3511
3512 static struct md_sysfs_entry max_corr_read_errors =
3513 __ATTR(max_read_errors, S_IRUGO|S_IWUSR, max_corrected_read_errors_show,
3514         max_corrected_read_errors_store);
3515
3516 static ssize_t
3517 null_show(mddev_t *mddev, char *page)
3518 {
3519         return -EINVAL;
3520 }
3521
3522 static ssize_t
3523 new_dev_store(mddev_t *mddev, const char *buf, size_t len)
3524 {
3525         /* buf must be %d:%d\n? giving major and minor numbers */
3526         /* The new device is added to the array.
3527          * If the array has a persistent superblock, we read the
3528          * superblock to initialise info and check validity.
3529          * Otherwise, only checking done is that in bind_rdev_to_array,
3530          * which mainly checks size.
3531          */
3532         char *e;
3533         int major = simple_strtoul(buf, &e, 10);
3534         int minor;
3535         dev_t dev;
3536         mdk_rdev_t *rdev;
3537         int err;
3538
3539         if (!*buf || *e != ':' || !e[1] || e[1] == '\n')
3540                 return -EINVAL;
3541         minor = simple_strtoul(e+1, &e, 10);
3542         if (*e && *e != '\n')
3543                 return -EINVAL;
3544         dev = MKDEV(major, minor);
3545         if (major != MAJOR(dev) ||
3546             minor != MINOR(dev))
3547                 return -EOVERFLOW;
3548
3549
3550         if (mddev->persistent) {
3551                 rdev = md_import_device(dev, mddev->major_version,
3552                                         mddev->minor_version);
3553                 if (!IS_ERR(rdev) && !list_empty(&mddev->disks)) {
3554                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
3555                                                        mdk_rdev_t, same_set);
3556                         err = super_types[mddev->major_version]
3557                                 .load_super(rdev, rdev0, mddev->minor_version);
3558                         if (err < 0)
3559                                 goto out;
3560                 }
3561         } else if (mddev->external)
3562                 rdev = md_import_device(dev, -2, -1);
3563         else
3564                 rdev = md_import_device(dev, -1, -1);
3565
3566         if (IS_ERR(rdev))
3567                 return PTR_ERR(rdev);
3568         err = bind_rdev_to_array(rdev, mddev);
3569  out:
3570         if (err)
3571                 export_rdev(rdev);
3572         return err ? err : len;
3573 }
3574
3575 static struct md_sysfs_entry md_new_device =
3576 __ATTR(new_dev, S_IWUSR, null_show, new_dev_store);
3577
3578 static ssize_t
3579 bitmap_store(mddev_t *mddev, const char *buf, size_t len)
3580 {
3581         char *end;
3582         unsigned long chunk, end_chunk;
3583
3584         if (!mddev->bitmap)
3585                 goto out;
3586         /* buf should be <chunk> <chunk> ... or <chunk>-<chunk> ... (range) */
3587         while (*buf) {
3588                 chunk = end_chunk = simple_strtoul(buf, &end, 0);
3589                 if (buf == end) break;
3590                 if (*end == '-') { /* range */
3591                         buf = end + 1;
3592                         end_chunk = simple_strtoul(buf, &end, 0);
3593                         if (buf == end) break;
3594                 }
3595                 if (*end && !isspace(*end)) break;
3596                 bitmap_dirty_bits(mddev->bitmap, chunk, end_chunk);
3597                 buf = skip_spaces(end);
3598         }
3599         bitmap_unplug(mddev->bitmap); /* flush the bits to disk */
3600 out:
3601         return len;
3602 }
3603
3604 static struct md_sysfs_entry md_bitmap =
3605 __ATTR(bitmap_set_bits, S_IWUSR, null_show, bitmap_store);
3606
3607 static ssize_t
3608 size_show(mddev_t *mddev, char *page)
3609 {
3610         return sprintf(page, "%llu\n",
3611                 (unsigned long long)mddev->dev_sectors / 2);
3612 }
3613
3614 static int update_size(mddev_t *mddev, sector_t num_sectors);
3615
3616 static ssize_t
3617 size_store(mddev_t *mddev, const char *buf, size_t len)
3618 {
3619         /* If array is inactive, we can reduce the component size, but
3620          * not increase it (except from 0).
3621          * If array is active, we can try an on-line resize
3622          */
3623         sector_t sectors;
3624         int err = strict_blocks_to_sectors(buf, &sectors);
3625
3626         if (err < 0)
3627                 return err;
3628         if (mddev->pers) {
3629                 err = update_size(mddev, sectors);
3630                 md_update_sb(mddev, 1);
3631         } else {
3632                 if (mddev->dev_sectors == 0 ||
3633                     mddev->dev_sectors > sectors)
3634                         mddev->dev_sectors = sectors;
3635                 else
3636                         err = -ENOSPC;
3637         }
3638         return err ? err : len;
3639 }
3640
3641 static struct md_sysfs_entry md_size =
3642 __ATTR(component_size, S_IRUGO|S_IWUSR, size_show, size_store);
3643
3644
3645 /* Metdata version.
3646  * This is one of
3647  *   'none' for arrays with no metadata (good luck...)
3648  *   'external' for arrays with externally managed metadata,
3649  * or N.M for internally known formats
3650  */
3651 static ssize_t
3652 metadata_show(mddev_t *mddev, char *page)
3653 {
3654         if (mddev->persistent)
3655                 return sprintf(page, "%d.%d\n",
3656                                mddev->major_version, mddev->minor_version);
3657         else if (mddev->external)
3658                 return sprintf(page, "external:%s\n", mddev->metadata_type);
3659         else
3660                 return sprintf(page, "none\n");
3661 }
3662
3663 static ssize_t
3664 metadata_store(mddev_t *mddev, const char *buf, size_t len)
3665 {
3666         int major, minor;
3667         char *e;
3668         /* Changing the details of 'external' metadata is
3669          * always permitted.  Otherwise there must be
3670          * no devices attached to the array.
3671          */
3672         if (mddev->external && strncmp(buf, "external:", 9) == 0)
3673                 ;
3674         else if (!list_empty(&mddev->disks))
3675                 return -EBUSY;
3676
3677         if (cmd_match(buf, "none")) {
3678                 mddev->persistent = 0;
3679                 mddev->external = 0;
3680                 mddev->major_version = 0;
3681                 mddev->minor_version = 90;
3682                 return len;
3683         }
3684         if (strncmp(buf, "external:", 9) == 0) {
3685                 size_t namelen = len-9;
3686                 if (namelen >= sizeof(mddev->metadata_type))
3687                         namelen = sizeof(mddev->metadata_type)-1;
3688                 strncpy(mddev->metadata_type, buf+9, namelen);
3689                 mddev->metadata_type[namelen] = 0;
3690                 if (namelen && mddev->metadata_type[namelen-1] == '\n')
3691                         mddev->metadata_type[--namelen] = 0;
3692                 mddev->persistent = 0;
3693                 mddev->external = 1;
3694                 mddev->major_version = 0;
3695                 mddev->minor_version = 90;
3696                 return len;
3697         }
3698         major = simple_strtoul(buf, &e, 10);
3699         if (e==buf || *e != '.')
3700                 return -EINVAL;
3701         buf = e+1;
3702         minor = simple_strtoul(buf, &e, 10);
3703         if (e==buf || (*e && *e != '\n') )
3704                 return -EINVAL;
3705         if (major >= ARRAY_SIZE(super_types) || super_types[major].name == NULL)
3706                 return -ENOENT;
3707         mddev->major_version = major;
3708         mddev->minor_version = minor;
3709         mddev->persistent = 1;
3710         mddev->external = 0;
3711         return len;
3712 }
3713
3714 static struct md_sysfs_entry md_metadata =
3715 __ATTR(metadata_version, S_IRUGO|S_IWUSR, metadata_show, metadata_store);
3716
3717 static ssize_t
3718 action_show(mddev_t *mddev, char *page)
3719 {
3720         char *type = "idle";
3721         if (test_bit(MD_RECOVERY_FROZEN, &mddev->recovery))
3722                 type = "frozen";
3723         else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3724             (!mddev->ro && test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))) {
3725                 if (test_bit(MD_RECOVERY_RESHAPE, &mddev->recovery))
3726                         type = "reshape";
3727                 else if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery)) {
3728                         if (!test_bit(MD_RECOVERY_REQUESTED, &mddev->recovery))
3729                                 type = "resync";
3730                         else if (test_bit(MD_RECOVERY_CHECK, &mddev->recovery))
3731                                 type = "check";
3732                         else
3733                                 type = "repair";
3734                 } else if (test_bit(MD_RECOVERY_RECOVER, &mddev->recovery))
3735                         type = "recover";
3736         }
3737         return sprintf(page, "%s\n", type);
3738 }
3739
3740 static ssize_t
3741 action_store(mddev_t *mddev, const char *page, size_t len)
3742 {
3743         if (!mddev->pers || !mddev->pers->sync_request)
3744                 return -EINVAL;
3745
3746         if (cmd_match(page, "frozen"))
3747                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3748         else
3749                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
3750
3751         if (cmd_match(page, "idle") || cmd_match(page, "frozen")) {
3752                 if (mddev->sync_thread) {
3753                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3754                         md_unregister_thread(mddev->sync_thread);
3755                         mddev->sync_thread = NULL;
3756                         mddev->recovery = 0;
3757                 }
3758         } else if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) ||
3759                    test_bit(MD_RECOVERY_NEEDED, &mddev->recovery))
3760                 return -EBUSY;
3761         else if (cmd_match(page, "resync"))
3762                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3763         else if (cmd_match(page, "recover")) {
3764                 set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
3765                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3766         } else if (cmd_match(page, "reshape")) {
3767                 int err;
3768                 if (mddev->pers->start_reshape == NULL)
3769                         return -EINVAL;
3770                 err = mddev->pers->start_reshape(mddev);
3771                 if (err)
3772                         return err;
3773                 sysfs_notify(&mddev->kobj, NULL, "degraded");
3774         } else {
3775                 if (cmd_match(page, "check"))
3776                         set_bit(MD_RECOVERY_CHECK, &mddev->recovery);
3777                 else if (!cmd_match(page, "repair"))
3778                         return -EINVAL;
3779                 set_bit(MD_RECOVERY_REQUESTED, &mddev->recovery);
3780                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3781         }
3782         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3783         md_wakeup_thread(mddev->thread);
3784         sysfs_notify_dirent_safe(mddev->sysfs_action);
3785         return len;
3786 }
3787
3788 static ssize_t
3789 mismatch_cnt_show(mddev_t *mddev, char *page)
3790 {
3791         return sprintf(page, "%llu\n",
3792                        (unsigned long long) mddev->resync_mismatches);
3793 }
3794
3795 static struct md_sysfs_entry md_scan_mode =
3796 __ATTR(sync_action, S_IRUGO|S_IWUSR, action_show, action_store);
3797
3798
3799 static struct md_sysfs_entry md_mismatches = __ATTR_RO(mismatch_cnt);
3800
3801 static ssize_t
3802 sync_min_show(mddev_t *mddev, char *page)
3803 {
3804         return sprintf(page, "%d (%s)\n", speed_min(mddev),
3805                        mddev->sync_speed_min ? "local": "system");
3806 }
3807
3808 static ssize_t
3809 sync_min_store(mddev_t *mddev, const char *buf, size_t len)
3810 {
3811         int min;
3812         char *e;
3813         if (strncmp(buf, "system", 6)==0) {
3814                 mddev->sync_speed_min = 0;
3815                 return len;
3816         }
3817         min = simple_strtoul(buf, &e, 10);
3818         if (buf == e || (*e && *e != '\n') || min <= 0)
3819                 return -EINVAL;
3820         mddev->sync_speed_min = min;
3821         return len;
3822 }
3823
3824 static struct md_sysfs_entry md_sync_min =
3825 __ATTR(sync_speed_min, S_IRUGO|S_IWUSR, sync_min_show, sync_min_store);
3826
3827 static ssize_t
3828 sync_max_show(mddev_t *mddev, char *page)
3829 {
3830         return sprintf(page, "%d (%s)\n", speed_max(mddev),
3831                        mddev->sync_speed_max ? "local": "system");
3832 }
3833
3834 static ssize_t
3835 sync_max_store(mddev_t *mddev, const char *buf, size_t len)
3836 {
3837         int max;
3838         char *e;
3839         if (strncmp(buf, "system", 6)==0) {
3840                 mddev->sync_speed_max = 0;
3841                 return len;
3842         }
3843         max = simple_strtoul(buf, &e, 10);
3844         if (buf == e || (*e && *e != '\n') || max <= 0)
3845                 return -EINVAL;
3846         mddev->sync_speed_max = max;
3847         return len;
3848 }
3849
3850 static struct md_sysfs_entry md_sync_max =
3851 __ATTR(sync_speed_max, S_IRUGO|S_IWUSR, sync_max_show, sync_max_store);
3852
3853 static ssize_t
3854 degraded_show(mddev_t *mddev, char *page)
3855 {
3856         return sprintf(page, "%d\n", mddev->degraded);
3857 }
3858 static struct md_sysfs_entry md_degraded = __ATTR_RO(degraded);
3859
3860 static ssize_t
3861 sync_force_parallel_show(mddev_t *mddev, char *page)
3862 {
3863         return sprintf(page, "%d\n", mddev->parallel_resync);
3864 }
3865
3866 static ssize_t
3867 sync_force_parallel_store(mddev_t *mddev, const char *buf, size_t len)
3868 {
3869         long n;
3870
3871         if (strict_strtol(buf, 10, &n))
3872                 return -EINVAL;
3873
3874         if (n != 0 && n != 1)
3875                 return -EINVAL;
3876
3877         mddev->parallel_resync = n;
3878
3879         if (mddev->sync_thread)
3880                 wake_up(&resync_wait);
3881
3882         return len;
3883 }
3884
3885 /* force parallel resync, even with shared block devices */
3886 static struct md_sysfs_entry md_sync_force_parallel =
3887 __ATTR(sync_force_parallel, S_IRUGO|S_IWUSR,
3888        sync_force_parallel_show, sync_force_parallel_store);
3889
3890 static ssize_t
3891 sync_speed_show(mddev_t *mddev, char *page)
3892 {
3893         unsigned long resync, dt, db;
3894         if (mddev->curr_resync == 0)
3895                 return sprintf(page, "none\n");
3896         resync = mddev->curr_mark_cnt - atomic_read(&mddev->recovery_active);
3897         dt = (jiffies - mddev->resync_mark) / HZ;
3898         if (!dt) dt++;
3899         db = resync - mddev->resync_mark_cnt;
3900         return sprintf(page, "%lu\n", db/dt/2); /* K/sec */
3901 }
3902
3903 static struct md_sysfs_entry md_sync_speed = __ATTR_RO(sync_speed);
3904
3905 static ssize_t
3906 sync_completed_show(mddev_t *mddev, char *page)
3907 {
3908         unsigned long max_sectors, resync;
3909
3910         if (!test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3911                 return sprintf(page, "none\n");
3912
3913         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3914                 max_sectors = mddev->resync_max_sectors;
3915         else
3916                 max_sectors = mddev->dev_sectors;
3917
3918         resync = mddev->curr_resync_completed;
3919         return sprintf(page, "%lu / %lu\n", resync, max_sectors);
3920 }
3921
3922 static struct md_sysfs_entry md_sync_completed = __ATTR_RO(sync_completed);
3923
3924 static ssize_t
3925 min_sync_show(mddev_t *mddev, char *page)
3926 {
3927         return sprintf(page, "%llu\n",
3928                        (unsigned long long)mddev->resync_min);
3929 }
3930 static ssize_t
3931 min_sync_store(mddev_t *mddev, const char *buf, size_t len)
3932 {
3933         unsigned long long min;
3934         if (strict_strtoull(buf, 10, &min))
3935                 return -EINVAL;
3936         if (min > mddev->resync_max)
3937                 return -EINVAL;
3938         if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3939                 return -EBUSY;
3940
3941         /* Must be a multiple of chunk_size */
3942         if (mddev->chunk_sectors) {
3943                 sector_t temp = min;
3944                 if (sector_div(temp, mddev->chunk_sectors))
3945                         return -EINVAL;
3946         }
3947         mddev->resync_min = min;
3948
3949         return len;
3950 }
3951
3952 static struct md_sysfs_entry md_min_sync =
3953 __ATTR(sync_min, S_IRUGO|S_IWUSR, min_sync_show, min_sync_store);
3954
3955 static ssize_t
3956 max_sync_show(mddev_t *mddev, char *page)
3957 {
3958         if (mddev->resync_max == MaxSector)
3959                 return sprintf(page, "max\n");
3960         else
3961                 return sprintf(page, "%llu\n",
3962                                (unsigned long long)mddev->resync_max);
3963 }
3964 static ssize_t
3965 max_sync_store(mddev_t *mddev, const char *buf, size_t len)
3966 {
3967         if (strncmp(buf, "max", 3) == 0)
3968                 mddev->resync_max = MaxSector;
3969         else {
3970                 unsigned long long max;
3971                 if (strict_strtoull(buf, 10, &max))
3972                         return -EINVAL;
3973                 if (max < mddev->resync_min)
3974                         return -EINVAL;
3975                 if (max < mddev->resync_max &&
3976                     mddev->ro == 0 &&
3977                     test_bit(MD_RECOVERY_RUNNING, &mddev->recovery))
3978                         return -EBUSY;
3979
3980                 /* Must be a multiple of chunk_size */
3981                 if (mddev->chunk_sectors) {
3982                         sector_t temp = max;
3983                         if (sector_div(temp, mddev->chunk_sectors))
3984                                 return -EINVAL;
3985                 }
3986                 mddev->resync_max = max;
3987         }
3988         wake_up(&mddev->recovery_wait);
3989         return len;
3990 }
3991
3992 static struct md_sysfs_entry md_max_sync =
3993 __ATTR(sync_max, S_IRUGO|S_IWUSR, max_sync_show, max_sync_store);
3994
3995 static ssize_t
3996 suspend_lo_show(mddev_t *mddev, char *page)
3997 {
3998         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_lo);
3999 }
4000
4001 static ssize_t
4002 suspend_lo_store(mddev_t *mddev, const char *buf, size_t len)
4003 {
4004         char *e;
4005         unsigned long long new = simple_strtoull(buf, &e, 10);
4006
4007         if (mddev->pers == NULL || 
4008             mddev->pers->quiesce == NULL)
4009                 return -EINVAL;
4010         if (buf == e || (*e && *e != '\n'))
4011                 return -EINVAL;
4012         if (new >= mddev->suspend_hi ||
4013             (new > mddev->suspend_lo && new < mddev->suspend_hi)) {
4014                 mddev->suspend_lo = new;
4015                 mddev->pers->quiesce(mddev, 2);
4016                 return len;
4017         } else
4018                 return -EINVAL;
4019 }
4020 static struct md_sysfs_entry md_suspend_lo =
4021 __ATTR(suspend_lo, S_IRUGO|S_IWUSR, suspend_lo_show, suspend_lo_store);
4022
4023
4024 static ssize_t
4025 suspend_hi_show(mddev_t *mddev, char *page)
4026 {
4027         return sprintf(page, "%llu\n", (unsigned long long)mddev->suspend_hi);
4028 }
4029
4030 static ssize_t
4031 suspend_hi_store(mddev_t *mddev, const char *buf, size_t len)
4032 {
4033         char *e;
4034         unsigned long long new = simple_strtoull(buf, &e, 10);
4035
4036         if (mddev->pers == NULL ||
4037             mddev->pers->quiesce == NULL)
4038                 return -EINVAL;
4039         if (buf == e || (*e && *e != '\n'))
4040                 return -EINVAL;
4041         if ((new <= mddev->suspend_lo && mddev->suspend_lo >= mddev->suspend_hi) ||
4042             (new > mddev->suspend_lo && new > mddev->suspend_hi)) {
4043                 mddev->suspend_hi = new;
4044                 mddev->pers->quiesce(mddev, 1);
4045                 mddev->pers->quiesce(mddev, 0);
4046                 return len;
4047         } else
4048                 return -EINVAL;
4049 }
4050 static struct md_sysfs_entry md_suspend_hi =
4051 __ATTR(suspend_hi, S_IRUGO|S_IWUSR, suspend_hi_show, suspend_hi_store);
4052
4053 static ssize_t
4054 reshape_position_show(mddev_t *mddev, char *page)
4055 {
4056         if (mddev->reshape_position != MaxSector)
4057                 return sprintf(page, "%llu\n",
4058                                (unsigned long long)mddev->reshape_position);
4059         strcpy(page, "none\n");
4060         return 5;
4061 }
4062
4063 static ssize_t
4064 reshape_position_store(mddev_t *mddev, const char *buf, size_t len)
4065 {
4066         char *e;
4067         unsigned long long new = simple_strtoull(buf, &e, 10);
4068         if (mddev->pers)
4069                 return -EBUSY;
4070         if (buf == e || (*e && *e != '\n'))
4071                 return -EINVAL;
4072         mddev->reshape_position = new;
4073         mddev->delta_disks = 0;
4074         mddev->new_level = mddev->level;
4075         mddev->new_layout = mddev->layout;
4076         mddev->new_chunk_sectors = mddev->chunk_sectors;
4077         return len;
4078 }
4079
4080 static struct md_sysfs_entry md_reshape_position =
4081 __ATTR(reshape_position, S_IRUGO|S_IWUSR, reshape_position_show,
4082        reshape_position_store);
4083
4084 static ssize_t
4085 array_size_show(mddev_t *mddev, char *page)
4086 {
4087         if (mddev->external_size)
4088                 return sprintf(page, "%llu\n",
4089                                (unsigned long long)mddev->array_sectors/2);
4090         else
4091                 return sprintf(page, "default\n");
4092 }
4093
4094 static ssize_t
4095 array_size_store(mddev_t *mddev, const char *buf, size_t len)
4096 {
4097         sector_t sectors;
4098
4099         if (strncmp(buf, "default", 7) == 0) {
4100                 if (mddev->pers)
4101                         sectors = mddev->pers->size(mddev, 0, 0);
4102                 else
4103                         sectors = mddev->array_sectors;
4104
4105                 mddev->external_size = 0;
4106         } else {
4107                 if (strict_blocks_to_sectors(buf, &sectors) < 0)
4108                         return -EINVAL;
4109                 if (mddev->pers && mddev->pers->size(mddev, 0, 0) < sectors)
4110                         return -E2BIG;
4111
4112                 mddev->external_size = 1;
4113         }
4114
4115         mddev->array_sectors = sectors;
4116         set_capacity(mddev->gendisk, mddev->array_sectors);
4117         if (mddev->pers)
4118                 revalidate_disk(mddev->gendisk);
4119
4120         return len;
4121 }
4122
4123 static struct md_sysfs_entry md_array_size =
4124 __ATTR(array_size, S_IRUGO|S_IWUSR, array_size_show,
4125        array_size_store);
4126
4127 static struct attribute *md_default_attrs[] = {
4128         &md_level.attr,
4129         &md_layout.attr,
4130         &md_raid_disks.attr,
4131         &md_chunk_size.attr,
4132         &md_size.attr,
4133         &md_resync_start.attr,
4134         &md_metadata.attr,
4135         &md_new_device.attr,
4136         &md_safe_delay.attr,
4137         &md_array_state.attr,
4138         &md_reshape_position.attr,
4139         &md_array_size.attr,
4140         &max_corr_read_errors.attr,
4141         NULL,
4142 };
4143
4144 static struct attribute *md_redundancy_attrs[] = {
4145         &md_scan_mode.attr,
4146         &md_mismatches.attr,
4147         &md_sync_min.attr,
4148         &md_sync_max.attr,
4149         &md_sync_speed.attr,
4150         &md_sync_force_parallel.attr,
4151         &md_sync_completed.attr,
4152         &md_min_sync.attr,
4153         &md_max_sync.attr,
4154         &md_suspend_lo.attr,
4155         &md_suspend_hi.attr,
4156         &md_bitmap.attr,
4157         &md_degraded.attr,
4158         NULL,
4159 };
4160 static struct attribute_group md_redundancy_group = {
4161         .name = NULL,
4162         .attrs = md_redundancy_attrs,
4163 };
4164
4165
4166 static ssize_t
4167 md_attr_show(struct kobject *kobj, struct attribute *attr, char *page)
4168 {
4169         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4170         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
4171         ssize_t rv;
4172
4173         if (!entry->show)
4174                 return -EIO;
4175         rv = mddev_lock(mddev);
4176         if (!rv) {
4177                 rv = entry->show(mddev, page);
4178                 mddev_unlock(mddev);
4179         }
4180         return rv;
4181 }
4182
4183 static ssize_t
4184 md_attr_store(struct kobject *kobj, struct attribute *attr,
4185               const char *page, size_t length)
4186 {
4187         struct md_sysfs_entry *entry = container_of(attr, struct md_sysfs_entry, attr);
4188         mddev_t *mddev = container_of(kobj, struct mddev_s, kobj);
4189         ssize_t rv;
4190
4191         if (!entry->store)
4192                 return -EIO;
4193         if (!capable(CAP_SYS_ADMIN))
4194                 return -EACCES;
4195         rv = mddev_lock(mddev);
4196         if (mddev->hold_active == UNTIL_IOCTL)
4197                 mddev->hold_active = 0;
4198         if (!rv) {
4199                 rv = entry->store(mddev, page, length);
4200                 mddev_unlock(mddev);
4201         }
4202         return rv;
4203 }
4204
4205 static void md_free(struct kobject *ko)
4206 {
4207         mddev_t *mddev = container_of(ko, mddev_t, kobj);
4208
4209         if (mddev->sysfs_state)
4210                 sysfs_put(mddev->sysfs_state);
4211
4212         if (mddev->gendisk) {
4213                 del_gendisk(mddev->gendisk);
4214                 put_disk(mddev->gendisk);
4215         }
4216         if (mddev->queue)
4217                 blk_cleanup_queue(mddev->queue);
4218
4219         kfree(mddev);
4220 }
4221
4222 static const struct sysfs_ops md_sysfs_ops = {
4223         .show   = md_attr_show,
4224         .store  = md_attr_store,
4225 };
4226 static struct kobj_type md_ktype = {
4227         .release        = md_free,
4228         .sysfs_ops      = &md_sysfs_ops,
4229         .default_attrs  = md_default_attrs,
4230 };
4231
4232 int mdp_major = 0;
4233
4234 static void mddev_delayed_delete(struct work_struct *ws)
4235 {
4236         mddev_t *mddev = container_of(ws, mddev_t, del_work);
4237
4238         sysfs_remove_group(&mddev->kobj, &md_bitmap_group);
4239         kobject_del(&mddev->kobj);
4240         kobject_put(&mddev->kobj);
4241 }
4242
4243 static int md_alloc(dev_t dev, char *name)
4244 {
4245         static DEFINE_MUTEX(disks_mutex);
4246         mddev_t *mddev = mddev_find(dev);
4247         struct gendisk *disk;
4248         int partitioned;
4249         int shift;
4250         int unit;
4251         int error;
4252
4253         if (!mddev)
4254                 return -ENODEV;
4255
4256         partitioned = (MAJOR(mddev->unit) != MD_MAJOR);
4257         shift = partitioned ? MdpMinorShift : 0;
4258         unit = MINOR(mddev->unit) >> shift;
4259
4260         /* wait for any previous instance of this device to be
4261          * completely removed (mddev_delayed_delete).
4262          */
4263         flush_workqueue(md_misc_wq);
4264
4265         mutex_lock(&disks_mutex);
4266         error = -EEXIST;
4267         if (mddev->gendisk)
4268                 goto abort;
4269
4270         if (name) {
4271                 /* Need to ensure that 'name' is not a duplicate.
4272                  */
4273                 mddev_t *mddev2;
4274                 spin_lock(&all_mddevs_lock);
4275
4276                 list_for_each_entry(mddev2, &all_mddevs, all_mddevs)
4277                         if (mddev2->gendisk &&
4278                             strcmp(mddev2->gendisk->disk_name, name) == 0) {
4279                                 spin_unlock(&all_mddevs_lock);
4280                                 goto abort;
4281                         }
4282                 spin_unlock(&all_mddevs_lock);
4283         }
4284
4285         error = -ENOMEM;
4286         mddev->queue = blk_alloc_queue(GFP_KERNEL);
4287         if (!mddev->queue)
4288                 goto abort;
4289         mddev->queue->queuedata = mddev;
4290
4291         /* Can be unlocked because the queue is new: no concurrency */
4292         queue_flag_set_unlocked(QUEUE_FLAG_CLUSTER, mddev->queue);
4293
4294         blk_queue_make_request(mddev->queue, md_make_request);
4295
4296         disk = alloc_disk(1 << shift);
4297         if (!disk) {
4298                 blk_cleanup_queue(mddev->queue);
4299                 mddev->queue = NULL;
4300                 goto abort;
4301         }
4302         disk->major = MAJOR(mddev->unit);
4303         disk->first_minor = unit << shift;
4304         if (name)
4305                 strcpy(disk->disk_name, name);
4306         else if (partitioned)
4307                 sprintf(disk->disk_name, "md_d%d", unit);
4308         else
4309                 sprintf(disk->disk_name, "md%d", unit);
4310         disk->fops = &md_fops;
4311         disk->private_data = mddev;
4312         disk->queue = mddev->queue;
4313         /* Allow extended partitions.  This makes the
4314          * 'mdp' device redundant, but we can't really
4315          * remove it now.
4316          */
4317         disk->flags |= GENHD_FL_EXT_DEVT;
4318         add_disk(disk);
4319         mddev->gendisk = disk;
4320         error = kobject_init_and_add(&mddev->kobj, &md_ktype,
4321                                      &disk_to_dev(disk)->kobj, "%s", "md");
4322         if (error) {
4323                 /* This isn't possible, but as kobject_init_and_add is marked
4324                  * __must_check, we must do something with the result
4325                  */
4326                 printk(KERN_WARNING "md: cannot register %s/md - name in use\n",
4327                        disk->disk_name);
4328                 error = 0;
4329         }
4330         if (mddev->kobj.sd &&
4331             sysfs_create_group(&mddev->kobj, &md_bitmap_group))
4332                 printk(KERN_DEBUG "pointless warning\n");
4333  abort:
4334         mutex_unlock(&disks_mutex);
4335         if (!error && mddev->kobj.sd) {
4336                 kobject_uevent(&mddev->kobj, KOBJ_ADD);
4337                 mddev->sysfs_state = sysfs_get_dirent_safe(mddev->kobj.sd, "array_state");
4338         }
4339         mddev_put(mddev);
4340         return error;
4341 }
4342
4343 static struct kobject *md_probe(dev_t dev, int *part, void *data)
4344 {
4345         md_alloc(dev, NULL);
4346         return NULL;
4347 }
4348
4349 static int add_named_array(const char *val, struct kernel_param *kp)
4350 {
4351         /* val must be "md_*" where * is not all digits.
4352          * We allocate an array with a large free minor number, and
4353          * set the name to val.  val must not already be an active name.
4354          */
4355         int len = strlen(val);
4356         char buf[DISK_NAME_LEN];
4357
4358         while (len && val[len-1] == '\n')
4359                 len--;
4360         if (len >= DISK_NAME_LEN)
4361                 return -E2BIG;
4362         strlcpy(buf, val, len+1);
4363         if (strncmp(buf, "md_", 3) != 0)
4364                 return -EINVAL;
4365         return md_alloc(0, buf);
4366 }
4367
4368 static void md_safemode_timeout(unsigned long data)
4369 {
4370         mddev_t *mddev = (mddev_t *) data;
4371
4372         if (!atomic_read(&mddev->writes_pending)) {
4373                 mddev->safemode = 1;
4374                 if (mddev->external)
4375                         sysfs_notify_dirent_safe(mddev->sysfs_state);
4376         }
4377         md_wakeup_thread(mddev->thread);
4378 }
4379
4380 static int start_dirty_degraded;
4381
4382 int md_run(mddev_t *mddev)
4383 {
4384         int err;
4385         mdk_rdev_t *rdev;
4386         struct mdk_personality *pers;
4387
4388         if (list_empty(&mddev->disks))
4389                 /* cannot run an array with no devices.. */
4390                 return -EINVAL;
4391
4392         if (mddev->pers)
4393                 return -EBUSY;
4394         /* Cannot run until previous stop completes properly */
4395         if (mddev->sysfs_active)
4396                 return -EBUSY;
4397
4398         /*
4399          * Analyze all RAID superblock(s)
4400          */
4401         if (!mddev->raid_disks) {
4402                 if (!mddev->persistent)
4403                         return -EINVAL;
4404                 analyze_sbs(mddev);
4405         }
4406
4407         if (mddev->level != LEVEL_NONE)
4408                 request_module("md-level-%d", mddev->level);
4409         else if (mddev->clevel[0])
4410                 request_module("md-%s", mddev->clevel);
4411
4412         /*
4413          * Drop all container device buffers, from now on
4414          * the only valid external interface is through the md
4415          * device.
4416          */
4417         list_for_each_entry(rdev, &mddev->disks, same_set) {
4418                 if (test_bit(Faulty, &rdev->flags))
4419                         continue;
4420                 sync_blockdev(rdev->bdev);
4421                 invalidate_bdev(rdev->bdev);
4422
4423                 /* perform some consistency tests on the device.
4424                  * We don't want the data to overlap the metadata,
4425                  * Internal Bitmap issues have been handled elsewhere.
4426                  */
4427                 if (rdev->data_offset < rdev->sb_start) {
4428                         if (mddev->dev_sectors &&
4429                             rdev->data_offset + mddev->dev_sectors
4430                             > rdev->sb_start) {
4431                                 printk("md: %s: data overlaps metadata\n",
4432                                        mdname(mddev));
4433                                 return -EINVAL;
4434                         }
4435                 } else {
4436                         if (rdev->sb_start + rdev->sb_size/512
4437                             > rdev->data_offset) {
4438                                 printk("md: %s: metadata overlaps data\n",
4439                                        mdname(mddev));
4440                                 return -EINVAL;
4441                         }
4442                 }
4443                 sysfs_notify_dirent_safe(rdev->sysfs_state);
4444         }
4445
4446         if (mddev->bio_set == NULL)
4447                 mddev->bio_set = bioset_create(BIO_POOL_SIZE, sizeof(mddev));
4448
4449         spin_lock(&pers_lock);
4450         pers = find_pers(mddev->level, mddev->clevel);
4451         if (!pers || !try_module_get(pers->owner)) {
4452                 spin_unlock(&pers_lock);
4453                 if (mddev->level != LEVEL_NONE)
4454                         printk(KERN_WARNING "md: personality for level %d is not loaded!\n",
4455                                mddev->level);
4456                 else
4457                         printk(KERN_WARNING "md: personality for level %s is not loaded!\n",
4458                                mddev->clevel);
4459                 return -EINVAL;
4460         }
4461         mddev->pers = pers;
4462         spin_unlock(&pers_lock);
4463         if (mddev->level != pers->level) {
4464                 mddev->level = pers->level;
4465                 mddev->new_level = pers->level;
4466         }
4467         strlcpy(mddev->clevel, pers->name, sizeof(mddev->clevel));
4468
4469         if (mddev->reshape_position != MaxSector &&
4470             pers->start_reshape == NULL) {
4471                 /* This personality cannot handle reshaping... */
4472                 mddev->pers = NULL;
4473                 module_put(pers->owner);
4474                 return -EINVAL;
4475         }
4476
4477         if (pers->sync_request) {
4478                 /* Warn if this is a potentially silly
4479                  * configuration.
4480                  */
4481                 char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
4482                 mdk_rdev_t *rdev2;
4483                 int warned = 0;
4484
4485                 list_for_each_entry(rdev, &mddev->disks, same_set)
4486                         list_for_each_entry(rdev2, &mddev->disks, same_set) {
4487                                 if (rdev < rdev2 &&
4488                                     rdev->bdev->bd_contains ==
4489                                     rdev2->bdev->bd_contains) {
4490                                         printk(KERN_WARNING
4491                                                "%s: WARNING: %s appears to be"
4492                                                " on the same physical disk as"
4493                                                " %s.\n",
4494                                                mdname(mddev),
4495                                                bdevname(rdev->bdev,b),
4496                                                bdevname(rdev2->bdev,b2));
4497                                         warned = 1;
4498                                 }
4499                         }
4500
4501                 if (warned)
4502                         printk(KERN_WARNING
4503                                "True protection against single-disk"
4504                                " failure might be compromised.\n");
4505         }
4506
4507         mddev->recovery = 0;
4508         /* may be over-ridden by personality */
4509         mddev->resync_max_sectors = mddev->dev_sectors;
4510
4511         mddev->ok_start_degraded = start_dirty_degraded;
4512
4513         if (start_readonly && mddev->ro == 0)
4514                 mddev->ro = 2; /* read-only, but switch on first write */
4515
4516         err = mddev->pers->run(mddev);
4517         if (err)
4518                 printk(KERN_ERR "md: pers->run() failed ...\n");
4519         else if (mddev->pers->size(mddev, 0, 0) < mddev->array_sectors) {
4520                 WARN_ONCE(!mddev->external_size, "%s: default size too small,"
4521                           " but 'external_size' not in effect?\n", __func__);
4522                 printk(KERN_ERR
4523                        "md: invalid array_size %llu > default size %llu\n",
4524                        (unsigned long long)mddev->array_sectors / 2,
4525                        (unsigned long long)mddev->pers->size(mddev, 0, 0) / 2);
4526                 err = -EINVAL;
4527                 mddev->pers->stop(mddev);
4528         }
4529         if (err == 0 && mddev->pers->sync_request) {
4530                 err = bitmap_create(mddev);
4531                 if (err) {
4532                         printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
4533                                mdname(mddev), err);
4534                         mddev->pers->stop(mddev);
4535                 }
4536         }
4537         if (err) {
4538                 module_put(mddev->pers->owner);
4539                 mddev->pers = NULL;
4540                 bitmap_destroy(mddev);
4541                 return err;
4542         }
4543         if (mddev->pers->sync_request) {
4544                 if (mddev->kobj.sd &&
4545                     sysfs_create_group(&mddev->kobj, &md_redundancy_group))
4546                         printk(KERN_WARNING
4547                                "md: cannot register extra attributes for %s\n",
4548                                mdname(mddev));
4549                 mddev->sysfs_action = sysfs_get_dirent_safe(mddev->kobj.sd, "sync_action");
4550         } else if (mddev->ro == 2) /* auto-readonly not meaningful */
4551                 mddev->ro = 0;
4552
4553         atomic_set(&mddev->writes_pending,0);
4554         atomic_set(&mddev->max_corr_read_errors,
4555                    MD_DEFAULT_MAX_CORRECTED_READ_ERRORS);
4556         mddev->safemode = 0;
4557         mddev->safemode_timer.function = md_safemode_timeout;
4558         mddev->safemode_timer.data = (unsigned long) mddev;
4559         mddev->safemode_delay = (200 * HZ)/1000 +1; /* 200 msec delay */
4560         mddev->in_sync = 1;
4561
4562         list_for_each_entry(rdev, &mddev->disks, same_set)
4563                 if (rdev->raid_disk >= 0) {
4564                         char nm[20];
4565                         sprintf(nm, "rd%d", rdev->raid_disk);
4566                         if (sysfs_create_link(&mddev->kobj, &rdev->kobj, nm))
4567                                 /* failure here is OK */;
4568                 }
4569         
4570         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4571         
4572         if (mddev->flags)
4573                 md_update_sb(mddev, 0);
4574
4575         md_wakeup_thread(mddev->thread);
4576         md_wakeup_thread(mddev->sync_thread); /* possibly kick off a reshape */
4577
4578         md_new_event(mddev);
4579         sysfs_notify_dirent_safe(mddev->sysfs_state);
4580         sysfs_notify_dirent_safe(mddev->sysfs_action);
4581         sysfs_notify(&mddev->kobj, NULL, "degraded");
4582         return 0;
4583 }
4584 EXPORT_SYMBOL_GPL(md_run);
4585
4586 static int do_md_run(mddev_t *mddev)
4587 {
4588         int err;
4589
4590         err = md_run(mddev);
4591         if (err)
4592                 goto out;
4593         err = bitmap_load(mddev);
4594         if (err) {
4595                 bitmap_destroy(mddev);
4596                 goto out;
4597         }
4598         set_capacity(mddev->gendisk, mddev->array_sectors);
4599         revalidate_disk(mddev->gendisk);
4600         kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4601 out:
4602         return err;
4603 }
4604
4605 static int restart_array(mddev_t *mddev)
4606 {
4607         struct gendisk *disk = mddev->gendisk;
4608
4609         /* Complain if it has no devices */
4610         if (list_empty(&mddev->disks))
4611                 return -ENXIO;
4612         if (!mddev->pers)
4613                 return -EINVAL;
4614         if (!mddev->ro)
4615                 return -EBUSY;
4616         mddev->safemode = 0;
4617         mddev->ro = 0;
4618         set_disk_ro(disk, 0);
4619         printk(KERN_INFO "md: %s switched to read-write mode.\n",
4620                 mdname(mddev));
4621         /* Kick recovery or resync if necessary */
4622         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
4623         md_wakeup_thread(mddev->thread);
4624         md_wakeup_thread(mddev->sync_thread);
4625         sysfs_notify_dirent_safe(mddev->sysfs_state);
4626         return 0;
4627 }
4628
4629 /* similar to deny_write_access, but accounts for our holding a reference
4630  * to the file ourselves */
4631 static int deny_bitmap_write_access(struct file * file)
4632 {
4633         struct inode *inode = file->f_mapping->host;
4634
4635         spin_lock(&inode->i_lock);
4636         if (atomic_read(&inode->i_writecount) > 1) {
4637                 spin_unlock(&inode->i_lock);
4638                 return -ETXTBSY;
4639         }
4640         atomic_set(&inode->i_writecount, -1);
4641         spin_unlock(&inode->i_lock);
4642
4643         return 0;
4644 }
4645
4646 void restore_bitmap_write_access(struct file *file)
4647 {
4648         struct inode *inode = file->f_mapping->host;
4649
4650         spin_lock(&inode->i_lock);
4651         atomic_set(&inode->i_writecount, 1);
4652         spin_unlock(&inode->i_lock);
4653 }
4654
4655 static void md_clean(mddev_t *mddev)
4656 {
4657         mddev->array_sectors = 0;
4658         mddev->external_size = 0;
4659         mddev->dev_sectors = 0;
4660         mddev->raid_disks = 0;
4661         mddev->recovery_cp = 0;
4662         mddev->resync_min = 0;
4663         mddev->resync_max = MaxSector;
4664         mddev->reshape_position = MaxSector;
4665         mddev->external = 0;
4666         mddev->persistent = 0;
4667         mddev->level = LEVEL_NONE;
4668         mddev->clevel[0] = 0;
4669         mddev->flags = 0;
4670         mddev->ro = 0;
4671         mddev->metadata_type[0] = 0;
4672         mddev->chunk_sectors = 0;
4673         mddev->ctime = mddev->utime = 0;
4674         mddev->layout = 0;
4675         mddev->max_disks = 0;
4676         mddev->events = 0;
4677         mddev->can_decrease_events = 0;
4678         mddev->delta_disks = 0;
4679         mddev->new_level = LEVEL_NONE;
4680         mddev->new_layout = 0;
4681         mddev->new_chunk_sectors = 0;
4682         mddev->curr_resync = 0;
4683         mddev->resync_mismatches = 0;
4684         mddev->suspend_lo = mddev->suspend_hi = 0;
4685         mddev->sync_speed_min = mddev->sync_speed_max = 0;
4686         mddev->recovery = 0;
4687         mddev->in_sync = 0;
4688         mddev->degraded = 0;
4689         mddev->safemode = 0;
4690         mddev->bitmap_info.offset = 0;
4691         mddev->bitmap_info.default_offset = 0;
4692         mddev->bitmap_info.chunksize = 0;
4693         mddev->bitmap_info.daemon_sleep = 0;
4694         mddev->bitmap_info.max_write_behind = 0;
4695         mddev->plug = NULL;
4696 }
4697
4698 void md_stop_writes(mddev_t *mddev)
4699 {
4700         if (mddev->sync_thread) {
4701                 set_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4702                 set_bit(MD_RECOVERY_INTR, &mddev->recovery);
4703                 md_unregister_thread(mddev->sync_thread);
4704                 mddev->sync_thread = NULL;
4705         }
4706
4707         del_timer_sync(&mddev->safemode_timer);
4708
4709         bitmap_flush(mddev);
4710         md_super_wait(mddev);
4711
4712         if (!mddev->in_sync || mddev->flags) {
4713                 /* mark array as shutdown cleanly */
4714                 mddev->in_sync = 1;
4715                 md_update_sb(mddev, 1);
4716         }
4717 }
4718 EXPORT_SYMBOL_GPL(md_stop_writes);
4719
4720 void md_stop(mddev_t *mddev)
4721 {
4722         mddev->pers->stop(mddev);
4723         if (mddev->pers->sync_request && mddev->to_remove == NULL)
4724                 mddev->to_remove = &md_redundancy_group;
4725         module_put(mddev->pers->owner);
4726         mddev->pers = NULL;
4727         clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4728 }
4729 EXPORT_SYMBOL_GPL(md_stop);
4730
4731 static int md_set_readonly(mddev_t *mddev, int is_open)
4732 {
4733         int err = 0;
4734         mutex_lock(&mddev->open_mutex);
4735         if (atomic_read(&mddev->openers) > is_open) {
4736                 printk("md: %s still in use.\n",mdname(mddev));
4737                 err = -EBUSY;
4738                 goto out;
4739         }
4740         if (mddev->pers) {
4741                 md_stop_writes(mddev);
4742
4743                 err  = -ENXIO;
4744                 if (mddev->ro==1)
4745                         goto out;
4746                 mddev->ro = 1;
4747                 set_disk_ro(mddev->gendisk, 1);
4748                 clear_bit(MD_RECOVERY_FROZEN, &mddev->recovery);
4749                 sysfs_notify_dirent_safe(mddev->sysfs_state);
4750                 err = 0;        
4751         }
4752 out:
4753         mutex_unlock(&mddev->open_mutex);
4754         return err;
4755 }
4756
4757 /* mode:
4758  *   0 - completely stop and dis-assemble array
4759  *   2 - stop but do not disassemble array
4760  */
4761 static int do_md_stop(mddev_t * mddev, int mode, int is_open)
4762 {
4763         struct gendisk *disk = mddev->gendisk;
4764         mdk_rdev_t *rdev;
4765
4766         mutex_lock(&mddev->open_mutex);
4767         if (atomic_read(&mddev->openers) > is_open ||
4768             mddev->sysfs_active) {
4769                 printk("md: %s still in use.\n",mdname(mddev));
4770                 mutex_unlock(&mddev->open_mutex);
4771                 return -EBUSY;
4772         }
4773
4774         if (mddev->pers) {
4775                 if (mddev->ro)
4776                         set_disk_ro(disk, 0);
4777
4778                 md_stop_writes(mddev);
4779                 md_stop(mddev);
4780                 mddev->queue->merge_bvec_fn = NULL;
4781                 mddev->queue->unplug_fn = NULL;
4782                 mddev->queue->backing_dev_info.congested_fn = NULL;
4783
4784                 /* tell userspace to handle 'inactive' */
4785                 sysfs_notify_dirent_safe(mddev->sysfs_state);
4786
4787                 list_for_each_entry(rdev, &mddev->disks, same_set)
4788                         if (rdev->raid_disk >= 0) {
4789                                 char nm[20];
4790                                 sprintf(nm, "rd%d", rdev->raid_disk);
4791                                 sysfs_remove_link(&mddev->kobj, nm);
4792                         }
4793
4794                 set_capacity(disk, 0);
4795                 mutex_unlock(&mddev->open_mutex);
4796                 revalidate_disk(disk);
4797
4798                 if (mddev->ro)
4799                         mddev->ro = 0;
4800         } else
4801                 mutex_unlock(&mddev->open_mutex);
4802         /*
4803          * Free resources if final stop
4804          */
4805         if (mode == 0) {
4806                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
4807
4808                 bitmap_destroy(mddev);
4809                 if (mddev->bitmap_info.file) {
4810                         restore_bitmap_write_access(mddev->bitmap_info.file);
4811                         fput(mddev->bitmap_info.file);
4812                         mddev->bitmap_info.file = NULL;
4813                 }
4814                 mddev->bitmap_info.offset = 0;
4815
4816                 export_array(mddev);
4817
4818                 md_clean(mddev);
4819                 kobject_uevent(&disk_to_dev(mddev->gendisk)->kobj, KOBJ_CHANGE);
4820                 if (mddev->hold_active == UNTIL_STOP)
4821                         mddev->hold_active = 0;
4822         }
4823         blk_integrity_unregister(disk);
4824         md_new_event(mddev);
4825         sysfs_notify_dirent_safe(mddev->sysfs_state);
4826         return 0;
4827 }
4828
4829 #ifndef MODULE
4830 static void autorun_array(mddev_t *mddev)
4831 {
4832         mdk_rdev_t *rdev;
4833         int err;
4834
4835         if (list_empty(&mddev->disks))
4836                 return;
4837
4838         printk(KERN_INFO "md: running: ");
4839
4840         list_for_each_entry(rdev, &mddev->disks, same_set) {
4841                 char b[BDEVNAME_SIZE];
4842                 printk("<%s>", bdevname(rdev->bdev,b));
4843         }
4844         printk("\n");
4845
4846         err = do_md_run(mddev);
4847         if (err) {
4848                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
4849                 do_md_stop(mddev, 0, 0);
4850         }
4851 }
4852
4853 /*
4854  * lets try to run arrays based on all disks that have arrived
4855  * until now. (those are in pending_raid_disks)
4856  *
4857  * the method: pick the first pending disk, collect all disks with
4858  * the same UUID, remove all from the pending list and put them into
4859  * the 'same_array' list. Then order this list based on superblock
4860  * update time (freshest comes first), kick out 'old' disks and
4861  * compare superblocks. If everything's fine then run it.
4862  *
4863  * If "unit" is allocated, then bump its reference count
4864  */
4865 static void autorun_devices(int part)
4866 {
4867         mdk_rdev_t *rdev0, *rdev, *tmp;
4868         mddev_t *mddev;
4869         char b[BDEVNAME_SIZE];
4870
4871         printk(KERN_INFO "md: autorun ...\n");
4872         while (!list_empty(&pending_raid_disks)) {
4873                 int unit;
4874                 dev_t dev;
4875                 LIST_HEAD(candidates);
4876                 rdev0 = list_entry(pending_raid_disks.next,
4877                                          mdk_rdev_t, same_set);
4878
4879                 printk(KERN_INFO "md: considering %s ...\n",
4880                         bdevname(rdev0->bdev,b));
4881                 INIT_LIST_HEAD(&candidates);
4882                 rdev_for_each_list(rdev, tmp, &pending_raid_disks)
4883                         if (super_90_load(rdev, rdev0, 0) >= 0) {
4884                                 printk(KERN_INFO "md:  adding %s ...\n",
4885                                         bdevname(rdev->bdev,b));
4886                                 list_move(&rdev->same_set, &candidates);
4887                         }
4888                 /*
4889                  * now we have a set of devices, with all of them having
4890                  * mostly sane superblocks. It's time to allocate the
4891                  * mddev.
4892                  */
4893                 if (part) {
4894                         dev = MKDEV(mdp_major,
4895                                     rdev0->preferred_minor << MdpMinorShift);
4896                         unit = MINOR(dev) >> MdpMinorShift;
4897                 } else {
4898                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
4899                         unit = MINOR(dev);
4900                 }
4901                 if (rdev0->preferred_minor != unit) {
4902                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
4903                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
4904                         break;
4905                 }
4906
4907                 md_probe(dev, NULL, NULL);
4908                 mddev = mddev_find(dev);
4909                 if (!mddev || !mddev->gendisk) {
4910                         if (mddev)
4911                                 mddev_put(mddev);
4912                         printk(KERN_ERR
4913                                 "md: cannot allocate memory for md drive.\n");
4914                         break;
4915                 }
4916                 if (mddev_lock(mddev)) 
4917                         printk(KERN_WARNING "md: %s locked, cannot run\n",
4918                                mdname(mddev));
4919                 else if (mddev->raid_disks || mddev->major_version
4920                          || !list_empty(&mddev->disks)) {
4921                         printk(KERN_WARNING 
4922                                 "md: %s already running, cannot run %s\n",
4923                                 mdname(mddev), bdevname(rdev0->bdev,b));
4924                         mddev_unlock(mddev);
4925                 } else {
4926                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
4927                         mddev->persistent = 1;
4928                         rdev_for_each_list(rdev, tmp, &candidates) {
4929                                 list_del_init(&rdev->same_set);
4930                                 if (bind_rdev_to_array(rdev, mddev))
4931                                         export_rdev(rdev);
4932                         }
4933                         autorun_array(mddev);
4934                         mddev_unlock(mddev);
4935                 }
4936                 /* on success, candidates will be empty, on error
4937                  * it won't...
4938                  */
4939                 rdev_for_each_list(rdev, tmp, &candidates) {
4940                         list_del_init(&rdev->same_set);
4941                         export_rdev(rdev);
4942                 }
4943                 mddev_put(mddev);
4944         }
4945         printk(KERN_INFO "md: ... autorun DONE.\n");
4946 }
4947 #endif /* !MODULE */
4948
4949 static int get_version(void __user * arg)
4950 {
4951         mdu_version_t ver;
4952
4953         ver.major = MD_MAJOR_VERSION;
4954         ver.minor = MD_MINOR_VERSION;
4955         ver.patchlevel = MD_PATCHLEVEL_VERSION;
4956
4957         if (copy_to_user(arg, &ver, sizeof(ver)))
4958                 return -EFAULT;
4959
4960         return 0;
4961 }
4962
4963 static int get_array_info(mddev_t * mddev, void __user * arg)
4964 {
4965         mdu_array_info_t info;
4966         int nr,working,insync,failed,spare;
4967         mdk_rdev_t *rdev;
4968
4969         nr=working=insync=failed=spare=0;
4970         list_for_each_entry(rdev, &mddev->disks, same_set) {
4971                 nr++;
4972                 if (test_bit(Faulty, &rdev->flags))
4973                         failed++;
4974                 else {
4975                         working++;
4976                         if (test_bit(In_sync, &rdev->flags))
4977                                 insync++;       
4978                         else
4979                                 spare++;
4980                 }
4981         }
4982
4983         info.major_version = mddev->major_version;
4984         info.minor_version = mddev->minor_version;
4985         info.patch_version = MD_PATCHLEVEL_VERSION;
4986         info.ctime         = mddev->ctime;
4987         info.level         = mddev->level;
4988         info.size          = mddev->dev_sectors / 2;
4989         if (info.size != mddev->dev_sectors / 2) /* overflow */
4990                 info.size = -1;
4991         info.nr_disks      = nr;
4992         info.raid_disks    = mddev->raid_disks;
4993         info.md_minor      = mddev->md_minor;
4994         info.not_persistent= !mddev->persistent;
4995
4996         info.utime         = mddev->utime;
4997         info.state         = 0;
4998         if (mddev->in_sync)
4999                 info.state = (1<<MD_SB_CLEAN);
5000         if (mddev->bitmap && mddev->bitmap_info.offset)
5001                 info.state = (1<<MD_SB_BITMAP_PRESENT);
5002         info.active_disks  = insync;
5003         info.working_disks = working;
5004         info.failed_disks  = failed;
5005         info.spare_disks   = spare;
5006
5007         info.layout        = mddev->layout;
5008         info.chunk_size    = mddev->chunk_sectors << 9;
5009
5010         if (copy_to_user(arg, &info, sizeof(info)))
5011                 return -EFAULT;
5012
5013         return 0;
5014 }
5015
5016 static int get_bitmap_file(mddev_t * mddev, void __user * arg)
5017 {
5018         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
5019         char *ptr, *buf = NULL;
5020         int err = -ENOMEM;
5021
5022         if (md_allow_write(mddev))
5023                 file = kmalloc(sizeof(*file), GFP_NOIO);
5024         else
5025                 file = kmalloc(sizeof(*file), GFP_KERNEL);
5026
5027         if (!file)
5028                 goto out;
5029
5030         /* bitmap disabled, zero the first byte and copy out */
5031         if (!mddev->bitmap || !mddev->bitmap->file) {
5032                 file->pathname[0] = '\0';
5033                 goto copy_out;
5034         }
5035
5036         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
5037         if (!buf)
5038                 goto out;
5039
5040         ptr = d_path(&mddev->bitmap->file->f_path, buf, sizeof(file->pathname));
5041         if (IS_ERR(ptr))
5042                 goto out;
5043
5044         strcpy(file->pathname, ptr);
5045
5046 copy_out:
5047         err = 0;
5048         if (copy_to_user(arg, file, sizeof(*file)))
5049                 err = -EFAULT;
5050 out:
5051         kfree(buf);
5052         kfree(file);
5053         return err;
5054 }
5055
5056 static int get_disk_info(mddev_t * mddev, void __user * arg)
5057 {
5058         mdu_disk_info_t info;
5059         mdk_rdev_t *rdev;
5060
5061         if (copy_from_user(&info, arg, sizeof(info)))
5062                 return -EFAULT;
5063
5064         rdev = find_rdev_nr(mddev, info.number);
5065         if (rdev) {
5066                 info.major = MAJOR(rdev->bdev->bd_dev);
5067                 info.minor = MINOR(rdev->bdev->bd_dev);
5068                 info.raid_disk = rdev->raid_disk;
5069                 info.state = 0;
5070                 if (test_bit(Faulty, &rdev->flags))
5071                         info.state |= (1<<MD_DISK_FAULTY);
5072                 else if (test_bit(In_sync, &rdev->flags)) {
5073                         info.state |= (1<<MD_DISK_ACTIVE);
5074                         info.state |= (1<<MD_DISK_SYNC);
5075                 }
5076                 if (test_bit(WriteMostly, &rdev->flags))
5077                         info.state |= (1<<MD_DISK_WRITEMOSTLY);
5078         } else {
5079                 info.major = info.minor = 0;
5080                 info.raid_disk = -1;
5081                 info.state = (1<<MD_DISK_REMOVED);
5082         }
5083
5084         if (copy_to_user(arg, &info, sizeof(info)))
5085                 return -EFAULT;
5086
5087         return 0;
5088 }
5089
5090 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
5091 {
5092         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
5093         mdk_rdev_t *rdev;
5094         dev_t dev = MKDEV(info->major,info->minor);
5095
5096         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
5097                 return -EOVERFLOW;
5098
5099         if (!mddev->raid_disks) {
5100                 int err;
5101                 /* expecting a device which has a superblock */
5102                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
5103                 if (IS_ERR(rdev)) {
5104                         printk(KERN_WARNING 
5105                                 "md: md_import_device returned %ld\n",
5106                                 PTR_ERR(rdev));
5107                         return PTR_ERR(rdev);
5108                 }
5109                 if (!list_empty(&mddev->disks)) {
5110                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
5111                                                         mdk_rdev_t, same_set);
5112                         err = super_types[mddev->major_version]
5113                                 .load_super(rdev, rdev0, mddev->minor_version);
5114                         if (err < 0) {
5115                                 printk(KERN_WARNING 
5116                                         "md: %s has different UUID to %s\n",
5117                                         bdevname(rdev->bdev,b), 
5118                                         bdevname(rdev0->bdev,b2));
5119                                 export_rdev(rdev);
5120                                 return -EINVAL;
5121                         }
5122                 }
5123                 err = bind_rdev_to_array(rdev, mddev);
5124                 if (err)
5125                         export_rdev(rdev);
5126                 return err;
5127         }
5128
5129         /*
5130          * add_new_disk can be used once the array is assembled
5131          * to add "hot spares".  They must already have a superblock
5132          * written
5133          */
5134         if (mddev->pers) {
5135                 int err;
5136                 if (!mddev->pers->hot_add_disk) {
5137                         printk(KERN_WARNING 
5138                                 "%s: personality does not support diskops!\n",
5139                                mdname(mddev));
5140                         return -EINVAL;
5141                 }
5142                 if (mddev->persistent)
5143                         rdev = md_import_device(dev, mddev->major_version,
5144                                                 mddev->minor_version);
5145                 else
5146                         rdev = md_import_device(dev, -1, -1);
5147                 if (IS_ERR(rdev)) {
5148                         printk(KERN_WARNING 
5149                                 "md: md_import_device returned %ld\n",
5150                                 PTR_ERR(rdev));
5151                         return PTR_ERR(rdev);
5152                 }
5153                 /* set save_raid_disk if appropriate */
5154                 if (!mddev->persistent) {
5155                         if (info->state & (1<<MD_DISK_SYNC)  &&
5156                             info->raid_disk < mddev->raid_disks)
5157                                 rdev->raid_disk = info->raid_disk;
5158                         else
5159                                 rdev->raid_disk = -1;
5160                 } else
5161                         super_types[mddev->major_version].
5162                                 validate_super(mddev, rdev);
5163                 rdev->saved_raid_disk = rdev->raid_disk;
5164
5165                 clear_bit(In_sync, &rdev->flags); /* just to be sure */
5166                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5167                         set_bit(WriteMostly, &rdev->flags);
5168                 else
5169                         clear_bit(WriteMostly, &rdev->flags);
5170
5171                 rdev->raid_disk = -1;
5172                 err = bind_rdev_to_array(rdev, mddev);
5173                 if (!err && !mddev->pers->hot_remove_disk) {
5174                         /* If there is hot_add_disk but no hot_remove_disk
5175                          * then added disks for geometry changes,
5176                          * and should be added immediately.
5177                          */
5178                         super_types[mddev->major_version].
5179                                 validate_super(mddev, rdev);
5180                         err = mddev->pers->hot_add_disk(mddev, rdev);
5181                         if (err)
5182                                 unbind_rdev_from_array(rdev);
5183                 }
5184                 if (err)
5185                         export_rdev(rdev);
5186                 else
5187                         sysfs_notify_dirent_safe(rdev->sysfs_state);
5188
5189                 md_update_sb(mddev, 1);
5190                 if (mddev->degraded)
5191                         set_bit(MD_RECOVERY_RECOVER, &mddev->recovery);
5192                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5193                 md_wakeup_thread(mddev->thread);
5194                 return err;
5195         }
5196
5197         /* otherwise, add_new_disk is only allowed
5198          * for major_version==0 superblocks
5199          */
5200         if (mddev->major_version != 0) {
5201                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
5202                        mdname(mddev));
5203                 return -EINVAL;
5204         }
5205
5206         if (!(info->state & (1<<MD_DISK_FAULTY))) {
5207                 int err;
5208                 rdev = md_import_device(dev, -1, 0);
5209                 if (IS_ERR(rdev)) {
5210                         printk(KERN_WARNING 
5211                                 "md: error, md_import_device() returned %ld\n",
5212                                 PTR_ERR(rdev));
5213                         return PTR_ERR(rdev);
5214                 }
5215                 rdev->desc_nr = info->number;
5216                 if (info->raid_disk < mddev->raid_disks)
5217                         rdev->raid_disk = info->raid_disk;
5218                 else
5219                         rdev->raid_disk = -1;
5220
5221                 if (rdev->raid_disk < mddev->raid_disks)
5222                         if (info->state & (1<<MD_DISK_SYNC))
5223                                 set_bit(In_sync, &rdev->flags);
5224
5225                 if (info->state & (1<<MD_DISK_WRITEMOSTLY))
5226                         set_bit(WriteMostly, &rdev->flags);
5227
5228                 if (!mddev->persistent) {
5229                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
5230                         rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
5231                 } else 
5232                         rdev->sb_start = calc_dev_sboffset(rdev->bdev);
5233                 rdev->sectors = rdev->sb_start;
5234
5235                 err = bind_rdev_to_array(rdev, mddev);
5236                 if (err) {
5237                         export_rdev(rdev);
5238                         return err;
5239                 }
5240         }
5241
5242         return 0;
5243 }
5244
5245 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
5246 {
5247         char b[BDEVNAME_SIZE];
5248         mdk_rdev_t *rdev;
5249
5250         rdev = find_rdev(mddev, dev);
5251         if (!rdev)
5252                 return -ENXIO;
5253
5254         if (rdev->raid_disk >= 0)
5255                 goto busy;
5256
5257         kick_rdev_from_array(rdev);
5258         md_update_sb(mddev, 1);
5259         md_new_event(mddev);
5260
5261         return 0;
5262 busy:
5263         printk(KERN_WARNING "md: cannot remove active disk %s from %s ...\n",
5264                 bdevname(rdev->bdev,b), mdname(mddev));
5265         return -EBUSY;
5266 }
5267
5268 static int hot_add_disk(mddev_t * mddev, dev_t dev)
5269 {
5270         char b[BDEVNAME_SIZE];
5271         int err;
5272         mdk_rdev_t *rdev;
5273
5274         if (!mddev->pers)
5275                 return -ENODEV;
5276
5277         if (mddev->major_version != 0) {
5278                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
5279                         " version-0 superblocks.\n",
5280                         mdname(mddev));
5281                 return -EINVAL;
5282         }
5283         if (!mddev->pers->hot_add_disk) {
5284                 printk(KERN_WARNING 
5285                         "%s: personality does not support diskops!\n",
5286                         mdname(mddev));
5287                 return -EINVAL;
5288         }
5289
5290         rdev = md_import_device(dev, -1, 0);
5291         if (IS_ERR(rdev)) {
5292                 printk(KERN_WARNING 
5293                         "md: error, md_import_device() returned %ld\n",
5294                         PTR_ERR(rdev));
5295                 return -EINVAL;
5296         }
5297
5298         if (mddev->persistent)
5299                 rdev->sb_start = calc_dev_sboffset(rdev->bdev);
5300         else
5301                 rdev->sb_start = rdev->bdev->bd_inode->i_size / 512;
5302
5303         rdev->sectors = rdev->sb_start;
5304
5305         if (test_bit(Faulty, &rdev->flags)) {
5306                 printk(KERN_WARNING 
5307                         "md: can not hot-add faulty %s disk to %s!\n",
5308                         bdevname(rdev->bdev,b), mdname(mddev));
5309                 err = -EINVAL;
5310                 goto abort_export;
5311         }
5312         clear_bit(In_sync, &rdev->flags);
5313         rdev->desc_nr = -1;
5314         rdev->saved_raid_disk = -1;
5315         err = bind_rdev_to_array(rdev, mddev);
5316         if (err)
5317                 goto abort_export;
5318
5319         /*
5320          * The rest should better be atomic, we can have disk failures
5321          * noticed in interrupt contexts ...
5322          */
5323
5324         rdev->raid_disk = -1;
5325
5326         md_update_sb(mddev, 1);
5327
5328         /*
5329          * Kick recovery, maybe this spare has to be added to the
5330          * array immediately.
5331          */
5332         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5333         md_wakeup_thread(mddev->thread);
5334         md_new_event(mddev);
5335         return 0;
5336
5337 abort_export:
5338         export_rdev(rdev);
5339         return err;
5340 }
5341
5342 static int set_bitmap_file(mddev_t *mddev, int fd)
5343 {
5344         int err;
5345
5346         if (mddev->pers) {
5347                 if (!mddev->pers->quiesce)
5348                         return -EBUSY;
5349                 if (mddev->recovery || mddev->sync_thread)
5350                         return -EBUSY;
5351                 /* we should be able to change the bitmap.. */
5352         }
5353
5354
5355         if (fd >= 0) {
5356                 if (mddev->bitmap)
5357                         return -EEXIST; /* cannot add when bitmap is present */
5358                 mddev->bitmap_info.file = fget(fd);
5359
5360                 if (mddev->bitmap_info.file == NULL) {
5361                         printk(KERN_ERR "%s: error: failed to get bitmap file\n",
5362                                mdname(mddev));
5363                         return -EBADF;
5364                 }
5365
5366                 err = deny_bitmap_write_access(mddev->bitmap_info.file);
5367                 if (err) {
5368                         printk(KERN_ERR "%s: error: bitmap file is already in use\n",
5369                                mdname(mddev));
5370                         fput(mddev->bitmap_info.file);
5371                         mddev->bitmap_info.file = NULL;
5372                         return err;
5373                 }
5374                 mddev->bitmap_info.offset = 0; /* file overrides offset */
5375         } else if (mddev->bitmap == NULL)
5376                 return -ENOENT; /* cannot remove what isn't there */
5377         err = 0;
5378         if (mddev->pers) {
5379                 mddev->pers->quiesce(mddev, 1);
5380                 if (fd >= 0) {
5381                         err = bitmap_create(mddev);
5382                         if (!err)
5383                                 err = bitmap_load(mddev);
5384                 }
5385                 if (fd < 0 || err) {
5386                         bitmap_destroy(mddev);
5387                         fd = -1; /* make sure to put the file */
5388                 }
5389                 mddev->pers->quiesce(mddev, 0);
5390         }
5391         if (fd < 0) {
5392                 if (mddev->bitmap_info.file) {
5393                         restore_bitmap_write_access(mddev->bitmap_info.file);
5394                         fput(mddev->bitmap_info.file);
5395                 }
5396                 mddev->bitmap_info.file = NULL;
5397         }
5398
5399         return err;
5400 }
5401
5402 /*
5403  * set_array_info is used two different ways
5404  * The original usage is when creating a new array.
5405  * In this usage, raid_disks is > 0 and it together with
5406  *  level, size, not_persistent,layout,chunksize determine the
5407  *  shape of the array.
5408  *  This will always create an array with a type-0.90.0 superblock.
5409  * The newer usage is when assembling an array.
5410  *  In this case raid_disks will be 0, and the major_version field is
5411  *  use to determine which style super-blocks are to be found on the devices.
5412  *  The minor and patch _version numbers are also kept incase the
5413  *  super_block handler wishes to interpret them.
5414  */
5415 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
5416 {
5417
5418         if (info->raid_disks == 0) {
5419                 /* just setting version number for superblock loading */
5420                 if (info->major_version < 0 ||
5421                     info->major_version >= ARRAY_SIZE(super_types) ||
5422                     super_types[info->major_version].name == NULL) {
5423                         /* maybe try to auto-load a module? */
5424                         printk(KERN_INFO 
5425                                 "md: superblock version %d not known\n",
5426                                 info->major_version);
5427                         return -EINVAL;
5428                 }
5429                 mddev->major_version = info->major_version;
5430                 mddev->minor_version = info->minor_version;
5431                 mddev->patch_version = info->patch_version;
5432                 mddev->persistent = !info->not_persistent;
5433                 /* ensure mddev_put doesn't delete this now that there
5434                  * is some minimal configuration.
5435                  */
5436                 mddev->ctime         = get_seconds();
5437                 return 0;
5438         }
5439         mddev->major_version = MD_MAJOR_VERSION;
5440         mddev->minor_version = MD_MINOR_VERSION;
5441         mddev->patch_version = MD_PATCHLEVEL_VERSION;
5442         mddev->ctime         = get_seconds();
5443
5444         mddev->level         = info->level;
5445         mddev->clevel[0]     = 0;
5446         mddev->dev_sectors   = 2 * (sector_t)info->size;
5447         mddev->raid_disks    = info->raid_disks;
5448         /* don't set md_minor, it is determined by which /dev/md* was
5449          * openned
5450          */
5451         if (info->state & (1<<MD_SB_CLEAN))
5452                 mddev->recovery_cp = MaxSector;
5453         else
5454                 mddev->recovery_cp = 0;
5455         mddev->persistent    = ! info->not_persistent;
5456         mddev->external      = 0;
5457
5458         mddev->layout        = info->layout;
5459         mddev->chunk_sectors = info->chunk_size >> 9;
5460
5461         mddev->max_disks     = MD_SB_DISKS;
5462
5463         if (mddev->persistent)
5464                 mddev->flags         = 0;
5465         set_bit(MD_CHANGE_DEVS, &mddev->flags);
5466
5467         mddev->bitmap_info.default_offset = MD_SB_BYTES >> 9;
5468         mddev->bitmap_info.offset = 0;
5469
5470         mddev->reshape_position = MaxSector;
5471
5472         /*
5473          * Generate a 128 bit UUID
5474          */
5475         get_random_bytes(mddev->uuid, 16);
5476
5477         mddev->new_level = mddev->level;
5478         mddev->new_chunk_sectors = mddev->chunk_sectors;
5479         mddev->new_layout = mddev->layout;
5480         mddev->delta_disks = 0;
5481
5482         return 0;
5483 }
5484
5485 void md_set_array_sectors(mddev_t *mddev, sector_t array_sectors)
5486 {
5487         WARN(!mddev_is_locked(mddev), "%s: unlocked mddev!\n", __func__);
5488
5489         if (mddev->external_size)
5490                 return;
5491
5492         mddev->array_sectors = array_sectors;
5493 }
5494 EXPORT_SYMBOL(md_set_array_sectors);
5495
5496 static int update_size(mddev_t *mddev, sector_t num_sectors)
5497 {
5498         mdk_rdev_t *rdev;
5499         int rv;
5500         int fit = (num_sectors == 0);
5501
5502         if (mddev->pers->resize == NULL)
5503                 return -EINVAL;
5504         /* The "num_sectors" is the number of sectors of each device that
5505          * is used.  This can only make sense for arrays with redundancy.
5506          * linear and raid0 always use whatever space is available. We can only
5507          * consider changing this number if no resync or reconstruction is
5508          * happening, and if the new size is acceptable. It must fit before the
5509          * sb_start or, if that is <data_offset, it must fit before the size
5510          * of each device.  If num_sectors is zero, we find the largest size
5511          * that fits.
5512
5513          */
5514         if (mddev->sync_thread)
5515                 return -EBUSY;
5516         if (mddev->bitmap)
5517                 /* Sorry, cannot grow a bitmap yet, just remove it,
5518                  * grow, and re-add.
5519                  */
5520                 return -EBUSY;
5521         list_for_each_entry(rdev, &mddev->disks, same_set) {
5522                 sector_t avail = rdev->sectors;
5523
5524                 if (fit && (num_sectors == 0 || num_sectors > avail))
5525                         num_sectors = avail;
5526                 if (avail < num_sectors)
5527                         return -ENOSPC;
5528         }
5529         rv = mddev->pers->resize(mddev, num_sectors);
5530         if (!rv)
5531                 revalidate_disk(mddev->gendisk);
5532         return rv;
5533 }
5534
5535 static int update_raid_disks(mddev_t *mddev, int raid_disks)
5536 {
5537         int rv;
5538         /* change the number of raid disks */
5539         if (mddev->pers->check_reshape == NULL)
5540                 return -EINVAL;
5541         if (raid_disks <= 0 ||
5542             (mddev->max_disks && raid_disks >= mddev->max_disks))
5543                 return -EINVAL;
5544         if (mddev->sync_thread || mddev->reshape_position != MaxSector)
5545                 return -EBUSY;
5546         mddev->delta_disks = raid_disks - mddev->raid_disks;
5547
5548         rv = mddev->pers->check_reshape(mddev);
5549         return rv;
5550 }
5551
5552
5553 /*
5554  * update_array_info is used to change the configuration of an
5555  * on-line array.
5556  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
5557  * fields in the info are checked against the array.
5558  * Any differences that cannot be handled will cause an error.
5559  * Normally, only one change can be managed at a time.
5560  */
5561 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
5562 {
5563         int rv = 0;
5564         int cnt = 0;
5565         int state = 0;
5566
5567         /* calculate expected state,ignoring low bits */
5568         if (mddev->bitmap && mddev->bitmap_info.offset)
5569                 state |= (1 << MD_SB_BITMAP_PRESENT);
5570
5571         if (mddev->major_version != info->major_version ||
5572             mddev->minor_version != info->minor_version ||
5573 /*          mddev->patch_version != info->patch_version || */
5574             mddev->ctime         != info->ctime         ||
5575             mddev->level         != info->level         ||
5576 /*          mddev->layout        != info->layout        || */
5577             !mddev->persistent   != info->not_persistent||
5578             mddev->chunk_sectors != info->chunk_size >> 9 ||
5579             /* ignore bottom 8 bits of state, and allow SB_BITMAP_PRESENT to change */
5580             ((state^info->state) & 0xfffffe00)
5581                 )
5582                 return -EINVAL;
5583         /* Check there is only one change */
5584         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5585                 cnt++;
5586         if (mddev->raid_disks != info->raid_disks)
5587                 cnt++;
5588         if (mddev->layout != info->layout)
5589                 cnt++;
5590         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT))
5591                 cnt++;
5592         if (cnt == 0)
5593                 return 0;
5594         if (cnt > 1)
5595                 return -EINVAL;
5596
5597         if (mddev->layout != info->layout) {
5598                 /* Change layout
5599                  * we don't need to do anything at the md level, the
5600                  * personality will take care of it all.
5601                  */
5602                 if (mddev->pers->check_reshape == NULL)
5603                         return -EINVAL;
5604                 else {
5605                         mddev->new_layout = info->layout;
5606                         rv = mddev->pers->check_reshape(mddev);
5607                         if (rv)
5608                                 mddev->new_layout = mddev->layout;
5609                         return rv;
5610                 }
5611         }
5612         if (info->size >= 0 && mddev->dev_sectors / 2 != info->size)
5613                 rv = update_size(mddev, (sector_t)info->size * 2);
5614
5615         if (mddev->raid_disks    != info->raid_disks)
5616                 rv = update_raid_disks(mddev, info->raid_disks);
5617
5618         if ((state ^ info->state) & (1<<MD_SB_BITMAP_PRESENT)) {
5619                 if (mddev->pers->quiesce == NULL)
5620                         return -EINVAL;
5621                 if (mddev->recovery || mddev->sync_thread)
5622                         return -EBUSY;
5623                 if (info->state & (1<<MD_SB_BITMAP_PRESENT)) {
5624                         /* add the bitmap */
5625                         if (mddev->bitmap)
5626                                 return -EEXIST;
5627                         if (mddev->bitmap_info.default_offset == 0)
5628                                 return -EINVAL;
5629                         mddev->bitmap_info.offset =
5630                                 mddev->bitmap_info.default_offset;
5631                         mddev->pers->quiesce(mddev, 1);
5632                         rv = bitmap_create(mddev);
5633                         if (!rv)
5634                                 rv = bitmap_load(mddev);
5635                         if (rv)
5636                                 bitmap_destroy(mddev);
5637                         mddev->pers->quiesce(mddev, 0);
5638                 } else {
5639                         /* remove the bitmap */
5640                         if (!mddev->bitmap)
5641                                 return -ENOENT;
5642                         if (mddev->bitmap->file)
5643                                 return -EINVAL;
5644                         mddev->pers->quiesce(mddev, 1);
5645                         bitmap_destroy(mddev);
5646                         mddev->pers->quiesce(mddev, 0);
5647                         mddev->bitmap_info.offset = 0;
5648                 }
5649         }
5650         md_update_sb(mddev, 1);
5651         return rv;
5652 }
5653
5654 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
5655 {
5656         mdk_rdev_t *rdev;
5657
5658         if (mddev->pers == NULL)
5659                 return -ENODEV;
5660
5661         rdev = find_rdev(mddev, dev);
5662         if (!rdev)
5663                 return -ENODEV;
5664
5665         md_error(mddev, rdev);
5666         return 0;
5667 }
5668
5669 /*
5670  * We have a problem here : there is no easy way to give a CHS
5671  * virtual geometry. We currently pretend that we have a 2 heads
5672  * 4 sectors (with a BIG number of cylinders...). This drives
5673  * dosfs just mad... ;-)
5674  */
5675 static int md_getgeo(struct block_device *bdev, struct hd_geometry *geo)
5676 {
5677         mddev_t *mddev = bdev->bd_disk->private_data;
5678
5679         geo->heads = 2;
5680         geo->sectors = 4;
5681         geo->cylinders = mddev->array_sectors / 8;
5682         return 0;
5683 }
5684
5685 static int md_ioctl(struct block_device *bdev, fmode_t mode,
5686                         unsigned int cmd, unsigned long arg)
5687 {
5688         int err = 0;
5689         void __user *argp = (void __user *)arg;
5690         mddev_t *mddev = NULL;
5691         int ro;
5692
5693         if (!capable(CAP_SYS_ADMIN))
5694                 return -EACCES;
5695
5696         /*
5697          * Commands dealing with the RAID driver but not any
5698          * particular array:
5699          */
5700         switch (cmd)
5701         {
5702                 case RAID_VERSION:
5703                         err = get_version(argp);
5704                         goto done;
5705
5706                 case PRINT_RAID_DEBUG:
5707                         err = 0;
5708                         md_print_devices();
5709                         goto done;
5710
5711 #ifndef MODULE
5712                 case RAID_AUTORUN:
5713                         err = 0;
5714                         autostart_arrays(arg);
5715                         goto done;
5716 #endif
5717                 default:;
5718         }
5719
5720         /*
5721          * Commands creating/starting a new array:
5722          */
5723
5724         mddev = bdev->bd_disk->private_data;
5725
5726         if (!mddev) {
5727                 BUG();
5728                 goto abort;
5729         }
5730
5731         err = mddev_lock(mddev);
5732         if (err) {
5733                 printk(KERN_INFO 
5734                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
5735                         err, cmd);
5736                 goto abort;
5737         }
5738
5739         switch (cmd)
5740         {
5741                 case SET_ARRAY_INFO:
5742                         {
5743                                 mdu_array_info_t info;
5744                                 if (!arg)
5745                                         memset(&info, 0, sizeof(info));
5746                                 else if (copy_from_user(&info, argp, sizeof(info))) {
5747                                         err = -EFAULT;
5748                                         goto abort_unlock;
5749                                 }
5750                                 if (mddev->pers) {
5751                                         err = update_array_info(mddev, &info);
5752                                         if (err) {
5753                                                 printk(KERN_WARNING "md: couldn't update"
5754                                                        " array info. %d\n", err);
5755                                                 goto abort_unlock;
5756                                         }
5757                                         goto done_unlock;
5758                                 }
5759                                 if (!list_empty(&mddev->disks)) {
5760                                         printk(KERN_WARNING
5761                                                "md: array %s already has disks!\n",
5762                                                mdname(mddev));
5763                                         err = -EBUSY;
5764                                         goto abort_unlock;
5765                                 }
5766                                 if (mddev->raid_disks) {
5767                                         printk(KERN_WARNING
5768                                                "md: array %s already initialised!\n",
5769                                                mdname(mddev));
5770                                         err = -EBUSY;
5771                                         goto abort_unlock;
5772                                 }
5773                                 err = set_array_info(mddev, &info);
5774                                 if (err) {
5775                                         printk(KERN_WARNING "md: couldn't set"
5776                                                " array info. %d\n", err);
5777                                         goto abort_unlock;
5778                                 }
5779                         }
5780                         goto done_unlock;
5781
5782                 default:;
5783         }
5784
5785         /*
5786          * Commands querying/configuring an existing array:
5787          */
5788         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
5789          * RUN_ARRAY, and GET_ and SET_BITMAP_FILE are allowed */
5790         if ((!mddev->raid_disks && !mddev->external)
5791             && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
5792             && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE
5793             && cmd != GET_BITMAP_FILE) {
5794                 err = -ENODEV;
5795                 goto abort_unlock;
5796         }
5797
5798         /*
5799          * Commands even a read-only array can execute:
5800          */
5801         switch (cmd)
5802         {
5803                 case GET_ARRAY_INFO:
5804                         err = get_array_info(mddev, argp);
5805                         goto done_unlock;
5806
5807                 case GET_BITMAP_FILE:
5808                         err = get_bitmap_file(mddev, argp);
5809                         goto done_unlock;
5810
5811                 case GET_DISK_INFO:
5812                         err = get_disk_info(mddev, argp);
5813                         goto done_unlock;
5814
5815                 case RESTART_ARRAY_RW:
5816                         err = restart_array(mddev);
5817                         goto done_unlock;
5818
5819                 case STOP_ARRAY:
5820                         err = do_md_stop(mddev, 0, 1);
5821                         goto done_unlock;
5822
5823                 case STOP_ARRAY_RO:
5824                         err = md_set_readonly(mddev, 1);
5825                         goto done_unlock;
5826
5827                 case BLKROSET:
5828                         if (get_user(ro, (int __user *)(arg))) {
5829                                 err = -EFAULT;
5830                                 goto done_unlock;
5831                         }
5832                         err = -EINVAL;
5833
5834                         /* if the bdev is going readonly the value of mddev->ro
5835                          * does not matter, no writes are coming
5836                          */
5837                         if (ro)
5838                                 goto done_unlock;
5839
5840                         /* are we are already prepared for writes? */
5841                         if (mddev->ro != 1)
5842                                 goto done_unlock;
5843
5844                         /* transitioning to readauto need only happen for
5845                          * arrays that call md_write_start
5846                          */
5847                         if (mddev->pers) {
5848                                 err = restart_array(mddev);
5849                                 if (err == 0) {
5850                                         mddev->ro = 2;
5851                                         set_disk_ro(mddev->gendisk, 0);
5852                                 }
5853                         }
5854                         goto done_unlock;
5855         }
5856
5857         /*
5858          * The remaining ioctls are changing the state of the
5859          * superblock, so we do not allow them on read-only arrays.
5860          * However non-MD ioctls (e.g. get-size) will still come through
5861          * here and hit the 'default' below, so only disallow
5862          * 'md' ioctls, and switch to rw mode if started auto-readonly.
5863          */
5864         if (_IOC_TYPE(cmd) == MD_MAJOR && mddev->ro && mddev->pers) {
5865                 if (mddev->ro == 2) {
5866                         mddev->ro = 0;
5867                         sysfs_notify_dirent_safe(mddev->sysfs_state);
5868                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
5869                         md_wakeup_thread(mddev->thread);
5870                 } else {
5871                         err = -EROFS;
5872                         goto abort_unlock;
5873                 }
5874         }
5875
5876         switch (cmd)
5877         {
5878                 case ADD_NEW_DISK:
5879                 {
5880                         mdu_disk_info_t info;
5881                         if (copy_from_user(&info, argp, sizeof(info)))
5882                                 err = -EFAULT;
5883                         else
5884                                 err = add_new_disk(mddev, &info);
5885                         goto done_unlock;
5886                 }
5887
5888                 case HOT_REMOVE_DISK:
5889                         err = hot_remove_disk(mddev, new_decode_dev(arg));
5890                         goto done_unlock;
5891
5892                 case HOT_ADD_DISK:
5893                         err = hot_add_disk(mddev, new_decode_dev(arg));
5894                         goto done_unlock;
5895
5896                 case SET_DISK_FAULTY:
5897                         err = set_disk_faulty(mddev, new_decode_dev(arg));
5898                         goto done_unlock;
5899
5900                 case RUN_ARRAY:
5901                         err = do_md_run(mddev);
5902                         goto done_unlock;
5903
5904                 case SET_BITMAP_FILE:
5905                         err = set_bitmap_file(mddev, (int)arg);
5906                         goto done_unlock;
5907
5908                 default:
5909                         err = -EINVAL;
5910                         goto abort_unlock;
5911         }
5912
5913 done_unlock:
5914 abort_unlock:
5915         if (mddev->hold_active == UNTIL_IOCTL &&
5916             err != -EINVAL)
5917                 mddev->hold_active = 0;
5918         mddev_unlock(mddev);
5919
5920         return err;
5921 done:
5922         if (err)
5923                 MD_BUG();
5924 abort:
5925         return err;
5926 }
5927 #ifdef CONFIG_COMPAT
5928 static int md_compat_ioctl(struct block_device *bdev, fmode_t mode,
5929                     unsigned int cmd, unsigned long arg)
5930 {
5931         switch (cmd) {
5932         case HOT_REMOVE_DISK:
5933         case HOT_ADD_DISK:
5934         case SET_DISK_FAULTY:
5935         case SET_BITMAP_FILE:
5936                 /* These take in integer arg, do not convert */
5937                 break;
5938         default:
5939                 arg = (unsigned long)compat_ptr(arg);
5940                 break;
5941         }
5942
5943         return md_ioctl(bdev, mode, cmd, arg);
5944 }
5945 #endif /* CONFIG_COMPAT */
5946
5947 static int md_open(struct block_device *bdev, fmode_t mode)
5948 {
5949         /*
5950          * Succeed if we can lock the mddev, which confirms that
5951          * it isn't being stopped right now.