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