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