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