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