[PATCH] md: make sure md bitmap updates are flushed when array is stopped.
[linux-2.6.git] / drivers / md / md.c
1 /*
2    md.c : Multiple Devices driver for Linux
3           Copyright (C) 1998, 1999, 2000 Ingo Molnar
4
5      completely rewritten, based on the MD driver code from Marc Zyngier
6
7    Changes:
8
9    - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
10    - RAID-6 extensions by H. Peter Anvin <hpa@zytor.com>
11    - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
12    - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
13    - kmod support by: Cyrus Durgin
14    - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
15    - Devfs support by Richard Gooch <rgooch@atnf.csiro.au>
16
17    - lots of fixes and improvements to the RAID1/RAID5 and generic
18      RAID code (such as request based resynchronization):
19
20      Neil Brown <neilb@cse.unsw.edu.au>.
21
22    - persistent bitmap code
23      Copyright (C) 2003-2004, Paul Clements, SteelEye Technology, Inc.
24
25    This program is free software; you can redistribute it and/or modify
26    it under the terms of the GNU General Public License as published by
27    the Free Software Foundation; either version 2, or (at your option)
28    any later version.
29
30    You should have received a copy of the GNU General Public License
31    (for example /usr/src/linux/COPYING); if not, write to the Free
32    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
33 */
34
35 #include <linux/module.h>
36 #include <linux/config.h>
37 #include <linux/linkage.h>
38 #include <linux/raid/md.h>
39 #include <linux/raid/bitmap.h>
40 #include <linux/sysctl.h>
41 #include <linux/devfs_fs_kernel.h>
42 #include <linux/buffer_head.h> /* for invalidate_bdev */
43 #include <linux/suspend.h>
44
45 #include <linux/init.h>
46
47 #include <linux/file.h>
48
49 #ifdef CONFIG_KMOD
50 #include <linux/kmod.h>
51 #endif
52
53 #include <asm/unaligned.h>
54
55 #define MAJOR_NR MD_MAJOR
56 #define MD_DRIVER
57
58 /* 63 partitions with the alternate major number (mdp) */
59 #define MdpMinorShift 6
60
61 #define DEBUG 0
62 #define dprintk(x...) ((void)(DEBUG && printk(x)))
63
64
65 #ifndef MODULE
66 static void autostart_arrays (int part);
67 #endif
68
69 static mdk_personality_t *pers[MAX_PERSONALITY];
70 static DEFINE_SPINLOCK(pers_lock);
71
72 /*
73  * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
74  * is 1000 KB/sec, so the extra system load does not show up that much.
75  * Increase it if you want to have more _guaranteed_ speed. Note that
76  * the RAID driver will use the maximum available bandwith if the IO
77  * subsystem is idle. There is also an 'absolute maximum' reconstruction
78  * speed limit - in case reconstruction slows down your system despite
79  * idle IO detection.
80  *
81  * you can change it via /proc/sys/dev/raid/speed_limit_min and _max.
82  */
83
84 static int sysctl_speed_limit_min = 1000;
85 static int sysctl_speed_limit_max = 200000;
86
87 static struct ctl_table_header *raid_table_header;
88
89 static ctl_table raid_table[] = {
90         {
91                 .ctl_name       = DEV_RAID_SPEED_LIMIT_MIN,
92                 .procname       = "speed_limit_min",
93                 .data           = &sysctl_speed_limit_min,
94                 .maxlen         = sizeof(int),
95                 .mode           = 0644,
96                 .proc_handler   = &proc_dointvec,
97         },
98         {
99                 .ctl_name       = DEV_RAID_SPEED_LIMIT_MAX,
100                 .procname       = "speed_limit_max",
101                 .data           = &sysctl_speed_limit_max,
102                 .maxlen         = sizeof(int),
103                 .mode           = 0644,
104                 .proc_handler   = &proc_dointvec,
105         },
106         { .ctl_name = 0 }
107 };
108
109 static ctl_table raid_dir_table[] = {
110         {
111                 .ctl_name       = DEV_RAID,
112                 .procname       = "raid",
113                 .maxlen         = 0,
114                 .mode           = 0555,
115                 .child          = raid_table,
116         },
117         { .ctl_name = 0 }
118 };
119
120 static ctl_table raid_root_table[] = {
121         {
122                 .ctl_name       = CTL_DEV,
123                 .procname       = "dev",
124                 .maxlen         = 0,
125                 .mode           = 0555,
126                 .child          = raid_dir_table,
127         },
128         { .ctl_name = 0 }
129 };
130
131 static struct block_device_operations md_fops;
132
133 /*
134  * Enables to iterate over all existing md arrays
135  * all_mddevs_lock protects this list.
136  */
137 static LIST_HEAD(all_mddevs);
138 static DEFINE_SPINLOCK(all_mddevs_lock);
139
140
141 /*
142  * iterates through all used mddevs in the system.
143  * We take care to grab the all_mddevs_lock whenever navigating
144  * the list, and to always hold a refcount when unlocked.
145  * Any code which breaks out of this loop while own
146  * a reference to the current mddev and must mddev_put it.
147  */
148 #define ITERATE_MDDEV(mddev,tmp)                                        \
149                                                                         \
150         for (({ spin_lock(&all_mddevs_lock);                            \
151                 tmp = all_mddevs.next;                                  \
152                 mddev = NULL;});                                        \
153              ({ if (tmp != &all_mddevs)                                 \
154                         mddev_get(list_entry(tmp, mddev_t, all_mddevs));\
155                 spin_unlock(&all_mddevs_lock);                          \
156                 if (mddev) mddev_put(mddev);                            \
157                 mddev = list_entry(tmp, mddev_t, all_mddevs);           \
158                 tmp != &all_mddevs;});                                  \
159              ({ spin_lock(&all_mddevs_lock);                            \
160                 tmp = tmp->next;})                                      \
161                 )
162
163
164 static int md_fail_request (request_queue_t *q, struct bio *bio)
165 {
166         bio_io_error(bio, bio->bi_size);
167         return 0;
168 }
169
170 static inline mddev_t *mddev_get(mddev_t *mddev)
171 {
172         atomic_inc(&mddev->active);
173         return mddev;
174 }
175
176 static void mddev_put(mddev_t *mddev)
177 {
178         if (!atomic_dec_and_lock(&mddev->active, &all_mddevs_lock))
179                 return;
180         if (!mddev->raid_disks && list_empty(&mddev->disks)) {
181                 list_del(&mddev->all_mddevs);
182                 blk_put_queue(mddev->queue);
183                 kfree(mddev);
184         }
185         spin_unlock(&all_mddevs_lock);
186 }
187
188 static mddev_t * mddev_find(dev_t unit)
189 {
190         mddev_t *mddev, *new = NULL;
191
192  retry:
193         spin_lock(&all_mddevs_lock);
194         list_for_each_entry(mddev, &all_mddevs, all_mddevs)
195                 if (mddev->unit == unit) {
196                         mddev_get(mddev);
197                         spin_unlock(&all_mddevs_lock);
198                         kfree(new);
199                         return mddev;
200                 }
201
202         if (new) {
203                 list_add(&new->all_mddevs, &all_mddevs);
204                 spin_unlock(&all_mddevs_lock);
205                 return new;
206         }
207         spin_unlock(&all_mddevs_lock);
208
209         new = (mddev_t *) kmalloc(sizeof(*new), GFP_KERNEL);
210         if (!new)
211                 return NULL;
212
213         memset(new, 0, sizeof(*new));
214
215         new->unit = unit;
216         if (MAJOR(unit) == MD_MAJOR)
217                 new->md_minor = MINOR(unit);
218         else
219                 new->md_minor = MINOR(unit) >> MdpMinorShift;
220
221         init_MUTEX(&new->reconfig_sem);
222         INIT_LIST_HEAD(&new->disks);
223         INIT_LIST_HEAD(&new->all_mddevs);
224         init_timer(&new->safemode_timer);
225         atomic_set(&new->active, 1);
226         spin_lock_init(&new->write_lock);
227         init_waitqueue_head(&new->sb_wait);
228
229         new->queue = blk_alloc_queue(GFP_KERNEL);
230         if (!new->queue) {
231                 kfree(new);
232                 return NULL;
233         }
234
235         blk_queue_make_request(new->queue, md_fail_request);
236
237         goto retry;
238 }
239
240 static inline int mddev_lock(mddev_t * mddev)
241 {
242         return down_interruptible(&mddev->reconfig_sem);
243 }
244
245 static inline void mddev_lock_uninterruptible(mddev_t * mddev)
246 {
247         down(&mddev->reconfig_sem);
248 }
249
250 static inline int mddev_trylock(mddev_t * mddev)
251 {
252         return down_trylock(&mddev->reconfig_sem);
253 }
254
255 static inline void mddev_unlock(mddev_t * mddev)
256 {
257         up(&mddev->reconfig_sem);
258
259         if (mddev->thread)
260                 md_wakeup_thread(mddev->thread);
261 }
262
263 mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
264 {
265         mdk_rdev_t * rdev;
266         struct list_head *tmp;
267
268         ITERATE_RDEV(mddev,rdev,tmp) {
269                 if (rdev->desc_nr == nr)
270                         return rdev;
271         }
272         return NULL;
273 }
274
275 static mdk_rdev_t * find_rdev(mddev_t * mddev, dev_t dev)
276 {
277         struct list_head *tmp;
278         mdk_rdev_t *rdev;
279
280         ITERATE_RDEV(mddev,rdev,tmp) {
281                 if (rdev->bdev->bd_dev == dev)
282                         return rdev;
283         }
284         return NULL;
285 }
286
287 static inline sector_t calc_dev_sboffset(struct block_device *bdev)
288 {
289         sector_t size = bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
290         return MD_NEW_SIZE_BLOCKS(size);
291 }
292
293 static sector_t calc_dev_size(mdk_rdev_t *rdev, unsigned chunk_size)
294 {
295         sector_t size;
296
297         size = rdev->sb_offset;
298
299         if (chunk_size)
300                 size &= ~((sector_t)chunk_size/1024 - 1);
301         return size;
302 }
303
304 static int alloc_disk_sb(mdk_rdev_t * rdev)
305 {
306         if (rdev->sb_page)
307                 MD_BUG();
308
309         rdev->sb_page = alloc_page(GFP_KERNEL);
310         if (!rdev->sb_page) {
311                 printk(KERN_ALERT "md: out of memory.\n");
312                 return -EINVAL;
313         }
314
315         return 0;
316 }
317
318 static void free_disk_sb(mdk_rdev_t * rdev)
319 {
320         if (rdev->sb_page) {
321                 page_cache_release(rdev->sb_page);
322                 rdev->sb_loaded = 0;
323                 rdev->sb_page = NULL;
324                 rdev->sb_offset = 0;
325                 rdev->size = 0;
326         }
327 }
328
329
330 static int super_written(struct bio *bio, unsigned int bytes_done, int error)
331 {
332         mdk_rdev_t *rdev = bio->bi_private;
333         if (bio->bi_size)
334                 return 1;
335
336         if (error || !test_bit(BIO_UPTODATE, &bio->bi_flags))
337                 md_error(rdev->mddev, rdev);
338
339         if (atomic_dec_and_test(&rdev->mddev->pending_writes))
340                 wake_up(&rdev->mddev->sb_wait);
341         bio_put(bio);
342         return 0;
343 }
344
345 void md_super_write(mddev_t *mddev, mdk_rdev_t *rdev,
346                    sector_t sector, int size, struct page *page)
347 {
348         /* write first size bytes of page to sector of rdev
349          * Increment mddev->pending_writes before returning
350          * and decrement it on completion, waking up sb_wait
351          * if zero is reached.
352          * If an error occurred, call md_error
353          */
354         struct bio *bio = bio_alloc(GFP_NOIO, 1);
355
356         bio->bi_bdev = rdev->bdev;
357         bio->bi_sector = sector;
358         bio_add_page(bio, page, size, 0);
359         bio->bi_private = rdev;
360         bio->bi_end_io = super_written;
361         atomic_inc(&mddev->pending_writes);
362         submit_bio((1<<BIO_RW)|(1<<BIO_RW_SYNC), bio);
363 }
364
365 static int bi_complete(struct bio *bio, unsigned int bytes_done, int error)
366 {
367         if (bio->bi_size)
368                 return 1;
369
370         complete((struct completion*)bio->bi_private);
371         return 0;
372 }
373
374 int sync_page_io(struct block_device *bdev, sector_t sector, int size,
375                    struct page *page, int rw)
376 {
377         struct bio *bio = bio_alloc(GFP_NOIO, 1);
378         struct completion event;
379         int ret;
380
381         rw |= (1 << BIO_RW_SYNC);
382
383         bio->bi_bdev = bdev;
384         bio->bi_sector = sector;
385         bio_add_page(bio, page, size, 0);
386         init_completion(&event);
387         bio->bi_private = &event;
388         bio->bi_end_io = bi_complete;
389         submit_bio(rw, bio);
390         wait_for_completion(&event);
391
392         ret = test_bit(BIO_UPTODATE, &bio->bi_flags);
393         bio_put(bio);
394         return ret;
395 }
396
397 static int read_disk_sb(mdk_rdev_t * rdev)
398 {
399         char b[BDEVNAME_SIZE];
400         if (!rdev->sb_page) {
401                 MD_BUG();
402                 return -EINVAL;
403         }
404         if (rdev->sb_loaded)
405                 return 0;
406
407
408         if (!sync_page_io(rdev->bdev, rdev->sb_offset<<1, MD_SB_BYTES, rdev->sb_page, READ))
409                 goto fail;
410         rdev->sb_loaded = 1;
411         return 0;
412
413 fail:
414         printk(KERN_WARNING "md: disabled device %s, could not read superblock.\n",
415                 bdevname(rdev->bdev,b));
416         return -EINVAL;
417 }
418
419 static int uuid_equal(mdp_super_t *sb1, mdp_super_t *sb2)
420 {
421         if (    (sb1->set_uuid0 == sb2->set_uuid0) &&
422                 (sb1->set_uuid1 == sb2->set_uuid1) &&
423                 (sb1->set_uuid2 == sb2->set_uuid2) &&
424                 (sb1->set_uuid3 == sb2->set_uuid3))
425
426                 return 1;
427
428         return 0;
429 }
430
431
432 static int sb_equal(mdp_super_t *sb1, mdp_super_t *sb2)
433 {
434         int ret;
435         mdp_super_t *tmp1, *tmp2;
436
437         tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
438         tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
439
440         if (!tmp1 || !tmp2) {
441                 ret = 0;
442                 printk(KERN_INFO "md.c: sb1 is not equal to sb2!\n");
443                 goto abort;
444         }
445
446         *tmp1 = *sb1;
447         *tmp2 = *sb2;
448
449         /*
450          * nr_disks is not constant
451          */
452         tmp1->nr_disks = 0;
453         tmp2->nr_disks = 0;
454
455         if (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4))
456                 ret = 0;
457         else
458                 ret = 1;
459
460 abort:
461         kfree(tmp1);
462         kfree(tmp2);
463         return ret;
464 }
465
466 static unsigned int calc_sb_csum(mdp_super_t * sb)
467 {
468         unsigned int disk_csum, csum;
469
470         disk_csum = sb->sb_csum;
471         sb->sb_csum = 0;
472         csum = csum_partial((void *)sb, MD_SB_BYTES, 0);
473         sb->sb_csum = disk_csum;
474         return csum;
475 }
476
477
478 /*
479  * Handle superblock details.
480  * We want to be able to handle multiple superblock formats
481  * so we have a common interface to them all, and an array of
482  * different handlers.
483  * We rely on user-space to write the initial superblock, and support
484  * reading and updating of superblocks.
485  * Interface methods are:
486  *   int load_super(mdk_rdev_t *dev, mdk_rdev_t *refdev, int minor_version)
487  *      loads and validates a superblock on dev.
488  *      if refdev != NULL, compare superblocks on both devices
489  *    Return:
490  *      0 - dev has a superblock that is compatible with refdev
491  *      1 - dev has a superblock that is compatible and newer than refdev
492  *          so dev should be used as the refdev in future
493  *     -EINVAL superblock incompatible or invalid
494  *     -othererror e.g. -EIO
495  *
496  *   int validate_super(mddev_t *mddev, mdk_rdev_t *dev)
497  *      Verify that dev is acceptable into mddev.
498  *       The first time, mddev->raid_disks will be 0, and data from
499  *       dev should be merged in.  Subsequent calls check that dev
500  *       is new enough.  Return 0 or -EINVAL
501  *
502  *   void sync_super(mddev_t *mddev, mdk_rdev_t *dev)
503  *     Update the superblock for rdev with data in mddev
504  *     This does not write to disc.
505  *
506  */
507
508 struct super_type  {
509         char            *name;
510         struct module   *owner;
511         int             (*load_super)(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version);
512         int             (*validate_super)(mddev_t *mddev, mdk_rdev_t *rdev);
513         void            (*sync_super)(mddev_t *mddev, mdk_rdev_t *rdev);
514 };
515
516 /*
517  * load_super for 0.90.0 
518  */
519 static int super_90_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
520 {
521         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
522         mdp_super_t *sb;
523         int ret;
524         sector_t sb_offset;
525
526         /*
527          * Calculate the position of the superblock,
528          * it's at the end of the disk.
529          *
530          * It also happens to be a multiple of 4Kb.
531          */
532         sb_offset = calc_dev_sboffset(rdev->bdev);
533         rdev->sb_offset = sb_offset;
534
535         ret = read_disk_sb(rdev);
536         if (ret) return ret;
537
538         ret = -EINVAL;
539
540         bdevname(rdev->bdev, b);
541         sb = (mdp_super_t*)page_address(rdev->sb_page);
542
543         if (sb->md_magic != MD_SB_MAGIC) {
544                 printk(KERN_ERR "md: invalid raid superblock magic on %s\n",
545                        b);
546                 goto abort;
547         }
548
549         if (sb->major_version != 0 ||
550             sb->minor_version != 90) {
551                 printk(KERN_WARNING "Bad version number %d.%d on %s\n",
552                         sb->major_version, sb->minor_version,
553                         b);
554                 goto abort;
555         }
556
557         if (sb->raid_disks <= 0)
558                 goto abort;
559
560         if (csum_fold(calc_sb_csum(sb)) != csum_fold(sb->sb_csum)) {
561                 printk(KERN_WARNING "md: invalid superblock checksum on %s\n",
562                         b);
563                 goto abort;
564         }
565
566         rdev->preferred_minor = sb->md_minor;
567         rdev->data_offset = 0;
568
569         if (sb->level == LEVEL_MULTIPATH)
570                 rdev->desc_nr = -1;
571         else
572                 rdev->desc_nr = sb->this_disk.number;
573
574         if (refdev == 0)
575                 ret = 1;
576         else {
577                 __u64 ev1, ev2;
578                 mdp_super_t *refsb = (mdp_super_t*)page_address(refdev->sb_page);
579                 if (!uuid_equal(refsb, sb)) {
580                         printk(KERN_WARNING "md: %s has different UUID to %s\n",
581                                 b, bdevname(refdev->bdev,b2));
582                         goto abort;
583                 }
584                 if (!sb_equal(refsb, sb)) {
585                         printk(KERN_WARNING "md: %s has same UUID"
586                                " but different superblock to %s\n",
587                                b, bdevname(refdev->bdev, b2));
588                         goto abort;
589                 }
590                 ev1 = md_event(sb);
591                 ev2 = md_event(refsb);
592                 if (ev1 > ev2)
593                         ret = 1;
594                 else 
595                         ret = 0;
596         }
597         rdev->size = calc_dev_size(rdev, sb->chunk_size);
598
599  abort:
600         return ret;
601 }
602
603 /*
604  * validate_super for 0.90.0
605  */
606 static int super_90_validate(mddev_t *mddev, mdk_rdev_t *rdev)
607 {
608         mdp_disk_t *desc;
609         mdp_super_t *sb = (mdp_super_t *)page_address(rdev->sb_page);
610
611         rdev->raid_disk = -1;
612         rdev->in_sync = 0;
613         if (mddev->raid_disks == 0) {
614                 mddev->major_version = 0;
615                 mddev->minor_version = sb->minor_version;
616                 mddev->patch_version = sb->patch_version;
617                 mddev->persistent = ! sb->not_persistent;
618                 mddev->chunk_size = sb->chunk_size;
619                 mddev->ctime = sb->ctime;
620                 mddev->utime = sb->utime;
621                 mddev->level = sb->level;
622                 mddev->layout = sb->layout;
623                 mddev->raid_disks = sb->raid_disks;
624                 mddev->size = sb->size;
625                 mddev->events = md_event(sb);
626
627                 if (sb->state & (1<<MD_SB_CLEAN))
628                         mddev->recovery_cp = MaxSector;
629                 else {
630                         if (sb->events_hi == sb->cp_events_hi && 
631                                 sb->events_lo == sb->cp_events_lo) {
632                                 mddev->recovery_cp = sb->recovery_cp;
633                         } else
634                                 mddev->recovery_cp = 0;
635                 }
636
637                 memcpy(mddev->uuid+0, &sb->set_uuid0, 4);
638                 memcpy(mddev->uuid+4, &sb->set_uuid1, 4);
639                 memcpy(mddev->uuid+8, &sb->set_uuid2, 4);
640                 memcpy(mddev->uuid+12,&sb->set_uuid3, 4);
641
642                 mddev->max_disks = MD_SB_DISKS;
643
644                 if (sb->state & (1<<MD_SB_BITMAP_PRESENT) &&
645                     mddev->bitmap_file == NULL) {
646                         if (mddev->level != 1) {
647                                 /* FIXME use a better test */
648                                 printk(KERN_WARNING "md: bitmaps only support for raid1\n");
649                                 return -EINVAL;
650                         }
651                         mddev->bitmap_offset = (MD_SB_BYTES >> 9);
652                 }
653
654         } else if (mddev->pers == NULL) {
655                 /* Insist on good event counter while assembling */
656                 __u64 ev1 = md_event(sb);
657                 ++ev1;
658                 if (ev1 < mddev->events) 
659                         return -EINVAL;
660         } else if (mddev->bitmap) {
661                 /* if adding to array with a bitmap, then we can accept an
662                  * older device ... but not too old.
663                  */
664                 __u64 ev1 = md_event(sb);
665                 if (ev1 < mddev->bitmap->events_cleared)
666                         return 0;
667         } else /* just a hot-add of a new device, leave raid_disk at -1 */
668                 return 0;
669
670         if (mddev->level != LEVEL_MULTIPATH) {
671                 rdev->faulty = 0;
672                 desc = sb->disks + rdev->desc_nr;
673
674                 if (desc->state & (1<<MD_DISK_FAULTY))
675                         rdev->faulty = 1;
676                 else if (desc->state & (1<<MD_DISK_SYNC) &&
677                          desc->raid_disk < mddev->raid_disks) {
678                         rdev->in_sync = 1;
679                         rdev->raid_disk = desc->raid_disk;
680                 }
681         } else /* MULTIPATH are always insync */
682                 rdev->in_sync = 1;
683         return 0;
684 }
685
686 /*
687  * sync_super for 0.90.0
688  */
689 static void super_90_sync(mddev_t *mddev, mdk_rdev_t *rdev)
690 {
691         mdp_super_t *sb;
692         struct list_head *tmp;
693         mdk_rdev_t *rdev2;
694         int next_spare = mddev->raid_disks;
695
696         /* make rdev->sb match mddev data..
697          *
698          * 1/ zero out disks
699          * 2/ Add info for each disk, keeping track of highest desc_nr (next_spare);
700          * 3/ any empty disks < next_spare become removed
701          *
702          * disks[0] gets initialised to REMOVED because
703          * we cannot be sure from other fields if it has
704          * been initialised or not.
705          */
706         int i;
707         int active=0, working=0,failed=0,spare=0,nr_disks=0;
708
709         sb = (mdp_super_t*)page_address(rdev->sb_page);
710
711         memset(sb, 0, sizeof(*sb));
712
713         sb->md_magic = MD_SB_MAGIC;
714         sb->major_version = mddev->major_version;
715         sb->minor_version = mddev->minor_version;
716         sb->patch_version = mddev->patch_version;
717         sb->gvalid_words  = 0; /* ignored */
718         memcpy(&sb->set_uuid0, mddev->uuid+0, 4);
719         memcpy(&sb->set_uuid1, mddev->uuid+4, 4);
720         memcpy(&sb->set_uuid2, mddev->uuid+8, 4);
721         memcpy(&sb->set_uuid3, mddev->uuid+12,4);
722
723         sb->ctime = mddev->ctime;
724         sb->level = mddev->level;
725         sb->size  = mddev->size;
726         sb->raid_disks = mddev->raid_disks;
727         sb->md_minor = mddev->md_minor;
728         sb->not_persistent = !mddev->persistent;
729         sb->utime = mddev->utime;
730         sb->state = 0;
731         sb->events_hi = (mddev->events>>32);
732         sb->events_lo = (u32)mddev->events;
733
734         if (mddev->in_sync)
735         {
736                 sb->recovery_cp = mddev->recovery_cp;
737                 sb->cp_events_hi = (mddev->events>>32);
738                 sb->cp_events_lo = (u32)mddev->events;
739                 if (mddev->recovery_cp == MaxSector)
740                         sb->state = (1<< MD_SB_CLEAN);
741         } else
742                 sb->recovery_cp = 0;
743
744         sb->layout = mddev->layout;
745         sb->chunk_size = mddev->chunk_size;
746
747         if (mddev->bitmap && mddev->bitmap_file == NULL)
748                 sb->state |= (1<<MD_SB_BITMAP_PRESENT);
749
750         sb->disks[0].state = (1<<MD_DISK_REMOVED);
751         ITERATE_RDEV(mddev,rdev2,tmp) {
752                 mdp_disk_t *d;
753                 if (rdev2->raid_disk >= 0 && rdev2->in_sync && !rdev2->faulty)
754                         rdev2->desc_nr = rdev2->raid_disk;
755                 else
756                         rdev2->desc_nr = next_spare++;
757                 d = &sb->disks[rdev2->desc_nr];
758                 nr_disks++;
759                 d->number = rdev2->desc_nr;
760                 d->major = MAJOR(rdev2->bdev->bd_dev);
761                 d->minor = MINOR(rdev2->bdev->bd_dev);
762                 if (rdev2->raid_disk >= 0 && rdev->in_sync && !rdev2->faulty)
763                         d->raid_disk = rdev2->raid_disk;
764                 else
765                         d->raid_disk = rdev2->desc_nr; /* compatibility */
766                 if (rdev2->faulty) {
767                         d->state = (1<<MD_DISK_FAULTY);
768                         failed++;
769                 } else if (rdev2->in_sync) {
770                         d->state = (1<<MD_DISK_ACTIVE);
771                         d->state |= (1<<MD_DISK_SYNC);
772                         active++;
773                         working++;
774                 } else {
775                         d->state = 0;
776                         spare++;
777                         working++;
778                 }
779         }
780         
781         /* now set the "removed" and "faulty" bits on any missing devices */
782         for (i=0 ; i < mddev->raid_disks ; i++) {
783                 mdp_disk_t *d = &sb->disks[i];
784                 if (d->state == 0 && d->number == 0) {
785                         d->number = i;
786                         d->raid_disk = i;
787                         d->state = (1<<MD_DISK_REMOVED);
788                         d->state |= (1<<MD_DISK_FAULTY);
789                         failed++;
790                 }
791         }
792         sb->nr_disks = nr_disks;
793         sb->active_disks = active;
794         sb->working_disks = working;
795         sb->failed_disks = failed;
796         sb->spare_disks = spare;
797
798         sb->this_disk = sb->disks[rdev->desc_nr];
799         sb->sb_csum = calc_sb_csum(sb);
800 }
801
802 /*
803  * version 1 superblock
804  */
805
806 static unsigned int calc_sb_1_csum(struct mdp_superblock_1 * sb)
807 {
808         unsigned int disk_csum, csum;
809         unsigned long long newcsum;
810         int size = 256 + le32_to_cpu(sb->max_dev)*2;
811         unsigned int *isuper = (unsigned int*)sb;
812         int i;
813
814         disk_csum = sb->sb_csum;
815         sb->sb_csum = 0;
816         newcsum = 0;
817         for (i=0; size>=4; size -= 4 )
818                 newcsum += le32_to_cpu(*isuper++);
819
820         if (size == 2)
821                 newcsum += le16_to_cpu(*(unsigned short*) isuper);
822
823         csum = (newcsum & 0xffffffff) + (newcsum >> 32);
824         sb->sb_csum = disk_csum;
825         return cpu_to_le32(csum);
826 }
827
828 static int super_1_load(mdk_rdev_t *rdev, mdk_rdev_t *refdev, int minor_version)
829 {
830         struct mdp_superblock_1 *sb;
831         int ret;
832         sector_t sb_offset;
833         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
834
835         /*
836          * Calculate the position of the superblock.
837          * It is always aligned to a 4K boundary and
838          * depeding on minor_version, it can be:
839          * 0: At least 8K, but less than 12K, from end of device
840          * 1: At start of device
841          * 2: 4K from start of device.
842          */
843         switch(minor_version) {
844         case 0:
845                 sb_offset = rdev->bdev->bd_inode->i_size >> 9;
846                 sb_offset -= 8*2;
847                 sb_offset &= ~(sector_t)(4*2-1);
848                 /* convert from sectors to K */
849                 sb_offset /= 2;
850                 break;
851         case 1:
852                 sb_offset = 0;
853                 break;
854         case 2:
855                 sb_offset = 4;
856                 break;
857         default:
858                 return -EINVAL;
859         }
860         rdev->sb_offset = sb_offset;
861
862         ret = read_disk_sb(rdev);
863         if (ret) return ret;
864
865
866         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
867
868         if (sb->magic != cpu_to_le32(MD_SB_MAGIC) ||
869             sb->major_version != cpu_to_le32(1) ||
870             le32_to_cpu(sb->max_dev) > (4096-256)/2 ||
871             le64_to_cpu(sb->super_offset) != (rdev->sb_offset<<1) ||
872             sb->feature_map != 0)
873                 return -EINVAL;
874
875         if (calc_sb_1_csum(sb) != sb->sb_csum) {
876                 printk("md: invalid superblock checksum on %s\n",
877                         bdevname(rdev->bdev,b));
878                 return -EINVAL;
879         }
880         if (le64_to_cpu(sb->data_size) < 10) {
881                 printk("md: data_size too small on %s\n",
882                        bdevname(rdev->bdev,b));
883                 return -EINVAL;
884         }
885         rdev->preferred_minor = 0xffff;
886         rdev->data_offset = le64_to_cpu(sb->data_offset);
887
888         if (refdev == 0)
889                 return 1;
890         else {
891                 __u64 ev1, ev2;
892                 struct mdp_superblock_1 *refsb = 
893                         (struct mdp_superblock_1*)page_address(refdev->sb_page);
894
895                 if (memcmp(sb->set_uuid, refsb->set_uuid, 16) != 0 ||
896                     sb->level != refsb->level ||
897                     sb->layout != refsb->layout ||
898                     sb->chunksize != refsb->chunksize) {
899                         printk(KERN_WARNING "md: %s has strangely different"
900                                 " superblock to %s\n",
901                                 bdevname(rdev->bdev,b),
902                                 bdevname(refdev->bdev,b2));
903                         return -EINVAL;
904                 }
905                 ev1 = le64_to_cpu(sb->events);
906                 ev2 = le64_to_cpu(refsb->events);
907
908                 if (ev1 > ev2)
909                         return 1;
910         }
911         if (minor_version) 
912                 rdev->size = ((rdev->bdev->bd_inode->i_size>>9) - le64_to_cpu(sb->data_offset)) / 2;
913         else
914                 rdev->size = rdev->sb_offset;
915         if (rdev->size < le64_to_cpu(sb->data_size)/2)
916                 return -EINVAL;
917         rdev->size = le64_to_cpu(sb->data_size)/2;
918         if (le32_to_cpu(sb->chunksize))
919                 rdev->size &= ~((sector_t)le32_to_cpu(sb->chunksize)/2 - 1);
920         return 0;
921 }
922
923 static int super_1_validate(mddev_t *mddev, mdk_rdev_t *rdev)
924 {
925         struct mdp_superblock_1 *sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
926
927         rdev->raid_disk = -1;
928         rdev->in_sync = 0;
929         if (mddev->raid_disks == 0) {
930                 mddev->major_version = 1;
931                 mddev->patch_version = 0;
932                 mddev->persistent = 1;
933                 mddev->chunk_size = le32_to_cpu(sb->chunksize) << 9;
934                 mddev->ctime = le64_to_cpu(sb->ctime) & ((1ULL << 32)-1);
935                 mddev->utime = le64_to_cpu(sb->utime) & ((1ULL << 32)-1);
936                 mddev->level = le32_to_cpu(sb->level);
937                 mddev->layout = le32_to_cpu(sb->layout);
938                 mddev->raid_disks = le32_to_cpu(sb->raid_disks);
939                 mddev->size = le64_to_cpu(sb->size)/2;
940                 mddev->events = le64_to_cpu(sb->events);
941                 
942                 mddev->recovery_cp = le64_to_cpu(sb->resync_offset);
943                 memcpy(mddev->uuid, sb->set_uuid, 16);
944
945                 mddev->max_disks =  (4096-256)/2;
946
947                 if ((le32_to_cpu(sb->feature_map) & 1) &&
948                     mddev->bitmap_file == NULL ) {
949                         if (mddev->level != 1) {
950                                 printk(KERN_WARNING "md: bitmaps only supported for raid1\n");
951                                 return -EINVAL;
952                         }
953                         mddev->bitmap_offset = (__s32)le32_to_cpu(sb->bitmap_offset);
954                 }
955         } else if (mddev->pers == NULL) {
956                 /* Insist of good event counter while assembling */
957                 __u64 ev1 = le64_to_cpu(sb->events);
958                 ++ev1;
959                 if (ev1 < mddev->events)
960                         return -EINVAL;
961         } else if (mddev->bitmap) {
962                 /* If adding to array with a bitmap, then we can accept an
963                  * older device, but not too old.
964                  */
965                 __u64 ev1 = le64_to_cpu(sb->events);
966                 if (ev1 < mddev->bitmap->events_cleared)
967                         return 0;
968         } else /* just a hot-add of a new device, leave raid_disk at -1 */
969                 return 0;
970
971         if (mddev->level != LEVEL_MULTIPATH) {
972                 int role;
973                 rdev->desc_nr = le32_to_cpu(sb->dev_number);
974                 role = le16_to_cpu(sb->dev_roles[rdev->desc_nr]);
975                 switch(role) {
976                 case 0xffff: /* spare */
977                         rdev->faulty = 0;
978                         break;
979                 case 0xfffe: /* faulty */
980                         rdev->faulty = 1;
981                         break;
982                 default:
983                         rdev->in_sync = 1;
984                         rdev->faulty = 0;
985                         rdev->raid_disk = role;
986                         break;
987                 }
988         } else /* MULTIPATH are always insync */
989                 rdev->in_sync = 1;
990
991         return 0;
992 }
993
994 static void super_1_sync(mddev_t *mddev, mdk_rdev_t *rdev)
995 {
996         struct mdp_superblock_1 *sb;
997         struct list_head *tmp;
998         mdk_rdev_t *rdev2;
999         int max_dev, i;
1000         /* make rdev->sb match mddev and rdev data. */
1001
1002         sb = (struct mdp_superblock_1*)page_address(rdev->sb_page);
1003
1004         sb->feature_map = 0;
1005         sb->pad0 = 0;
1006         memset(sb->pad1, 0, sizeof(sb->pad1));
1007         memset(sb->pad2, 0, sizeof(sb->pad2));
1008         memset(sb->pad3, 0, sizeof(sb->pad3));
1009
1010         sb->utime = cpu_to_le64((__u64)mddev->utime);
1011         sb->events = cpu_to_le64(mddev->events);
1012         if (mddev->in_sync)
1013                 sb->resync_offset = cpu_to_le64(mddev->recovery_cp);
1014         else
1015                 sb->resync_offset = cpu_to_le64(0);
1016
1017         if (mddev->bitmap && mddev->bitmap_file == NULL) {
1018                 sb->bitmap_offset = cpu_to_le32((__u32)mddev->bitmap_offset);
1019                 sb->feature_map = cpu_to_le32(1);
1020         }
1021
1022         max_dev = 0;
1023         ITERATE_RDEV(mddev,rdev2,tmp)
1024                 if (rdev2->desc_nr+1 > max_dev)
1025                         max_dev = rdev2->desc_nr+1;
1026         
1027         sb->max_dev = cpu_to_le32(max_dev);
1028         for (i=0; i<max_dev;i++)
1029                 sb->dev_roles[i] = cpu_to_le16(0xfffe);
1030         
1031         ITERATE_RDEV(mddev,rdev2,tmp) {
1032                 i = rdev2->desc_nr;
1033                 if (rdev2->faulty)
1034                         sb->dev_roles[i] = cpu_to_le16(0xfffe);
1035                 else if (rdev2->in_sync)
1036                         sb->dev_roles[i] = cpu_to_le16(rdev2->raid_disk);
1037                 else
1038                         sb->dev_roles[i] = cpu_to_le16(0xffff);
1039         }
1040
1041         sb->recovery_offset = cpu_to_le64(0); /* not supported yet */
1042         sb->sb_csum = calc_sb_1_csum(sb);
1043 }
1044
1045
1046 static struct super_type super_types[] = {
1047         [0] = {
1048                 .name   = "0.90.0",
1049                 .owner  = THIS_MODULE,
1050                 .load_super     = super_90_load,
1051                 .validate_super = super_90_validate,
1052                 .sync_super     = super_90_sync,
1053         },
1054         [1] = {
1055                 .name   = "md-1",
1056                 .owner  = THIS_MODULE,
1057                 .load_super     = super_1_load,
1058                 .validate_super = super_1_validate,
1059                 .sync_super     = super_1_sync,
1060         },
1061 };
1062         
1063 static mdk_rdev_t * match_dev_unit(mddev_t *mddev, mdk_rdev_t *dev)
1064 {
1065         struct list_head *tmp;
1066         mdk_rdev_t *rdev;
1067
1068         ITERATE_RDEV(mddev,rdev,tmp)
1069                 if (rdev->bdev->bd_contains == dev->bdev->bd_contains)
1070                         return rdev;
1071
1072         return NULL;
1073 }
1074
1075 static int match_mddev_units(mddev_t *mddev1, mddev_t *mddev2)
1076 {
1077         struct list_head *tmp;
1078         mdk_rdev_t *rdev;
1079
1080         ITERATE_RDEV(mddev1,rdev,tmp)
1081                 if (match_dev_unit(mddev2, rdev))
1082                         return 1;
1083
1084         return 0;
1085 }
1086
1087 static LIST_HEAD(pending_raid_disks);
1088
1089 static int bind_rdev_to_array(mdk_rdev_t * rdev, mddev_t * mddev)
1090 {
1091         mdk_rdev_t *same_pdev;
1092         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
1093
1094         if (rdev->mddev) {
1095                 MD_BUG();
1096                 return -EINVAL;
1097         }
1098         same_pdev = match_dev_unit(mddev, rdev);
1099         if (same_pdev)
1100                 printk(KERN_WARNING
1101                         "%s: WARNING: %s appears to be on the same physical"
1102                         " disk as %s. True\n     protection against single-disk"
1103                         " failure might be compromised.\n",
1104                         mdname(mddev), bdevname(rdev->bdev,b),
1105                         bdevname(same_pdev->bdev,b2));
1106
1107         /* Verify rdev->desc_nr is unique.
1108          * If it is -1, assign a free number, else
1109          * check number is not in use
1110          */
1111         if (rdev->desc_nr < 0) {
1112                 int choice = 0;
1113                 if (mddev->pers) choice = mddev->raid_disks;
1114                 while (find_rdev_nr(mddev, choice))
1115                         choice++;
1116                 rdev->desc_nr = choice;
1117         } else {
1118                 if (find_rdev_nr(mddev, rdev->desc_nr))
1119                         return -EBUSY;
1120         }
1121                         
1122         list_add(&rdev->same_set, &mddev->disks);
1123         rdev->mddev = mddev;
1124         printk(KERN_INFO "md: bind<%s>\n", bdevname(rdev->bdev,b));
1125         return 0;
1126 }
1127
1128 static void unbind_rdev_from_array(mdk_rdev_t * rdev)
1129 {
1130         char b[BDEVNAME_SIZE];
1131         if (!rdev->mddev) {
1132                 MD_BUG();
1133                 return;
1134         }
1135         list_del_init(&rdev->same_set);
1136         printk(KERN_INFO "md: unbind<%s>\n", bdevname(rdev->bdev,b));
1137         rdev->mddev = NULL;
1138 }
1139
1140 /*
1141  * prevent the device from being mounted, repartitioned or
1142  * otherwise reused by a RAID array (or any other kernel
1143  * subsystem), by bd_claiming the device.
1144  */
1145 static int lock_rdev(mdk_rdev_t *rdev, dev_t dev)
1146 {
1147         int err = 0;
1148         struct block_device *bdev;
1149         char b[BDEVNAME_SIZE];
1150
1151         bdev = open_by_devnum(dev, FMODE_READ|FMODE_WRITE);
1152         if (IS_ERR(bdev)) {
1153                 printk(KERN_ERR "md: could not open %s.\n",
1154                         __bdevname(dev, b));
1155                 return PTR_ERR(bdev);
1156         }
1157         err = bd_claim(bdev, rdev);
1158         if (err) {
1159                 printk(KERN_ERR "md: could not bd_claim %s.\n",
1160                         bdevname(bdev, b));
1161                 blkdev_put(bdev);
1162                 return err;
1163         }
1164         rdev->bdev = bdev;
1165         return err;
1166 }
1167
1168 static void unlock_rdev(mdk_rdev_t *rdev)
1169 {
1170         struct block_device *bdev = rdev->bdev;
1171         rdev->bdev = NULL;
1172         if (!bdev)
1173                 MD_BUG();
1174         bd_release(bdev);
1175         blkdev_put(bdev);
1176 }
1177
1178 void md_autodetect_dev(dev_t dev);
1179
1180 static void export_rdev(mdk_rdev_t * rdev)
1181 {
1182         char b[BDEVNAME_SIZE];
1183         printk(KERN_INFO "md: export_rdev(%s)\n",
1184                 bdevname(rdev->bdev,b));
1185         if (rdev->mddev)
1186                 MD_BUG();
1187         free_disk_sb(rdev);
1188         list_del_init(&rdev->same_set);
1189 #ifndef MODULE
1190         md_autodetect_dev(rdev->bdev->bd_dev);
1191 #endif
1192         unlock_rdev(rdev);
1193         kfree(rdev);
1194 }
1195
1196 static void kick_rdev_from_array(mdk_rdev_t * rdev)
1197 {
1198         unbind_rdev_from_array(rdev);
1199         export_rdev(rdev);
1200 }
1201
1202 static void export_array(mddev_t *mddev)
1203 {
1204         struct list_head *tmp;
1205         mdk_rdev_t *rdev;
1206
1207         ITERATE_RDEV(mddev,rdev,tmp) {
1208                 if (!rdev->mddev) {
1209                         MD_BUG();
1210                         continue;
1211                 }
1212                 kick_rdev_from_array(rdev);
1213         }
1214         if (!list_empty(&mddev->disks))
1215                 MD_BUG();
1216         mddev->raid_disks = 0;
1217         mddev->major_version = 0;
1218 }
1219
1220 static void print_desc(mdp_disk_t *desc)
1221 {
1222         printk(" DISK<N:%d,(%d,%d),R:%d,S:%d>\n", desc->number,
1223                 desc->major,desc->minor,desc->raid_disk,desc->state);
1224 }
1225
1226 static void print_sb(mdp_super_t *sb)
1227 {
1228         int i;
1229
1230         printk(KERN_INFO 
1231                 "md:  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
1232                 sb->major_version, sb->minor_version, sb->patch_version,
1233                 sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
1234                 sb->ctime);
1235         printk(KERN_INFO "md:     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n",
1236                 sb->level, sb->size, sb->nr_disks, sb->raid_disks,
1237                 sb->md_minor, sb->layout, sb->chunk_size);
1238         printk(KERN_INFO "md:     UT:%08x ST:%d AD:%d WD:%d"
1239                 " FD:%d SD:%d CSUM:%08x E:%08lx\n",
1240                 sb->utime, sb->state, sb->active_disks, sb->working_disks,
1241                 sb->failed_disks, sb->spare_disks,
1242                 sb->sb_csum, (unsigned long)sb->events_lo);
1243
1244         printk(KERN_INFO);
1245         for (i = 0; i < MD_SB_DISKS; i++) {
1246                 mdp_disk_t *desc;
1247
1248                 desc = sb->disks + i;
1249                 if (desc->number || desc->major || desc->minor ||
1250                     desc->raid_disk || (desc->state && (desc->state != 4))) {
1251                         printk("     D %2d: ", i);
1252                         print_desc(desc);
1253                 }
1254         }
1255         printk(KERN_INFO "md:     THIS: ");
1256         print_desc(&sb->this_disk);
1257
1258 }
1259
1260 static void print_rdev(mdk_rdev_t *rdev)
1261 {
1262         char b[BDEVNAME_SIZE];
1263         printk(KERN_INFO "md: rdev %s, SZ:%08llu F:%d S:%d DN:%u\n",
1264                 bdevname(rdev->bdev,b), (unsigned long long)rdev->size,
1265                 rdev->faulty, rdev->in_sync, rdev->desc_nr);
1266         if (rdev->sb_loaded) {
1267                 printk(KERN_INFO "md: rdev superblock:\n");
1268                 print_sb((mdp_super_t*)page_address(rdev->sb_page));
1269         } else
1270                 printk(KERN_INFO "md: no rdev superblock!\n");
1271 }
1272
1273 void md_print_devices(void)
1274 {
1275         struct list_head *tmp, *tmp2;
1276         mdk_rdev_t *rdev;
1277         mddev_t *mddev;
1278         char b[BDEVNAME_SIZE];
1279
1280         printk("\n");
1281         printk("md:     **********************************\n");
1282         printk("md:     * <COMPLETE RAID STATE PRINTOUT> *\n");
1283         printk("md:     **********************************\n");
1284         ITERATE_MDDEV(mddev,tmp) {
1285
1286                 if (mddev->bitmap)
1287                         bitmap_print_sb(mddev->bitmap);
1288                 else
1289                         printk("%s: ", mdname(mddev));
1290                 ITERATE_RDEV(mddev,rdev,tmp2)
1291                         printk("<%s>", bdevname(rdev->bdev,b));
1292                 printk("\n");
1293
1294                 ITERATE_RDEV(mddev,rdev,tmp2)
1295                         print_rdev(rdev);
1296         }
1297         printk("md:     **********************************\n");
1298         printk("\n");
1299 }
1300
1301
1302 static void sync_sbs(mddev_t * mddev)
1303 {
1304         mdk_rdev_t *rdev;
1305         struct list_head *tmp;
1306
1307         ITERATE_RDEV(mddev,rdev,tmp) {
1308                 super_types[mddev->major_version].
1309                         sync_super(mddev, rdev);
1310                 rdev->sb_loaded = 1;
1311         }
1312 }
1313
1314 static void md_update_sb(mddev_t * mddev)
1315 {
1316         int err;
1317         struct list_head *tmp;
1318         mdk_rdev_t *rdev;
1319         int sync_req;
1320
1321 repeat:
1322         spin_lock(&mddev->write_lock);
1323         sync_req = mddev->in_sync;
1324         mddev->utime = get_seconds();
1325         mddev->events ++;
1326
1327         if (!mddev->events) {
1328                 /*
1329                  * oops, this 64-bit counter should never wrap.
1330                  * Either we are in around ~1 trillion A.C., assuming
1331                  * 1 reboot per second, or we have a bug:
1332                  */
1333                 MD_BUG();
1334                 mddev->events --;
1335         }
1336         mddev->sb_dirty = 2;
1337         sync_sbs(mddev);
1338
1339         /*
1340          * do not write anything to disk if using
1341          * nonpersistent superblocks
1342          */
1343         if (!mddev->persistent) {
1344                 mddev->sb_dirty = 0;
1345                 spin_unlock(&mddev->write_lock);
1346                 wake_up(&mddev->sb_wait);
1347                 return;
1348         }
1349         spin_unlock(&mddev->write_lock);
1350
1351         dprintk(KERN_INFO 
1352                 "md: updating %s RAID superblock on device (in sync %d)\n",
1353                 mdname(mddev),mddev->in_sync);
1354
1355         err = bitmap_update_sb(mddev->bitmap);
1356         ITERATE_RDEV(mddev,rdev,tmp) {
1357                 char b[BDEVNAME_SIZE];
1358                 dprintk(KERN_INFO "md: ");
1359                 if (rdev->faulty)
1360                         dprintk("(skipping faulty ");
1361
1362                 dprintk("%s ", bdevname(rdev->bdev,b));
1363                 if (!rdev->faulty) {
1364                         md_super_write(mddev,rdev,
1365                                        rdev->sb_offset<<1, MD_SB_BYTES,
1366                                        rdev->sb_page);
1367                         dprintk(KERN_INFO "(write) %s's sb offset: %llu\n",
1368                                 bdevname(rdev->bdev,b),
1369                                 (unsigned long long)rdev->sb_offset);
1370
1371                 } else
1372                         dprintk(")\n");
1373                 if (mddev->level == LEVEL_MULTIPATH)
1374                         /* only need to write one superblock... */
1375                         break;
1376         }
1377         wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
1378         /* if there was a failure, sb_dirty was set to 1, and we re-write super */
1379
1380         spin_lock(&mddev->write_lock);
1381         if (mddev->in_sync != sync_req|| mddev->sb_dirty == 1) {
1382                 /* have to write it out again */
1383                 spin_unlock(&mddev->write_lock);
1384                 goto repeat;
1385         }
1386         mddev->sb_dirty = 0;
1387         spin_unlock(&mddev->write_lock);
1388         wake_up(&mddev->sb_wait);
1389
1390 }
1391
1392 /*
1393  * Import a device. If 'super_format' >= 0, then sanity check the superblock
1394  *
1395  * mark the device faulty if:
1396  *
1397  *   - the device is nonexistent (zero size)
1398  *   - the device has no valid superblock
1399  *
1400  * a faulty rdev _never_ has rdev->sb set.
1401  */
1402 static mdk_rdev_t *md_import_device(dev_t newdev, int super_format, int super_minor)
1403 {
1404         char b[BDEVNAME_SIZE];
1405         int err;
1406         mdk_rdev_t *rdev;
1407         sector_t size;
1408
1409         rdev = (mdk_rdev_t *) kmalloc(sizeof(*rdev), GFP_KERNEL);
1410         if (!rdev) {
1411                 printk(KERN_ERR "md: could not alloc mem for new device!\n");
1412                 return ERR_PTR(-ENOMEM);
1413         }
1414         memset(rdev, 0, sizeof(*rdev));
1415
1416         if ((err = alloc_disk_sb(rdev)))
1417                 goto abort_free;
1418
1419         err = lock_rdev(rdev, newdev);
1420         if (err)
1421                 goto abort_free;
1422
1423         rdev->desc_nr = -1;
1424         rdev->faulty = 0;
1425         rdev->in_sync = 0;
1426         rdev->data_offset = 0;
1427         atomic_set(&rdev->nr_pending, 0);
1428
1429         size = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
1430         if (!size) {
1431                 printk(KERN_WARNING 
1432                         "md: %s has zero or unknown size, marking faulty!\n",
1433                         bdevname(rdev->bdev,b));
1434                 err = -EINVAL;
1435                 goto abort_free;
1436         }
1437
1438         if (super_format >= 0) {
1439                 err = super_types[super_format].
1440                         load_super(rdev, NULL, super_minor);
1441                 if (err == -EINVAL) {
1442                         printk(KERN_WARNING 
1443                                 "md: %s has invalid sb, not importing!\n",
1444                                 bdevname(rdev->bdev,b));
1445                         goto abort_free;
1446                 }
1447                 if (err < 0) {
1448                         printk(KERN_WARNING 
1449                                 "md: could not read %s's sb, not importing!\n",
1450                                 bdevname(rdev->bdev,b));
1451                         goto abort_free;
1452                 }
1453         }
1454         INIT_LIST_HEAD(&rdev->same_set);
1455
1456         return rdev;
1457
1458 abort_free:
1459         if (rdev->sb_page) {
1460                 if (rdev->bdev)
1461                         unlock_rdev(rdev);
1462                 free_disk_sb(rdev);
1463         }
1464         kfree(rdev);
1465         return ERR_PTR(err);
1466 }
1467
1468 /*
1469  * Check a full RAID array for plausibility
1470  */
1471
1472
1473 static void analyze_sbs(mddev_t * mddev)
1474 {
1475         int i;
1476         struct list_head *tmp;
1477         mdk_rdev_t *rdev, *freshest;
1478         char b[BDEVNAME_SIZE];
1479
1480         freshest = NULL;
1481         ITERATE_RDEV(mddev,rdev,tmp)
1482                 switch (super_types[mddev->major_version].
1483                         load_super(rdev, freshest, mddev->minor_version)) {
1484                 case 1:
1485                         freshest = rdev;
1486                         break;
1487                 case 0:
1488                         break;
1489                 default:
1490                         printk( KERN_ERR \
1491                                 "md: fatal superblock inconsistency in %s"
1492                                 " -- removing from array\n", 
1493                                 bdevname(rdev->bdev,b));
1494                         kick_rdev_from_array(rdev);
1495                 }
1496
1497
1498         super_types[mddev->major_version].
1499                 validate_super(mddev, freshest);
1500
1501         i = 0;
1502         ITERATE_RDEV(mddev,rdev,tmp) {
1503                 if (rdev != freshest)
1504                         if (super_types[mddev->major_version].
1505                             validate_super(mddev, rdev)) {
1506                                 printk(KERN_WARNING "md: kicking non-fresh %s"
1507                                         " from array!\n",
1508                                         bdevname(rdev->bdev,b));
1509                                 kick_rdev_from_array(rdev);
1510                                 continue;
1511                         }
1512                 if (mddev->level == LEVEL_MULTIPATH) {
1513                         rdev->desc_nr = i++;
1514                         rdev->raid_disk = rdev->desc_nr;
1515                         rdev->in_sync = 1;
1516                 }
1517         }
1518
1519
1520
1521         if (mddev->recovery_cp != MaxSector &&
1522             mddev->level >= 1)
1523                 printk(KERN_ERR "md: %s: raid array is not clean"
1524                        " -- starting background reconstruction\n",
1525                        mdname(mddev));
1526
1527 }
1528
1529 int mdp_major = 0;
1530
1531 static struct kobject *md_probe(dev_t dev, int *part, void *data)
1532 {
1533         static DECLARE_MUTEX(disks_sem);
1534         mddev_t *mddev = mddev_find(dev);
1535         struct gendisk *disk;
1536         int partitioned = (MAJOR(dev) != MD_MAJOR);
1537         int shift = partitioned ? MdpMinorShift : 0;
1538         int unit = MINOR(dev) >> shift;
1539
1540         if (!mddev)
1541                 return NULL;
1542
1543         down(&disks_sem);
1544         if (mddev->gendisk) {
1545                 up(&disks_sem);
1546                 mddev_put(mddev);
1547                 return NULL;
1548         }
1549         disk = alloc_disk(1 << shift);
1550         if (!disk) {
1551                 up(&disks_sem);
1552                 mddev_put(mddev);
1553                 return NULL;
1554         }
1555         disk->major = MAJOR(dev);
1556         disk->first_minor = unit << shift;
1557         if (partitioned) {
1558                 sprintf(disk->disk_name, "md_d%d", unit);
1559                 sprintf(disk->devfs_name, "md/d%d", unit);
1560         } else {
1561                 sprintf(disk->disk_name, "md%d", unit);
1562                 sprintf(disk->devfs_name, "md/%d", unit);
1563         }
1564         disk->fops = &md_fops;
1565         disk->private_data = mddev;
1566         disk->queue = mddev->queue;
1567         add_disk(disk);
1568         mddev->gendisk = disk;
1569         up(&disks_sem);
1570         return NULL;
1571 }
1572
1573 void md_wakeup_thread(mdk_thread_t *thread);
1574
1575 static void md_safemode_timeout(unsigned long data)
1576 {
1577         mddev_t *mddev = (mddev_t *) data;
1578
1579         mddev->safemode = 1;
1580         md_wakeup_thread(mddev->thread);
1581 }
1582
1583
1584 static int do_md_run(mddev_t * mddev)
1585 {
1586         int pnum, err;
1587         int chunk_size;
1588         struct list_head *tmp;
1589         mdk_rdev_t *rdev;
1590         struct gendisk *disk;
1591         char b[BDEVNAME_SIZE];
1592
1593         if (list_empty(&mddev->disks))
1594                 /* cannot run an array with no devices.. */
1595                 return -EINVAL;
1596
1597         if (mddev->pers)
1598                 return -EBUSY;
1599
1600         /*
1601          * Analyze all RAID superblock(s)
1602          */
1603         if (!mddev->raid_disks)
1604                 analyze_sbs(mddev);
1605
1606         chunk_size = mddev->chunk_size;
1607         pnum = level_to_pers(mddev->level);
1608
1609         if ((pnum != MULTIPATH) && (pnum != RAID1)) {
1610                 if (!chunk_size) {
1611                         /*
1612                          * 'default chunksize' in the old md code used to
1613                          * be PAGE_SIZE, baaad.
1614                          * we abort here to be on the safe side. We don't
1615                          * want to continue the bad practice.
1616                          */
1617                         printk(KERN_ERR 
1618                                 "no chunksize specified, see 'man raidtab'\n");
1619                         return -EINVAL;
1620                 }
1621                 if (chunk_size > MAX_CHUNK_SIZE) {
1622                         printk(KERN_ERR "too big chunk_size: %d > %d\n",
1623                                 chunk_size, MAX_CHUNK_SIZE);
1624                         return -EINVAL;
1625                 }
1626                 /*
1627                  * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
1628                  */
1629                 if ( (1 << ffz(~chunk_size)) != chunk_size) {
1630                         printk(KERN_ERR "chunk_size of %d not valid\n", chunk_size);
1631                         return -EINVAL;
1632                 }
1633                 if (chunk_size < PAGE_SIZE) {
1634                         printk(KERN_ERR "too small chunk_size: %d < %ld\n",
1635                                 chunk_size, PAGE_SIZE);
1636                         return -EINVAL;
1637                 }
1638
1639                 /* devices must have minimum size of one chunk */
1640                 ITERATE_RDEV(mddev,rdev,tmp) {
1641                         if (rdev->faulty)
1642                                 continue;
1643                         if (rdev->size < chunk_size / 1024) {
1644                                 printk(KERN_WARNING
1645                                         "md: Dev %s smaller than chunk_size:"
1646                                         " %lluk < %dk\n",
1647                                         bdevname(rdev->bdev,b),
1648                                         (unsigned long long)rdev->size,
1649                                         chunk_size / 1024);
1650                                 return -EINVAL;
1651                         }
1652                 }
1653         }
1654
1655 #ifdef CONFIG_KMOD
1656         if (!pers[pnum])
1657         {
1658                 request_module("md-personality-%d", pnum);
1659         }
1660 #endif
1661
1662         /*
1663          * Drop all container device buffers, from now on
1664          * the only valid external interface is through the md
1665          * device.
1666          * Also find largest hardsector size
1667          */
1668         ITERATE_RDEV(mddev,rdev,tmp) {
1669                 if (rdev->faulty)
1670                         continue;
1671                 sync_blockdev(rdev->bdev);
1672                 invalidate_bdev(rdev->bdev, 0);
1673         }
1674
1675         md_probe(mddev->unit, NULL, NULL);
1676         disk = mddev->gendisk;
1677         if (!disk)
1678                 return -ENOMEM;
1679
1680         spin_lock(&pers_lock);
1681         if (!pers[pnum] || !try_module_get(pers[pnum]->owner)) {
1682                 spin_unlock(&pers_lock);
1683                 printk(KERN_WARNING "md: personality %d is not loaded!\n",
1684                        pnum);
1685                 return -EINVAL;
1686         }
1687
1688         mddev->pers = pers[pnum];
1689         spin_unlock(&pers_lock);
1690
1691         mddev->resync_max_sectors = mddev->size << 1; /* may be over-ridden by personality */
1692
1693         /* before we start the array running, initialise the bitmap */
1694         err = bitmap_create(mddev);
1695         if (err)
1696                 printk(KERN_ERR "%s: failed to create bitmap (%d)\n",
1697                         mdname(mddev), err);
1698         else
1699                 err = mddev->pers->run(mddev);
1700         if (err) {
1701                 printk(KERN_ERR "md: pers->run() failed ...\n");
1702                 module_put(mddev->pers->owner);
1703                 mddev->pers = NULL;
1704                 bitmap_destroy(mddev);
1705                 return err;
1706         }
1707         atomic_set(&mddev->writes_pending,0);
1708         mddev->safemode = 0;
1709         mddev->safemode_timer.function = md_safemode_timeout;
1710         mddev->safemode_timer.data = (unsigned long) mddev;
1711         mddev->safemode_delay = (20 * HZ)/1000 +1; /* 20 msec delay */
1712         mddev->in_sync = 1;
1713         
1714         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1715         
1716         if (mddev->sb_dirty)
1717                 md_update_sb(mddev);
1718
1719         set_capacity(disk, mddev->array_size<<1);
1720
1721         /* If we call blk_queue_make_request here, it will
1722          * re-initialise max_sectors etc which may have been
1723          * refined inside -> run.  So just set the bits we need to set.
1724          * Most initialisation happended when we called
1725          * blk_queue_make_request(..., md_fail_request)
1726          * earlier.
1727          */
1728         mddev->queue->queuedata = mddev;
1729         mddev->queue->make_request_fn = mddev->pers->make_request;
1730
1731         mddev->changed = 1;
1732         return 0;
1733 }
1734
1735 static int restart_array(mddev_t *mddev)
1736 {
1737         struct gendisk *disk = mddev->gendisk;
1738         int err;
1739
1740         /*
1741          * Complain if it has no devices
1742          */
1743         err = -ENXIO;
1744         if (list_empty(&mddev->disks))
1745                 goto out;
1746
1747         if (mddev->pers) {
1748                 err = -EBUSY;
1749                 if (!mddev->ro)
1750                         goto out;
1751
1752                 mddev->safemode = 0;
1753                 mddev->ro = 0;
1754                 set_disk_ro(disk, 0);
1755
1756                 printk(KERN_INFO "md: %s switched to read-write mode.\n",
1757                         mdname(mddev));
1758                 /*
1759                  * Kick recovery or resync if necessary
1760                  */
1761                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
1762                 md_wakeup_thread(mddev->thread);
1763                 err = 0;
1764         } else {
1765                 printk(KERN_ERR "md: %s has no personality assigned.\n",
1766                         mdname(mddev));
1767                 err = -EINVAL;
1768         }
1769
1770 out:
1771         return err;
1772 }
1773
1774 static int do_md_stop(mddev_t * mddev, int ro)
1775 {
1776         int err = 0;
1777         struct gendisk *disk = mddev->gendisk;
1778
1779         if (mddev->pers) {
1780                 if (atomic_read(&mddev->active)>2) {
1781                         printk("md: %s still in use.\n",mdname(mddev));
1782                         return -EBUSY;
1783                 }
1784
1785                 if (mddev->sync_thread) {
1786                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
1787                         md_unregister_thread(mddev->sync_thread);
1788                         mddev->sync_thread = NULL;
1789                 }
1790
1791                 del_timer_sync(&mddev->safemode_timer);
1792
1793                 invalidate_partition(disk, 0);
1794
1795                 if (ro) {
1796                         err  = -ENXIO;
1797                         if (mddev->ro)
1798                                 goto out;
1799                         mddev->ro = 1;
1800                 } else {
1801                         bitmap_flush(mddev);
1802                         wait_event(mddev->sb_wait, atomic_read(&mddev->pending_writes)==0);
1803                         if (mddev->ro)
1804                                 set_disk_ro(disk, 0);
1805                         blk_queue_make_request(mddev->queue, md_fail_request);
1806                         mddev->pers->stop(mddev);
1807                         module_put(mddev->pers->owner);
1808                         mddev->pers = NULL;
1809                         if (mddev->ro)
1810                                 mddev->ro = 0;
1811                 }
1812                 if (!mddev->in_sync) {
1813                         /* mark array as shutdown cleanly */
1814                         mddev->in_sync = 1;
1815                         md_update_sb(mddev);
1816                 }
1817                 if (ro)
1818                         set_disk_ro(disk, 1);
1819         }
1820
1821         bitmap_destroy(mddev);
1822         if (mddev->bitmap_file) {
1823                 atomic_set(&mddev->bitmap_file->f_dentry->d_inode->i_writecount, 1);
1824                 fput(mddev->bitmap_file);
1825                 mddev->bitmap_file = NULL;
1826         }
1827
1828         /*
1829          * Free resources if final stop
1830          */
1831         if (!ro) {
1832                 struct gendisk *disk;
1833                 printk(KERN_INFO "md: %s stopped.\n", mdname(mddev));
1834
1835                 export_array(mddev);
1836
1837                 mddev->array_size = 0;
1838                 disk = mddev->gendisk;
1839                 if (disk)
1840                         set_capacity(disk, 0);
1841                 mddev->changed = 1;
1842         } else
1843                 printk(KERN_INFO "md: %s switched to read-only mode.\n",
1844                         mdname(mddev));
1845         err = 0;
1846 out:
1847         return err;
1848 }
1849
1850 static void autorun_array(mddev_t *mddev)
1851 {
1852         mdk_rdev_t *rdev;
1853         struct list_head *tmp;
1854         int err;
1855
1856         if (list_empty(&mddev->disks))
1857                 return;
1858
1859         printk(KERN_INFO "md: running: ");
1860
1861         ITERATE_RDEV(mddev,rdev,tmp) {
1862                 char b[BDEVNAME_SIZE];
1863                 printk("<%s>", bdevname(rdev->bdev,b));
1864         }
1865         printk("\n");
1866
1867         err = do_md_run (mddev);
1868         if (err) {
1869                 printk(KERN_WARNING "md: do_md_run() returned %d\n", err);
1870                 do_md_stop (mddev, 0);
1871         }
1872 }
1873
1874 /*
1875  * lets try to run arrays based on all disks that have arrived
1876  * until now. (those are in pending_raid_disks)
1877  *
1878  * the method: pick the first pending disk, collect all disks with
1879  * the same UUID, remove all from the pending list and put them into
1880  * the 'same_array' list. Then order this list based on superblock
1881  * update time (freshest comes first), kick out 'old' disks and
1882  * compare superblocks. If everything's fine then run it.
1883  *
1884  * If "unit" is allocated, then bump its reference count
1885  */
1886 static void autorun_devices(int part)
1887 {
1888         struct list_head candidates;
1889         struct list_head *tmp;
1890         mdk_rdev_t *rdev0, *rdev;
1891         mddev_t *mddev;
1892         char b[BDEVNAME_SIZE];
1893
1894         printk(KERN_INFO "md: autorun ...\n");
1895         while (!list_empty(&pending_raid_disks)) {
1896                 dev_t dev;
1897                 rdev0 = list_entry(pending_raid_disks.next,
1898                                          mdk_rdev_t, same_set);
1899
1900                 printk(KERN_INFO "md: considering %s ...\n",
1901                         bdevname(rdev0->bdev,b));
1902                 INIT_LIST_HEAD(&candidates);
1903                 ITERATE_RDEV_PENDING(rdev,tmp)
1904                         if (super_90_load(rdev, rdev0, 0) >= 0) {
1905                                 printk(KERN_INFO "md:  adding %s ...\n",
1906                                         bdevname(rdev->bdev,b));
1907                                 list_move(&rdev->same_set, &candidates);
1908                         }
1909                 /*
1910                  * now we have a set of devices, with all of them having
1911                  * mostly sane superblocks. It's time to allocate the
1912                  * mddev.
1913                  */
1914                 if (rdev0->preferred_minor < 0 || rdev0->preferred_minor >= MAX_MD_DEVS) {
1915                         printk(KERN_INFO "md: unit number in %s is bad: %d\n",
1916                                bdevname(rdev0->bdev, b), rdev0->preferred_minor);
1917                         break;
1918                 }
1919                 if (part)
1920                         dev = MKDEV(mdp_major,
1921                                     rdev0->preferred_minor << MdpMinorShift);
1922                 else
1923                         dev = MKDEV(MD_MAJOR, rdev0->preferred_minor);
1924
1925                 md_probe(dev, NULL, NULL);
1926                 mddev = mddev_find(dev);
1927                 if (!mddev) {
1928                         printk(KERN_ERR 
1929                                 "md: cannot allocate memory for md drive.\n");
1930                         break;
1931                 }
1932                 if (mddev_lock(mddev)) 
1933                         printk(KERN_WARNING "md: %s locked, cannot run\n",
1934                                mdname(mddev));
1935                 else if (mddev->raid_disks || mddev->major_version
1936                          || !list_empty(&mddev->disks)) {
1937                         printk(KERN_WARNING 
1938                                 "md: %s already running, cannot run %s\n",
1939                                 mdname(mddev), bdevname(rdev0->bdev,b));
1940                         mddev_unlock(mddev);
1941                 } else {
1942                         printk(KERN_INFO "md: created %s\n", mdname(mddev));
1943                         ITERATE_RDEV_GENERIC(candidates,rdev,tmp) {
1944                                 list_del_init(&rdev->same_set);
1945                                 if (bind_rdev_to_array(rdev, mddev))
1946                                         export_rdev(rdev);
1947                         }
1948                         autorun_array(mddev);
1949                         mddev_unlock(mddev);
1950                 }
1951                 /* on success, candidates will be empty, on error
1952                  * it won't...
1953                  */
1954                 ITERATE_RDEV_GENERIC(candidates,rdev,tmp)
1955                         export_rdev(rdev);
1956                 mddev_put(mddev);
1957         }
1958         printk(KERN_INFO "md: ... autorun DONE.\n");
1959 }
1960
1961 /*
1962  * import RAID devices based on one partition
1963  * if possible, the array gets run as well.
1964  */
1965
1966 static int autostart_array(dev_t startdev)
1967 {
1968         char b[BDEVNAME_SIZE];
1969         int err = -EINVAL, i;
1970         mdp_super_t *sb = NULL;
1971         mdk_rdev_t *start_rdev = NULL, *rdev;
1972
1973         start_rdev = md_import_device(startdev, 0, 0);
1974         if (IS_ERR(start_rdev))
1975                 return err;
1976
1977
1978         /* NOTE: this can only work for 0.90.0 superblocks */
1979         sb = (mdp_super_t*)page_address(start_rdev->sb_page);
1980         if (sb->major_version != 0 ||
1981             sb->minor_version != 90 ) {
1982                 printk(KERN_WARNING "md: can only autostart 0.90.0 arrays\n");
1983                 export_rdev(start_rdev);
1984                 return err;
1985         }
1986
1987         if (start_rdev->faulty) {
1988                 printk(KERN_WARNING 
1989                         "md: can not autostart based on faulty %s!\n",
1990                         bdevname(start_rdev->bdev,b));
1991                 export_rdev(start_rdev);
1992                 return err;
1993         }
1994         list_add(&start_rdev->same_set, &pending_raid_disks);
1995
1996         for (i = 0; i < MD_SB_DISKS; i++) {
1997                 mdp_disk_t *desc = sb->disks + i;
1998                 dev_t dev = MKDEV(desc->major, desc->minor);
1999
2000                 if (!dev)
2001                         continue;
2002                 if (dev == startdev)
2003                         continue;
2004                 if (MAJOR(dev) != desc->major || MINOR(dev) != desc->minor)
2005                         continue;
2006                 rdev = md_import_device(dev, 0, 0);
2007                 if (IS_ERR(rdev))
2008                         continue;
2009
2010                 list_add(&rdev->same_set, &pending_raid_disks);
2011         }
2012
2013         /*
2014          * possibly return codes
2015          */
2016         autorun_devices(0);
2017         return 0;
2018
2019 }
2020
2021
2022 static int get_version(void __user * arg)
2023 {
2024         mdu_version_t ver;
2025
2026         ver.major = MD_MAJOR_VERSION;
2027         ver.minor = MD_MINOR_VERSION;
2028         ver.patchlevel = MD_PATCHLEVEL_VERSION;
2029
2030         if (copy_to_user(arg, &ver, sizeof(ver)))
2031                 return -EFAULT;
2032
2033         return 0;
2034 }
2035
2036 static int get_array_info(mddev_t * mddev, void __user * arg)
2037 {
2038         mdu_array_info_t info;
2039         int nr,working,active,failed,spare;
2040         mdk_rdev_t *rdev;
2041         struct list_head *tmp;
2042
2043         nr=working=active=failed=spare=0;
2044         ITERATE_RDEV(mddev,rdev,tmp) {
2045                 nr++;
2046                 if (rdev->faulty)
2047                         failed++;
2048                 else {
2049                         working++;
2050                         if (rdev->in_sync)
2051                                 active++;       
2052                         else
2053                                 spare++;
2054                 }
2055         }
2056
2057         info.major_version = mddev->major_version;
2058         info.minor_version = mddev->minor_version;
2059         info.patch_version = MD_PATCHLEVEL_VERSION;
2060         info.ctime         = mddev->ctime;
2061         info.level         = mddev->level;
2062         info.size          = mddev->size;
2063         info.nr_disks      = nr;
2064         info.raid_disks    = mddev->raid_disks;
2065         info.md_minor      = mddev->md_minor;
2066         info.not_persistent= !mddev->persistent;
2067
2068         info.utime         = mddev->utime;
2069         info.state         = 0;
2070         if (mddev->in_sync)
2071                 info.state = (1<<MD_SB_CLEAN);
2072         info.active_disks  = active;
2073         info.working_disks = working;
2074         info.failed_disks  = failed;
2075         info.spare_disks   = spare;
2076
2077         info.layout        = mddev->layout;
2078         info.chunk_size    = mddev->chunk_size;
2079
2080         if (copy_to_user(arg, &info, sizeof(info)))
2081                 return -EFAULT;
2082
2083         return 0;
2084 }
2085
2086 static int get_bitmap_file(mddev_t * mddev, void * arg)
2087 {
2088         mdu_bitmap_file_t *file = NULL; /* too big for stack allocation */
2089         char *ptr, *buf = NULL;
2090         int err = -ENOMEM;
2091
2092         file = kmalloc(sizeof(*file), GFP_KERNEL);
2093         if (!file)
2094                 goto out;
2095
2096         /* bitmap disabled, zero the first byte and copy out */
2097         if (!mddev->bitmap || !mddev->bitmap->file) {
2098                 file->pathname[0] = '\0';
2099                 goto copy_out;
2100         }
2101
2102         buf = kmalloc(sizeof(file->pathname), GFP_KERNEL);
2103         if (!buf)
2104                 goto out;
2105
2106         ptr = file_path(mddev->bitmap->file, buf, sizeof(file->pathname));
2107         if (!ptr)
2108                 goto out;
2109
2110         strcpy(file->pathname, ptr);
2111
2112 copy_out:
2113         err = 0;
2114         if (copy_to_user(arg, file, sizeof(*file)))
2115                 err = -EFAULT;
2116 out:
2117         kfree(buf);
2118         kfree(file);
2119         return err;
2120 }
2121
2122 static int get_disk_info(mddev_t * mddev, void __user * arg)
2123 {
2124         mdu_disk_info_t info;
2125         unsigned int nr;
2126         mdk_rdev_t *rdev;
2127
2128         if (copy_from_user(&info, arg, sizeof(info)))
2129                 return -EFAULT;
2130
2131         nr = info.number;
2132
2133         rdev = find_rdev_nr(mddev, nr);
2134         if (rdev) {
2135                 info.major = MAJOR(rdev->bdev->bd_dev);
2136                 info.minor = MINOR(rdev->bdev->bd_dev);
2137                 info.raid_disk = rdev->raid_disk;
2138                 info.state = 0;
2139                 if (rdev->faulty)
2140                         info.state |= (1<<MD_DISK_FAULTY);
2141                 else if (rdev->in_sync) {
2142                         info.state |= (1<<MD_DISK_ACTIVE);
2143                         info.state |= (1<<MD_DISK_SYNC);
2144                 }
2145         } else {
2146                 info.major = info.minor = 0;
2147                 info.raid_disk = -1;
2148                 info.state = (1<<MD_DISK_REMOVED);
2149         }
2150
2151         if (copy_to_user(arg, &info, sizeof(info)))
2152                 return -EFAULT;
2153
2154         return 0;
2155 }
2156
2157 static int add_new_disk(mddev_t * mddev, mdu_disk_info_t *info)
2158 {
2159         char b[BDEVNAME_SIZE], b2[BDEVNAME_SIZE];
2160         mdk_rdev_t *rdev;
2161         dev_t dev = MKDEV(info->major,info->minor);
2162
2163         if (info->major != MAJOR(dev) || info->minor != MINOR(dev))
2164                 return -EOVERFLOW;
2165
2166         if (!mddev->raid_disks) {
2167                 int err;
2168                 /* expecting a device which has a superblock */
2169                 rdev = md_import_device(dev, mddev->major_version, mddev->minor_version);
2170                 if (IS_ERR(rdev)) {
2171                         printk(KERN_WARNING 
2172                                 "md: md_import_device returned %ld\n",
2173                                 PTR_ERR(rdev));
2174                         return PTR_ERR(rdev);
2175                 }
2176                 if (!list_empty(&mddev->disks)) {
2177                         mdk_rdev_t *rdev0 = list_entry(mddev->disks.next,
2178                                                         mdk_rdev_t, same_set);
2179                         int err = super_types[mddev->major_version]
2180                                 .load_super(rdev, rdev0, mddev->minor_version);
2181                         if (err < 0) {
2182                                 printk(KERN_WARNING 
2183                                         "md: %s has different UUID to %s\n",
2184                                         bdevname(rdev->bdev,b), 
2185                                         bdevname(rdev0->bdev,b2));
2186                                 export_rdev(rdev);
2187                                 return -EINVAL;
2188                         }
2189                 }
2190                 err = bind_rdev_to_array(rdev, mddev);
2191                 if (err)
2192                         export_rdev(rdev);
2193                 return err;
2194         }
2195
2196         /*
2197          * add_new_disk can be used once the array is assembled
2198          * to add "hot spares".  They must already have a superblock
2199          * written
2200          */
2201         if (mddev->pers) {
2202                 int err;
2203                 if (!mddev->pers->hot_add_disk) {
2204                         printk(KERN_WARNING 
2205                                 "%s: personality does not support diskops!\n",
2206                                mdname(mddev));
2207                         return -EINVAL;
2208                 }
2209                 rdev = md_import_device(dev, mddev->major_version,
2210                                         mddev->minor_version);
2211                 if (IS_ERR(rdev)) {
2212                         printk(KERN_WARNING 
2213                                 "md: md_import_device returned %ld\n",
2214                                 PTR_ERR(rdev));
2215                         return PTR_ERR(rdev);
2216                 }
2217                 /* set save_raid_disk if appropriate */
2218                 if (!mddev->persistent) {
2219                         if (info->state & (1<<MD_DISK_SYNC)  &&
2220                             info->raid_disk < mddev->raid_disks)
2221                                 rdev->raid_disk = info->raid_disk;
2222                         else
2223                                 rdev->raid_disk = -1;
2224                 } else
2225                         super_types[mddev->major_version].
2226                                 validate_super(mddev, rdev);
2227                 rdev->saved_raid_disk = rdev->raid_disk;
2228
2229                 rdev->in_sync = 0; /* just to be sure */
2230                 rdev->raid_disk = -1;
2231                 err = bind_rdev_to_array(rdev, mddev);
2232                 if (err)
2233                         export_rdev(rdev);
2234
2235                 set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2236                 if (mddev->thread)
2237                         md_wakeup_thread(mddev->thread);
2238                 return err;
2239         }
2240
2241         /* otherwise, add_new_disk is only allowed
2242          * for major_version==0 superblocks
2243          */
2244         if (mddev->major_version != 0) {
2245                 printk(KERN_WARNING "%s: ADD_NEW_DISK not supported\n",
2246                        mdname(mddev));
2247                 return -EINVAL;
2248         }
2249
2250         if (!(info->state & (1<<MD_DISK_FAULTY))) {
2251                 int err;
2252                 rdev = md_import_device (dev, -1, 0);
2253                 if (IS_ERR(rdev)) {
2254                         printk(KERN_WARNING 
2255                                 "md: error, md_import_device() returned %ld\n",
2256                                 PTR_ERR(rdev));
2257                         return PTR_ERR(rdev);
2258                 }
2259                 rdev->desc_nr = info->number;
2260                 if (info->raid_disk < mddev->raid_disks)
2261                         rdev->raid_disk = info->raid_disk;
2262                 else
2263                         rdev->raid_disk = -1;
2264
2265                 rdev->faulty = 0;
2266                 if (rdev->raid_disk < mddev->raid_disks)
2267                         rdev->in_sync = (info->state & (1<<MD_DISK_SYNC));
2268                 else
2269                         rdev->in_sync = 0;
2270
2271                 err = bind_rdev_to_array(rdev, mddev);
2272                 if (err) {
2273                         export_rdev(rdev);
2274                         return err;
2275                 }
2276
2277                 if (!mddev->persistent) {
2278                         printk(KERN_INFO "md: nonpersistent superblock ...\n");
2279                         rdev->sb_offset = rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
2280                 } else 
2281                         rdev->sb_offset = calc_dev_sboffset(rdev->bdev);
2282                 rdev->size = calc_dev_size(rdev, mddev->chunk_size);
2283
2284                 if (!mddev->size || (mddev->size > rdev->size))
2285                         mddev->size = rdev->size;
2286         }
2287
2288         return 0;
2289 }
2290
2291 static int hot_remove_disk(mddev_t * mddev, dev_t dev)
2292 {
2293         char b[BDEVNAME_SIZE];
2294         mdk_rdev_t *rdev;
2295
2296         if (!mddev->pers)
2297                 return -ENODEV;
2298
2299         rdev = find_rdev(mddev, dev);
2300         if (!rdev)
2301                 return -ENXIO;
2302
2303         if (rdev->raid_disk >= 0)
2304                 goto busy;
2305
2306         kick_rdev_from_array(rdev);
2307         md_update_sb(mddev);
2308
2309         return 0;
2310 busy:
2311         printk(KERN_WARNING "md: cannot remove active disk %s from %s ... \n",
2312                 bdevname(rdev->bdev,b), mdname(mddev));
2313         return -EBUSY;
2314 }
2315
2316 static int hot_add_disk(mddev_t * mddev, dev_t dev)
2317 {
2318         char b[BDEVNAME_SIZE];
2319         int err;
2320         unsigned int size;
2321         mdk_rdev_t *rdev;
2322
2323         if (!mddev->pers)
2324                 return -ENODEV;
2325
2326         if (mddev->major_version != 0) {
2327                 printk(KERN_WARNING "%s: HOT_ADD may only be used with"
2328                         " version-0 superblocks.\n",
2329                         mdname(mddev));
2330                 return -EINVAL;
2331         }
2332         if (!mddev->pers->hot_add_disk) {
2333                 printk(KERN_WARNING 
2334                         "%s: personality does not support diskops!\n",
2335                         mdname(mddev));
2336                 return -EINVAL;
2337         }
2338
2339         rdev = md_import_device (dev, -1, 0);
2340         if (IS_ERR(rdev)) {
2341                 printk(KERN_WARNING 
2342                         "md: error, md_import_device() returned %ld\n",
2343                         PTR_ERR(rdev));
2344                 return -EINVAL;
2345         }
2346
2347         if (mddev->persistent)
2348                 rdev->sb_offset = calc_dev_sboffset(rdev->bdev);
2349         else
2350                 rdev->sb_offset =
2351                         rdev->bdev->bd_inode->i_size >> BLOCK_SIZE_BITS;
2352
2353         size = calc_dev_size(rdev, mddev->chunk_size);
2354         rdev->size = size;
2355
2356         if (size < mddev->size) {
2357                 printk(KERN_WARNING 
2358                         "%s: disk size %llu blocks < array size %llu\n",
2359                         mdname(mddev), (unsigned long long)size,
2360                         (unsigned long long)mddev->size);
2361                 err = -ENOSPC;
2362                 goto abort_export;
2363         }
2364
2365         if (rdev->faulty) {
2366                 printk(KERN_WARNING 
2367                         "md: can not hot-add faulty %s disk to %s!\n",
2368                         bdevname(rdev->bdev,b), mdname(mddev));
2369                 err = -EINVAL;
2370                 goto abort_export;
2371         }
2372         rdev->in_sync = 0;
2373         rdev->desc_nr = -1;
2374         bind_rdev_to_array(rdev, mddev);
2375
2376         /*
2377          * The rest should better be atomic, we can have disk failures
2378          * noticed in interrupt contexts ...
2379          */
2380
2381         if (rdev->desc_nr == mddev->max_disks) {
2382                 printk(KERN_WARNING "%s: can not hot-add to full array!\n",
2383                         mdname(mddev));
2384                 err = -EBUSY;
2385                 goto abort_unbind_export;
2386         }
2387
2388         rdev->raid_disk = -1;
2389
2390         md_update_sb(mddev);
2391
2392         /*
2393          * Kick recovery, maybe this spare has to be added to the
2394          * array immediately.
2395          */
2396         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
2397         md_wakeup_thread(mddev->thread);
2398
2399         return 0;
2400
2401 abort_unbind_export:
2402         unbind_rdev_from_array(rdev);
2403
2404 abort_export:
2405         export_rdev(rdev);
2406         return err;
2407 }
2408
2409 /* similar to deny_write_access, but accounts for our holding a reference
2410  * to the file ourselves */
2411 static int deny_bitmap_write_access(struct file * file)
2412 {
2413         struct inode *inode = file->f_mapping->host;
2414
2415         spin_lock(&inode->i_lock);
2416         if (atomic_read(&inode->i_writecount) > 1) {
2417                 spin_unlock(&inode->i_lock);
2418                 return -ETXTBSY;
2419         }
2420         atomic_set(&inode->i_writecount, -1);
2421         spin_unlock(&inode->i_lock);
2422
2423         return 0;
2424 }
2425
2426 static int set_bitmap_file(mddev_t *mddev, int fd)
2427 {
2428         int err;
2429
2430         if (mddev->pers)
2431                 return -EBUSY;
2432
2433         mddev->bitmap_file = fget(fd);
2434
2435         if (mddev->bitmap_file == NULL) {
2436                 printk(KERN_ERR "%s: error: failed to get bitmap file\n",
2437                         mdname(mddev));
2438                 return -EBADF;
2439         }
2440
2441         err = deny_bitmap_write_access(mddev->bitmap_file);
2442         if (err) {
2443                 printk(KERN_ERR "%s: error: bitmap file is already in use\n",
2444                         mdname(mddev));
2445                 fput(mddev->bitmap_file);
2446                 mddev->bitmap_file = NULL;
2447         } else
2448                 mddev->bitmap_offset = 0; /* file overrides offset */
2449         return err;
2450 }
2451
2452 /*
2453  * set_array_info is used two different ways
2454  * The original usage is when creating a new array.
2455  * In this usage, raid_disks is > 0 and it together with
2456  *  level, size, not_persistent,layout,chunksize determine the
2457  *  shape of the array.
2458  *  This will always create an array with a type-0.90.0 superblock.
2459  * The newer usage is when assembling an array.
2460  *  In this case raid_disks will be 0, and the major_version field is
2461  *  use to determine which style super-blocks are to be found on the devices.
2462  *  The minor and patch _version numbers are also kept incase the
2463  *  super_block handler wishes to interpret them.
2464  */
2465 static int set_array_info(mddev_t * mddev, mdu_array_info_t *info)
2466 {
2467
2468         if (info->raid_disks == 0) {
2469                 /* just setting version number for superblock loading */
2470                 if (info->major_version < 0 ||
2471                     info->major_version >= sizeof(super_types)/sizeof(super_types[0]) ||
2472                     super_types[info->major_version].name == NULL) {
2473                         /* maybe try to auto-load a module? */
2474                         printk(KERN_INFO 
2475                                 "md: superblock version %d not known\n",
2476                                 info->major_version);
2477                         return -EINVAL;
2478                 }
2479                 mddev->major_version = info->major_version;
2480                 mddev->minor_version = info->minor_version;
2481                 mddev->patch_version = info->patch_version;
2482                 return 0;
2483         }
2484         mddev->major_version = MD_MAJOR_VERSION;
2485         mddev->minor_version = MD_MINOR_VERSION;
2486         mddev->patch_version = MD_PATCHLEVEL_VERSION;
2487         mddev->ctime         = get_seconds();
2488
2489         mddev->level         = info->level;
2490         mddev->size          = info->size;
2491         mddev->raid_disks    = info->raid_disks;
2492         /* don't set md_minor, it is determined by which /dev/md* was
2493          * openned
2494          */
2495         if (info->state & (1<<MD_SB_CLEAN))
2496                 mddev->recovery_cp = MaxSector;
2497         else
2498                 mddev->recovery_cp = 0;
2499         mddev->persistent    = ! info->not_persistent;
2500
2501         mddev->layout        = info->layout;
2502         mddev->chunk_size    = info->chunk_size;
2503
2504         mddev->max_disks     = MD_SB_DISKS;
2505
2506         mddev->sb_dirty      = 1;
2507
2508         /*
2509          * Generate a 128 bit UUID
2510          */
2511         get_random_bytes(mddev->uuid, 16);
2512
2513         return 0;
2514 }
2515
2516 /*
2517  * update_array_info is used to change the configuration of an
2518  * on-line array.
2519  * The version, ctime,level,size,raid_disks,not_persistent, layout,chunk_size
2520  * fields in the info are checked against the array.
2521  * Any differences that cannot be handled will cause an error.
2522  * Normally, only one change can be managed at a time.
2523  */
2524 static int update_array_info(mddev_t *mddev, mdu_array_info_t *info)
2525 {
2526         int rv = 0;
2527         int cnt = 0;
2528
2529         if (mddev->major_version != info->major_version ||
2530             mddev->minor_version != info->minor_version ||
2531 /*          mddev->patch_version != info->patch_version || */
2532             mddev->ctime         != info->ctime         ||
2533             mddev->level         != info->level         ||
2534 /*          mddev->layout        != info->layout        || */
2535             !mddev->persistent   != info->not_persistent||
2536             mddev->chunk_size    != info->chunk_size    )
2537                 return -EINVAL;
2538         /* Check there is only one change */
2539         if (mddev->size != info->size) cnt++;
2540         if (mddev->raid_disks != info->raid_disks) cnt++;
2541         if (mddev->layout != info->layout) cnt++;
2542         if (cnt == 0) return 0;
2543         if (cnt > 1) return -EINVAL;
2544
2545         if (mddev->layout != info->layout) {
2546                 /* Change layout
2547                  * we don't need to do anything at the md level, the
2548                  * personality will take care of it all.
2549                  */
2550                 if (mddev->pers->reconfig == NULL)
2551                         return -EINVAL;
2552                 else
2553                         return mddev->pers->reconfig(mddev, info->layout, -1);
2554         }
2555         if (mddev->size != info->size) {
2556                 mdk_rdev_t * rdev;
2557                 struct list_head *tmp;
2558                 if (mddev->pers->resize == NULL)
2559                         return -EINVAL;
2560                 /* The "size" is the amount of each device that is used.
2561                  * This can only make sense for arrays with redundancy.
2562                  * linear and raid0 always use whatever space is available
2563                  * We can only consider changing the size if no resync
2564                  * or reconstruction is happening, and if the new size
2565                  * is acceptable. It must fit before the sb_offset or,
2566                  * if that is <data_offset, it must fit before the
2567                  * size of each device.
2568                  * If size is zero, we find the largest size that fits.
2569                  */
2570                 if (mddev->sync_thread)
2571                         return -EBUSY;
2572                 ITERATE_RDEV(mddev,rdev,tmp) {
2573                         sector_t avail;
2574                         int fit = (info->size == 0);
2575                         if (rdev->sb_offset > rdev->data_offset)
2576                                 avail = (rdev->sb_offset*2) - rdev->data_offset;
2577                         else
2578                                 avail = get_capacity(rdev->bdev->bd_disk)
2579                                         - rdev->data_offset;
2580                         if (fit && (info->size == 0 || info->size > avail/2))
2581                                 info->size = avail/2;
2582                         if (avail < ((sector_t)info->size << 1))
2583                                 return -ENOSPC;
2584                 }
2585                 rv = mddev->pers->resize(mddev, (sector_t)info->size *2);
2586                 if (!rv) {
2587                         struct block_device *bdev;
2588
2589                         bdev = bdget_disk(mddev->gendisk, 0);
2590                         if (bdev) {
2591                                 down(&bdev->bd_inode->i_sem);
2592                                 i_size_write(bdev->bd_inode, mddev->array_size << 10);
2593                                 up(&bdev->bd_inode->i_sem);
2594                                 bdput(bdev);
2595                         }
2596                 }
2597         }
2598         if (mddev->raid_disks    != info->raid_disks) {
2599                 /* change the number of raid disks */
2600                 if (mddev->pers->reshape == NULL)
2601                         return -EINVAL;
2602                 if (info->raid_disks <= 0 ||
2603                     info->raid_disks >= mddev->max_disks)
2604                         return -EINVAL;
2605                 if (mddev->sync_thread)
2606                         return -EBUSY;
2607                 rv = mddev->pers->reshape(mddev, info->raid_disks);
2608                 if (!rv) {
2609                         struct block_device *bdev;
2610
2611                         bdev = bdget_disk(mddev->gendisk, 0);
2612                         if (bdev) {
2613                                 down(&bdev->bd_inode->i_sem);
2614                                 i_size_write(bdev->bd_inode, mddev->array_size << 10);
2615                                 up(&bdev->bd_inode->i_sem);
2616                                 bdput(bdev);
2617                         }
2618                 }
2619         }
2620         md_update_sb(mddev);
2621         return rv;
2622 }
2623
2624 static int set_disk_faulty(mddev_t *mddev, dev_t dev)
2625 {
2626         mdk_rdev_t *rdev;
2627
2628         if (mddev->pers == NULL)
2629                 return -ENODEV;
2630
2631         rdev = find_rdev(mddev, dev);
2632         if (!rdev)
2633                 return -ENODEV;
2634
2635         md_error(mddev, rdev);
2636         return 0;
2637 }
2638
2639 static int md_ioctl(struct inode *inode, struct file *file,
2640                         unsigned int cmd, unsigned long arg)
2641 {
2642         int err = 0;
2643         void __user *argp = (void __user *)arg;
2644         struct hd_geometry __user *loc = argp;
2645         mddev_t *mddev = NULL;
2646
2647         if (!capable(CAP_SYS_ADMIN))
2648                 return -EACCES;
2649
2650         /*
2651          * Commands dealing with the RAID driver but not any
2652          * particular array:
2653          */
2654         switch (cmd)
2655         {
2656                 case RAID_VERSION:
2657                         err = get_version(argp);
2658                         goto done;
2659
2660                 case PRINT_RAID_DEBUG:
2661                         err = 0;
2662                         md_print_devices();
2663                         goto done;
2664
2665 #ifndef MODULE
2666                 case RAID_AUTORUN:
2667                         err = 0;
2668                         autostart_arrays(arg);
2669                         goto done;
2670 #endif
2671                 default:;
2672         }
2673
2674         /*
2675          * Commands creating/starting a new array:
2676          */
2677
2678         mddev = inode->i_bdev->bd_disk->private_data;
2679
2680         if (!mddev) {
2681                 BUG();
2682                 goto abort;
2683         }
2684
2685
2686         if (cmd == START_ARRAY) {
2687                 /* START_ARRAY doesn't need to lock the array as autostart_array
2688                  * does the locking, and it could even be a different array
2689                  */
2690                 static int cnt = 3;
2691                 if (cnt > 0 ) {
2692                         printk(KERN_WARNING
2693                                "md: %s(pid %d) used deprecated START_ARRAY ioctl. "
2694                                "This will not be supported beyond 2.6\n",
2695                                current->comm, current->pid);
2696                         cnt--;
2697                 }
2698                 err = autostart_array(new_decode_dev(arg));
2699                 if (err) {
2700                         printk(KERN_WARNING "md: autostart failed!\n");
2701                         goto abort;
2702                 }
2703                 goto done;
2704         }
2705
2706         err = mddev_lock(mddev);
2707         if (err) {
2708                 printk(KERN_INFO 
2709                         "md: ioctl lock interrupted, reason %d, cmd %d\n",
2710                         err, cmd);
2711                 goto abort;
2712         }
2713
2714         switch (cmd)
2715         {
2716                 case SET_ARRAY_INFO:
2717                         {
2718                                 mdu_array_info_t info;
2719                                 if (!arg)
2720                                         memset(&info, 0, sizeof(info));
2721                                 else if (copy_from_user(&info, argp, sizeof(info))) {
2722                                         err = -EFAULT;
2723                                         goto abort_unlock;
2724                                 }
2725                                 if (mddev->pers) {
2726                                         err = update_array_info(mddev, &info);
2727                                         if (err) {
2728                                                 printk(KERN_WARNING "md: couldn't update"
2729                                                        " array info. %d\n", err);
2730                                                 goto abort_unlock;
2731                                         }
2732                                         goto done_unlock;
2733                                 }
2734                                 if (!list_empty(&mddev->disks)) {
2735                                         printk(KERN_WARNING
2736                                                "md: array %s already has disks!\n",
2737                                                mdname(mddev));
2738                                         err = -EBUSY;
2739                                         goto abort_unlock;
2740                                 }
2741                                 if (mddev->raid_disks) {
2742                                         printk(KERN_WARNING
2743                                                "md: array %s already initialised!\n",
2744                                                mdname(mddev));
2745                                         err = -EBUSY;
2746                                         goto abort_unlock;
2747                                 }
2748                                 err = set_array_info(mddev, &info);
2749                                 if (err) {
2750                                         printk(KERN_WARNING "md: couldn't set"
2751                                                " array info. %d\n", err);
2752                                         goto abort_unlock;
2753                                 }
2754                         }
2755                         goto done_unlock;
2756
2757                 default:;
2758         }
2759
2760         /*
2761          * Commands querying/configuring an existing array:
2762          */
2763         /* if we are not initialised yet, only ADD_NEW_DISK, STOP_ARRAY,
2764          * RUN_ARRAY, and SET_BITMAP_FILE are allowed */
2765         if (!mddev->raid_disks && cmd != ADD_NEW_DISK && cmd != STOP_ARRAY
2766                         && cmd != RUN_ARRAY && cmd != SET_BITMAP_FILE) {
2767                 err = -ENODEV;
2768                 goto abort_unlock;
2769         }
2770
2771         /*
2772          * Commands even a read-only array can execute:
2773          */
2774         switch (cmd)
2775         {
2776                 case GET_ARRAY_INFO:
2777                         err = get_array_info(mddev, argp);
2778                         goto done_unlock;
2779
2780                 case GET_BITMAP_FILE:
2781                         err = get_bitmap_file(mddev, (void *)arg);
2782                         goto done_unlock;
2783
2784                 case GET_DISK_INFO:
2785                         err = get_disk_info(mddev, argp);
2786                         goto done_unlock;
2787
2788                 case RESTART_ARRAY_RW:
2789                         err = restart_array(mddev);
2790                         goto done_unlock;
2791
2792                 case STOP_ARRAY:
2793                         err = do_md_stop (mddev, 0);
2794                         goto done_unlock;
2795
2796                 case STOP_ARRAY_RO:
2797                         err = do_md_stop (mddev, 1);
2798                         goto done_unlock;
2799
2800         /*
2801          * We have a problem here : there is no easy way to give a CHS
2802          * virtual geometry. We currently pretend that we have a 2 heads
2803          * 4 sectors (with a BIG number of cylinders...). This drives
2804          * dosfs just mad... ;-)
2805          */
2806                 case HDIO_GETGEO:
2807                         if (!loc) {
2808                                 err = -EINVAL;
2809                                 goto abort_unlock;
2810                         }
2811                         err = put_user (2, (char __user *) &loc->heads);
2812                         if (err)
2813                                 goto abort_unlock;
2814                         err = put_user (4, (char __user *) &loc->sectors);
2815                         if (err)
2816                                 goto abort_unlock;
2817                         err = put_user(get_capacity(mddev->gendisk)/8,
2818                                         (short __user *) &loc->cylinders);
2819                         if (err)
2820                                 goto abort_unlock;
2821                         err = put_user (get_start_sect(inode->i_bdev),
2822                                                 (long __user *) &loc->start);
2823                         goto done_unlock;
2824         }
2825
2826         /*
2827          * The remaining ioctls are changing the state of the
2828          * superblock, so we do not allow read-only arrays
2829          * here:
2830          */
2831         if (mddev->ro) {
2832                 err = -EROFS;
2833                 goto abort_unlock;
2834         }
2835
2836         switch (cmd)
2837         {
2838                 case ADD_NEW_DISK:
2839                 {
2840                         mdu_disk_info_t info;
2841                         if (copy_from_user(&info, argp, sizeof(info)))
2842                                 err = -EFAULT;
2843                         else
2844                                 err = add_new_disk(mddev, &info);
2845                         goto done_unlock;
2846                 }
2847
2848                 case HOT_REMOVE_DISK:
2849                         err = hot_remove_disk(mddev, new_decode_dev(arg));
2850                         goto done_unlock;
2851
2852                 case HOT_ADD_DISK:
2853                         err = hot_add_disk(mddev, new_decode_dev(arg));
2854                         goto done_unlock;
2855
2856                 case SET_DISK_FAULTY:
2857                         err = set_disk_faulty(mddev, new_decode_dev(arg));
2858                         goto done_unlock;
2859
2860                 case RUN_ARRAY:
2861                         err = do_md_run (mddev);
2862                         goto done_unlock;
2863
2864                 case SET_BITMAP_FILE:
2865                         err = set_bitmap_file(mddev, (int)arg);
2866                         goto done_unlock;
2867
2868                 default:
2869                         if (_IOC_TYPE(cmd) == MD_MAJOR)
2870                                 printk(KERN_WARNING "md: %s(pid %d) used"
2871                                         " obsolete MD ioctl, upgrade your"
2872                                         " software to use new ictls.\n",
2873                                         current->comm, current->pid);
2874                         err = -EINVAL;
2875                         goto abort_unlock;
2876         }
2877
2878 done_unlock:
2879 abort_unlock:
2880         mddev_unlock(mddev);
2881
2882         return err;
2883 done:
2884         if (err)
2885                 MD_BUG();
2886 abort:
2887         return err;
2888 }
2889
2890 static int md_open(struct inode *inode, struct file *file)
2891 {
2892         /*
2893          * Succeed if we can lock the mddev, which confirms that
2894          * it isn't being stopped right now.
2895          */
2896         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
2897         int err;
2898
2899         if ((err = mddev_lock(mddev)))
2900                 goto out;
2901
2902         err = 0;
2903         mddev_get(mddev);
2904         mddev_unlock(mddev);
2905
2906         check_disk_change(inode->i_bdev);
2907  out:
2908         return err;
2909 }
2910
2911 static int md_release(struct inode *inode, struct file * file)
2912 {
2913         mddev_t *mddev = inode->i_bdev->bd_disk->private_data;
2914
2915         if (!mddev)
2916                 BUG();
2917         mddev_put(mddev);
2918
2919         return 0;
2920 }
2921
2922 static int md_media_changed(struct gendisk *disk)
2923 {
2924         mddev_t *mddev = disk->private_data;
2925
2926         return mddev->changed;
2927 }
2928
2929 static int md_revalidate(struct gendisk *disk)
2930 {
2931         mddev_t *mddev = disk->private_data;
2932
2933         mddev->changed = 0;
2934         return 0;
2935 }
2936 static struct block_device_operations md_fops =
2937 {
2938         .owner          = THIS_MODULE,
2939         .open           = md_open,
2940         .release        = md_release,
2941         .ioctl          = md_ioctl,
2942         .media_changed  = md_media_changed,
2943         .revalidate_disk= md_revalidate,
2944 };
2945
2946 static int md_thread(void * arg)
2947 {
2948         mdk_thread_t *thread = arg;
2949
2950         lock_kernel();
2951
2952         /*
2953          * Detach thread
2954          */
2955
2956         daemonize(thread->name, mdname(thread->mddev));
2957
2958         current->exit_signal = SIGCHLD;
2959         allow_signal(SIGKILL);
2960         thread->tsk = current;
2961
2962         /*
2963          * md_thread is a 'system-thread', it's priority should be very
2964          * high. We avoid resource deadlocks individually in each
2965          * raid personality. (RAID5 does preallocation) We also use RR and
2966          * the very same RT priority as kswapd, thus we will never get
2967          * into a priority inversion deadlock.
2968          *
2969          * we definitely have to have equal or higher priority than
2970          * bdflush, otherwise bdflush will deadlock if there are too
2971          * many dirty RAID5 blocks.
2972          */
2973         unlock_kernel();
2974
2975         complete(thread->event);
2976         while (thread->run) {
2977                 void (*run)(mddev_t *);
2978
2979                 wait_event_interruptible_timeout(thread->wqueue,
2980                                                  test_bit(THREAD_WAKEUP, &thread->flags),
2981                                                  thread->timeout);
2982                 try_to_freeze();
2983
2984                 clear_bit(THREAD_WAKEUP, &thread->flags);
2985
2986                 run = thread->run;
2987                 if (run)
2988                         run(thread->mddev);
2989
2990                 if (signal_pending(current))
2991                         flush_signals(current);
2992         }
2993         complete(thread->event);
2994         return 0;
2995 }
2996
2997 void md_wakeup_thread(mdk_thread_t *thread)
2998 {
2999         if (thread) {
3000                 dprintk("md: waking up MD thread %s.\n", thread->tsk->comm);
3001                 set_bit(THREAD_WAKEUP, &thread->flags);
3002                 wake_up(&thread->wqueue);
3003         }
3004 }
3005
3006 mdk_thread_t *md_register_thread(void (*run) (mddev_t *), mddev_t *mddev,
3007                                  const char *name)
3008 {
3009         mdk_thread_t *thread;
3010         int ret;
3011         struct completion event;
3012
3013         thread = (mdk_thread_t *) kmalloc
3014                                 (sizeof(mdk_thread_t), GFP_KERNEL);
3015         if (!thread)
3016                 return NULL;
3017
3018         memset(thread, 0, sizeof(mdk_thread_t));
3019         init_waitqueue_head(&thread->wqueue);
3020
3021         init_completion(&event);
3022         thread->event = &event;
3023         thread->run = run;
3024         thread->mddev = mddev;
3025         thread->name = name;
3026         thread->timeout = MAX_SCHEDULE_TIMEOUT;
3027         ret = kernel_thread(md_thread, thread, 0);
3028         if (ret < 0) {
3029                 kfree(thread);
3030                 return NULL;
3031         }
3032         wait_for_completion(&event);
3033         return thread;
3034 }
3035
3036 void md_unregister_thread(mdk_thread_t *thread)
3037 {
3038         struct completion event;
3039
3040         init_completion(&event);
3041
3042         thread->event = &event;
3043
3044         /* As soon as ->run is set to NULL, the task could disappear,
3045          * so we need to hold tasklist_lock until we have sent the signal
3046          */
3047         dprintk("interrupting MD-thread pid %d\n", thread->tsk->pid);
3048         read_lock(&tasklist_lock);
3049         thread->run = NULL;
3050         send_sig(SIGKILL, thread->tsk, 1);
3051         read_unlock(&tasklist_lock);
3052         wait_for_completion(&event);
3053         kfree(thread);
3054 }
3055
3056 void md_error(mddev_t *mddev, mdk_rdev_t *rdev)
3057 {
3058         if (!mddev) {
3059                 MD_BUG();
3060                 return;
3061         }
3062
3063         if (!rdev || rdev->faulty)
3064                 return;
3065 /*
3066         dprintk("md_error dev:%s, rdev:(%d:%d), (caller: %p,%p,%p,%p).\n",
3067                 mdname(mddev),
3068                 MAJOR(rdev->bdev->bd_dev), MINOR(rdev->bdev->bd_dev),
3069                 __builtin_return_address(0),__builtin_return_address(1),
3070                 __builtin_return_address(2),__builtin_return_address(3));
3071 */
3072         if (!mddev->pers->error_handler)
3073                 return;
3074         mddev->pers->error_handler(mddev,rdev);
3075         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3076         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3077         md_wakeup_thread(mddev->thread);
3078 }
3079
3080 /* seq_file implementation /proc/mdstat */
3081
3082 static void status_unused(struct seq_file *seq)
3083 {
3084         int i = 0;
3085         mdk_rdev_t *rdev;
3086         struct list_head *tmp;
3087
3088         seq_printf(seq, "unused devices: ");
3089
3090         ITERATE_RDEV_PENDING(rdev,tmp) {
3091                 char b[BDEVNAME_SIZE];
3092                 i++;
3093                 seq_printf(seq, "%s ",
3094                               bdevname(rdev->bdev,b));
3095         }
3096         if (!i)
3097                 seq_printf(seq, "<none>");
3098
3099         seq_printf(seq, "\n");
3100 }
3101
3102
3103 static void status_resync(struct seq_file *seq, mddev_t * mddev)
3104 {
3105         unsigned long max_blocks, resync, res, dt, db, rt;
3106
3107         resync = (mddev->curr_resync - atomic_read(&mddev->recovery_active))/2;
3108
3109         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3110                 max_blocks = mddev->resync_max_sectors >> 1;
3111         else
3112                 max_blocks = mddev->size;
3113
3114         /*
3115          * Should not happen.
3116          */
3117         if (!max_blocks) {
3118                 MD_BUG();
3119                 return;
3120         }
3121         res = (resync/1024)*1000/(max_blocks/1024 + 1);
3122         {
3123                 int i, x = res/50, y = 20-x;
3124                 seq_printf(seq, "[");
3125                 for (i = 0; i < x; i++)
3126                         seq_printf(seq, "=");
3127                 seq_printf(seq, ">");
3128                 for (i = 0; i < y; i++)
3129                         seq_printf(seq, ".");
3130                 seq_printf(seq, "] ");
3131         }
3132         seq_printf(seq, " %s =%3lu.%lu%% (%lu/%lu)",
3133                       (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) ?
3134                        "resync" : "recovery"),
3135                       res/10, res % 10, resync, max_blocks);
3136
3137         /*
3138          * We do not want to overflow, so the order of operands and
3139          * the * 100 / 100 trick are important. We do a +1 to be
3140          * safe against division by zero. We only estimate anyway.
3141          *
3142          * dt: time from mark until now
3143          * db: blocks written from mark until now
3144          * rt: remaining time
3145          */
3146         dt = ((jiffies - mddev->resync_mark) / HZ);
3147         if (!dt) dt++;
3148         db = resync - (mddev->resync_mark_cnt/2);
3149         rt = (dt * ((max_blocks-resync) / (db/100+1)))/100;
3150
3151         seq_printf(seq, " finish=%lu.%lumin", rt / 60, (rt % 60)/6);
3152
3153         seq_printf(seq, " speed=%ldK/sec", db/dt);
3154 }
3155
3156 static void *md_seq_start(struct seq_file *seq, loff_t *pos)
3157 {
3158         struct list_head *tmp;
3159         loff_t l = *pos;
3160         mddev_t *mddev;
3161
3162         if (l >= 0x10000)
3163                 return NULL;
3164         if (!l--)
3165                 /* header */
3166                 return (void*)1;
3167
3168         spin_lock(&all_mddevs_lock);
3169         list_for_each(tmp,&all_mddevs)
3170                 if (!l--) {
3171                         mddev = list_entry(tmp, mddev_t, all_mddevs);
3172                         mddev_get(mddev);
3173                         spin_unlock(&all_mddevs_lock);
3174                         return mddev;
3175                 }
3176         spin_unlock(&all_mddevs_lock);
3177         if (!l--)
3178                 return (void*)2;/* tail */
3179         return NULL;
3180 }
3181
3182 static void *md_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3183 {
3184         struct list_head *tmp;
3185         mddev_t *next_mddev, *mddev = v;
3186         
3187         ++*pos;
3188         if (v == (void*)2)
3189                 return NULL;
3190
3191         spin_lock(&all_mddevs_lock);
3192         if (v == (void*)1)
3193                 tmp = all_mddevs.next;
3194         else
3195                 tmp = mddev->all_mddevs.next;
3196         if (tmp != &all_mddevs)
3197                 next_mddev = mddev_get(list_entry(tmp,mddev_t,all_mddevs));
3198         else {
3199                 next_mddev = (void*)2;
3200                 *pos = 0x10000;
3201         }               
3202         spin_unlock(&all_mddevs_lock);
3203
3204         if (v != (void*)1)
3205                 mddev_put(mddev);
3206         return next_mddev;
3207
3208 }
3209
3210 static void md_seq_stop(struct seq_file *seq, void *v)
3211 {
3212         mddev_t *mddev = v;
3213
3214         if (mddev && v != (void*)1 && v != (void*)2)
3215                 mddev_put(mddev);
3216 }
3217
3218 static int md_seq_show(struct seq_file *seq, void *v)
3219 {
3220         mddev_t *mddev = v;
3221         sector_t size;
3222         struct list_head *tmp2;
3223         mdk_rdev_t *rdev;
3224         int i;
3225         struct bitmap *bitmap;
3226
3227         if (v == (void*)1) {
3228                 seq_printf(seq, "Personalities : ");
3229                 spin_lock(&pers_lock);
3230                 for (i = 0; i < MAX_PERSONALITY; i++)
3231                         if (pers[i])
3232                                 seq_printf(seq, "[%s] ", pers[i]->name);
3233
3234                 spin_unlock(&pers_lock);
3235                 seq_printf(seq, "\n");
3236                 return 0;
3237         }
3238         if (v == (void*)2) {
3239                 status_unused(seq);
3240                 return 0;
3241         }
3242
3243         if (mddev_lock(mddev)!=0) 
3244                 return -EINTR;
3245         if (mddev->pers || mddev->raid_disks || !list_empty(&mddev->disks)) {
3246                 seq_printf(seq, "%s : %sactive", mdname(mddev),
3247                                                 mddev->pers ? "" : "in");
3248                 if (mddev->pers) {
3249                         if (mddev->ro)
3250                                 seq_printf(seq, " (read-only)");
3251                         seq_printf(seq, " %s", mddev->pers->name);
3252                 }
3253
3254                 size = 0;
3255                 ITERATE_RDEV(mddev,rdev,tmp2) {
3256                         char b[BDEVNAME_SIZE];
3257                         seq_printf(seq, " %s[%d]",
3258                                 bdevname(rdev->bdev,b), rdev->desc_nr);
3259                         if (rdev->faulty) {
3260                                 seq_printf(seq, "(F)");
3261                                 continue;
3262                         }
3263                         size += rdev->size;
3264                 }
3265
3266                 if (!list_empty(&mddev->disks)) {
3267                         if (mddev->pers)
3268                                 seq_printf(seq, "\n      %llu blocks",
3269                                         (unsigned long long)mddev->array_size);
3270                         else
3271                                 seq_printf(seq, "\n      %llu blocks",
3272                                         (unsigned long long)size);
3273                 }
3274
3275                 if (mddev->pers) {
3276                         mddev->pers->status (seq, mddev);
3277                         seq_printf(seq, "\n      ");
3278                         if (mddev->curr_resync > 2) {
3279                                 status_resync (seq, mddev);
3280                                 seq_printf(seq, "\n      ");
3281                         } else if (mddev->curr_resync == 1 || mddev->curr_resync == 2)
3282                                 seq_printf(seq, "       resync=DELAYED\n      ");
3283                 } else
3284                         seq_printf(seq, "\n       ");
3285
3286                 if ((bitmap = mddev->bitmap)) {
3287                         unsigned long chunk_kb;
3288                         unsigned long flags;
3289                         spin_lock_irqsave(&bitmap->lock, flags);
3290                         chunk_kb = bitmap->chunksize >> 10;
3291                         seq_printf(seq, "bitmap: %lu/%lu pages [%luKB], "
3292                                 "%lu%s chunk",
3293                                 bitmap->pages - bitmap->missing_pages,
3294                                 bitmap->pages,
3295                                 (bitmap->pages - bitmap->missing_pages)
3296                                         << (PAGE_SHIFT - 10),
3297                                 chunk_kb ? chunk_kb : bitmap->chunksize,
3298                                 chunk_kb ? "KB" : "B");
3299                         if (bitmap->file) {
3300                                 seq_printf(seq, ", file: ");
3301                                 seq_path(seq, bitmap->file->f_vfsmnt,
3302                                          bitmap->file->f_dentry," \t\n");
3303                         }
3304
3305                         seq_printf(seq, "\n");
3306                         spin_unlock_irqrestore(&bitmap->lock, flags);
3307                 }
3308
3309                 seq_printf(seq, "\n");
3310         }
3311         mddev_unlock(mddev);
3312         
3313         return 0;
3314 }
3315
3316 static struct seq_operations md_seq_ops = {
3317         .start  = md_seq_start,
3318         .next   = md_seq_next,
3319         .stop   = md_seq_stop,
3320         .show   = md_seq_show,
3321 };
3322
3323 static int md_seq_open(struct inode *inode, struct file *file)
3324 {
3325         int error;
3326
3327         error = seq_open(file, &md_seq_ops);
3328         return error;
3329 }
3330
3331 static struct file_operations md_seq_fops = {
3332         .open           = md_seq_open,
3333         .read           = seq_read,
3334         .llseek         = seq_lseek,
3335         .release        = seq_release,
3336 };
3337
3338 int register_md_personality(int pnum, mdk_personality_t *p)
3339 {
3340         if (pnum >= MAX_PERSONALITY) {
3341                 printk(KERN_ERR
3342                        "md: tried to install personality %s as nr %d, but max is %lu\n",
3343                        p->name, pnum, MAX_PERSONALITY-1);
3344                 return -EINVAL;
3345         }
3346
3347         spin_lock(&pers_lock);
3348         if (pers[pnum]) {
3349                 spin_unlock(&pers_lock);
3350                 return -EBUSY;
3351         }
3352
3353         pers[pnum] = p;
3354         printk(KERN_INFO "md: %s personality registered as nr %d\n", p->name, pnum);
3355         spin_unlock(&pers_lock);
3356         return 0;
3357 }
3358
3359 int unregister_md_personality(int pnum)
3360 {
3361         if (pnum >= MAX_PERSONALITY)
3362                 return -EINVAL;
3363
3364         printk(KERN_INFO "md: %s personality unregistered\n", pers[pnum]->name);
3365         spin_lock(&pers_lock);
3366         pers[pnum] = NULL;
3367         spin_unlock(&pers_lock);
3368         return 0;
3369 }
3370
3371 static int is_mddev_idle(mddev_t *mddev)
3372 {
3373         mdk_rdev_t * rdev;
3374         struct list_head *tmp;
3375         int idle;
3376         unsigned long curr_events;
3377
3378         idle = 1;
3379         ITERATE_RDEV(mddev,rdev,tmp) {
3380                 struct gendisk *disk = rdev->bdev->bd_contains->bd_disk;
3381                 curr_events = disk_stat_read(disk, read_sectors) + 
3382                                 disk_stat_read(disk, write_sectors) - 
3383                                 atomic_read(&disk->sync_io);
3384                 /* Allow some slack between valud of curr_events and last_events,
3385                  * as there are some uninteresting races.
3386                  * Note: the following is an unsigned comparison.
3387                  */
3388                 if ((curr_events - rdev->last_events + 32) > 64) {
3389                         rdev->last_events = curr_events;
3390                         idle = 0;
3391                 }
3392         }
3393         return idle;
3394 }
3395
3396 void md_done_sync(mddev_t *mddev, int blocks, int ok)
3397 {
3398         /* another "blocks" (512byte) blocks have been synced */
3399         atomic_sub(blocks, &mddev->recovery_active);
3400         wake_up(&mddev->recovery_wait);
3401         if (!ok) {
3402                 set_bit(MD_RECOVERY_ERR, &mddev->recovery);
3403                 md_wakeup_thread(mddev->thread);
3404                 // stop recovery, signal do_sync ....
3405         }
3406 }
3407
3408
3409 /* md_write_start(mddev, bi)
3410  * If we need to update some array metadata (e.g. 'active' flag
3411  * in superblock) before writing, schedule a superblock update
3412  * and wait for it to complete.
3413  */
3414 void md_write_start(mddev_t *mddev, struct bio *bi)
3415 {
3416         DEFINE_WAIT(w);
3417         if (bio_data_dir(bi) != WRITE)
3418                 return;
3419
3420         atomic_inc(&mddev->writes_pending);
3421         if (mddev->in_sync) {
3422                 spin_lock(&mddev->write_lock);
3423                 if (mddev->in_sync) {
3424                         mddev->in_sync = 0;
3425                         mddev->sb_dirty = 1;
3426                         md_wakeup_thread(mddev->thread);
3427                 }
3428                 spin_unlock(&mddev->write_lock);
3429         }
3430         wait_event(mddev->sb_wait, mddev->sb_dirty==0);
3431 }
3432
3433 void md_write_end(mddev_t *mddev)
3434 {
3435         if (atomic_dec_and_test(&mddev->writes_pending)) {
3436                 if (mddev->safemode == 2)
3437                         md_wakeup_thread(mddev->thread);
3438                 else
3439                         mod_timer(&mddev->safemode_timer, jiffies + mddev->safemode_delay);
3440         }
3441 }
3442
3443 static DECLARE_WAIT_QUEUE_HEAD(resync_wait);
3444
3445 #define SYNC_MARKS      10
3446 #define SYNC_MARK_STEP  (3*HZ)
3447 static void md_do_sync(mddev_t *mddev)
3448 {
3449         mddev_t *mddev2;
3450         unsigned int currspeed = 0,
3451                  window;
3452         sector_t max_sectors,j, io_sectors;
3453         unsigned long mark[SYNC_MARKS];
3454         sector_t mark_cnt[SYNC_MARKS];
3455         int last_mark,m;
3456         struct list_head *tmp;
3457         sector_t last_check;
3458         int skipped = 0;
3459
3460         /* just incase thread restarts... */
3461         if (test_bit(MD_RECOVERY_DONE, &mddev->recovery))
3462                 return;
3463
3464         /* we overload curr_resync somewhat here.
3465          * 0 == not engaged in resync at all
3466          * 2 == checking that there is no conflict with another sync
3467          * 1 == like 2, but have yielded to allow conflicting resync to
3468          *              commense
3469          * other == active in resync - this many blocks
3470          *
3471          * Before starting a resync we must have set curr_resync to
3472          * 2, and then checked that every "conflicting" array has curr_resync
3473          * less than ours.  When we find one that is the same or higher
3474          * we wait on resync_wait.  To avoid deadlock, we reduce curr_resync
3475          * to 1 if we choose to yield (based arbitrarily on address of mddev structure).
3476          * This will mean we have to start checking from the beginning again.
3477          *
3478          */
3479
3480         do {
3481                 mddev->curr_resync = 2;
3482
3483         try_again:
3484                 if (signal_pending(current)) {
3485                         flush_signals(current);
3486                         goto skip;
3487                 }
3488                 ITERATE_MDDEV(mddev2,tmp) {
3489                         if (mddev2 == mddev)
3490                                 continue;
3491                         if (mddev2->curr_resync && 
3492                             match_mddev_units(mddev,mddev2)) {
3493                                 DEFINE_WAIT(wq);
3494                                 if (mddev < mddev2 && mddev->curr_resync == 2) {
3495                                         /* arbitrarily yield */
3496                                         mddev->curr_resync = 1;
3497                                         wake_up(&resync_wait);
3498                                 }
3499                                 if (mddev > mddev2 && mddev->curr_resync == 1)
3500                                         /* no need to wait here, we can wait the next
3501                                          * time 'round when curr_resync == 2
3502                                          */
3503                                         continue;
3504                                 prepare_to_wait(&resync_wait, &wq, TASK_INTERRUPTIBLE);
3505                                 if (!signal_pending(current)
3506                                     && mddev2->curr_resync >= mddev->curr_resync) {
3507                                         printk(KERN_INFO "md: delaying resync of %s"
3508                                                " until %s has finished resync (they"
3509                                                " share one or more physical units)\n",
3510                                                mdname(mddev), mdname(mddev2));
3511                                         mddev_put(mddev2);
3512                                         schedule();
3513                                         finish_wait(&resync_wait, &wq);
3514                                         goto try_again;
3515                                 }
3516                                 finish_wait(&resync_wait, &wq);
3517                         }
3518                 }
3519         } while (mddev->curr_resync < 2);
3520
3521         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery))
3522                 /* resync follows the size requested by the personality,
3523                  * which defaults to physical size, but can be virtual size
3524                  */
3525                 max_sectors = mddev->resync_max_sectors;
3526         else
3527                 /* recovery follows the physical size of devices */
3528                 max_sectors = mddev->size << 1;
3529
3530         printk(KERN_INFO "md: syncing RAID array %s\n", mdname(mddev));
3531         printk(KERN_INFO "md: minimum _guaranteed_ reconstruction speed:"
3532                 " %d KB/sec/disc.\n", sysctl_speed_limit_min);
3533         printk(KERN_INFO "md: using maximum available idle IO bandwith "
3534                "(but not more than %d KB/sec) for reconstruction.\n",
3535                sysctl_speed_limit_max);
3536
3537         is_mddev_idle(mddev); /* this also initializes IO event counters */
3538         /* we don't use the checkpoint if there's a bitmap */
3539         if (test_bit(MD_RECOVERY_SYNC, &mddev->recovery) && !mddev->bitmap)
3540                 j = mddev->recovery_cp;
3541         else
3542                 j = 0;
3543         io_sectors = 0;
3544         for (m = 0; m < SYNC_MARKS; m++) {
3545                 mark[m] = jiffies;
3546                 mark_cnt[m] = io_sectors;
3547         }
3548         last_mark = 0;
3549         mddev->resync_mark = mark[last_mark];
3550         mddev->resync_mark_cnt = mark_cnt[last_mark];
3551
3552         /*
3553          * Tune reconstruction:
3554          */
3555         window = 32*(PAGE_SIZE/512);
3556         printk(KERN_INFO "md: using %dk window, over a total of %llu blocks.\n",
3557                 window/2,(unsigned long long) max_sectors/2);
3558
3559         atomic_set(&mddev->recovery_active, 0);
3560         init_waitqueue_head(&mddev->recovery_wait);
3561         last_check = 0;
3562
3563         if (j>2) {
3564                 printk(KERN_INFO 
3565                         "md: resuming recovery of %s from checkpoint.\n",
3566                         mdname(mddev));
3567                 mddev->curr_resync = j;
3568         }
3569
3570         while (j < max_sectors) {
3571                 sector_t sectors;
3572
3573                 skipped = 0;
3574                 sectors = mddev->pers->sync_request(mddev, j, &skipped,
3575                                             currspeed < sysctl_speed_limit_min);
3576                 if (sectors == 0) {
3577                         set_bit(MD_RECOVERY_ERR, &mddev->recovery);
3578                         goto out;
3579                 }
3580
3581                 if (!skipped) { /* actual IO requested */
3582                         io_sectors += sectors;
3583                         atomic_add(sectors, &mddev->recovery_active);
3584                 }
3585
3586                 j += sectors;
3587                 if (j>1) mddev->curr_resync = j;
3588
3589
3590                 if (last_check + window > io_sectors || j == max_sectors)
3591                         continue;
3592
3593                 last_check = io_sectors;
3594
3595                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery) ||
3596                     test_bit(MD_RECOVERY_ERR, &mddev->recovery))
3597                         break;
3598
3599         repeat:
3600                 if (time_after_eq(jiffies, mark[last_mark] + SYNC_MARK_STEP )) {
3601                         /* step marks */
3602                         int next = (last_mark+1) % SYNC_MARKS;
3603
3604                         mddev->resync_mark = mark[next];
3605                         mddev->resync_mark_cnt = mark_cnt[next];
3606                         mark[next] = jiffies;
3607                         mark_cnt[next] = io_sectors - atomic_read(&mddev->recovery_active);
3608                         last_mark = next;
3609                 }
3610
3611
3612                 if (signal_pending(current)) {
3613                         /*
3614                          * got a signal, exit.
3615                          */
3616                         printk(KERN_INFO 
3617                                 "md: md_do_sync() got signal ... exiting\n");
3618                         flush_signals(current);
3619                         set_bit(MD_RECOVERY_INTR, &mddev->recovery);
3620                         goto out;
3621                 }
3622
3623                 /*
3624                  * this loop exits only if either when we are slower than
3625                  * the 'hard' speed limit, or the system was IO-idle for
3626                  * a jiffy.
3627                  * the system might be non-idle CPU-wise, but we only care
3628                  * about not overloading the IO subsystem. (things like an
3629                  * e2fsck being done on the RAID array should execute fast)
3630                  */
3631                 mddev->queue->unplug_fn(mddev->queue);
3632                 cond_resched();
3633
3634                 currspeed = ((unsigned long)(io_sectors-mddev->resync_mark_cnt))/2
3635                         /((jiffies-mddev->resync_mark)/HZ +1) +1;
3636
3637                 if (currspeed > sysctl_speed_limit_min) {
3638                         if ((currspeed > sysctl_speed_limit_max) ||
3639                                         !is_mddev_idle(mddev)) {
3640                                 msleep_interruptible(250);
3641                                 goto repeat;
3642                         }
3643                 }
3644         }
3645         printk(KERN_INFO "md: %s: sync done.\n",mdname(mddev));
3646         /*
3647          * this also signals 'finished resyncing' to md_stop
3648          */
3649  out:
3650         mddev->queue->unplug_fn(mddev->queue);
3651
3652         wait_event(mddev->recovery_wait, !atomic_read(&mddev->recovery_active));
3653
3654         /* tell personality that we are finished */
3655         mddev->pers->sync_request(mddev, max_sectors, &skipped, 1);
3656
3657         if (!test_bit(MD_RECOVERY_ERR, &mddev->recovery) &&
3658             mddev->curr_resync > 2 &&
3659             mddev->curr_resync >= mddev->recovery_cp) {
3660                 if (test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
3661                         printk(KERN_INFO 
3662                                 "md: checkpointing recovery of %s.\n",
3663                                 mdname(mddev));
3664                         mddev->recovery_cp = mddev->curr_resync;
3665                 } else
3666                         mddev->recovery_cp = MaxSector;
3667         }
3668
3669  skip:
3670         mddev->curr_resync = 0;
3671         wake_up(&resync_wait);
3672         set_bit(MD_RECOVERY_DONE, &mddev->recovery);
3673         md_wakeup_thread(mddev->thread);
3674 }
3675
3676
3677 /*
3678  * This routine is regularly called by all per-raid-array threads to
3679  * deal with generic issues like resync and super-block update.
3680  * Raid personalities that don't have a thread (linear/raid0) do not
3681  * need this as they never do any recovery or update the superblock.
3682  *
3683  * It does not do any resync itself, but rather "forks" off other threads
3684  * to do that as needed.
3685  * When it is determined that resync is needed, we set MD_RECOVERY_RUNNING in
3686  * "->recovery" and create a thread at ->sync_thread.
3687  * When the thread finishes it sets MD_RECOVERY_DONE (and might set MD_RECOVERY_ERR)
3688  * and wakeups up this thread which will reap the thread and finish up.
3689  * This thread also removes any faulty devices (with nr_pending == 0).
3690  *
3691  * The overall approach is:
3692  *  1/ if the superblock needs updating, update it.
3693  *  2/ If a recovery thread is running, don't do anything else.
3694  *  3/ If recovery has finished, clean up, possibly marking spares active.
3695  *  4/ If there are any faulty devices, remove them.
3696  *  5/ If array is degraded, try to add spares devices
3697  *  6/ If array has spares or is not in-sync, start a resync thread.
3698  */
3699 void md_check_recovery(mddev_t *mddev)
3700 {
3701         mdk_rdev_t *rdev;
3702         struct list_head *rtmp;
3703
3704
3705         if (mddev->bitmap)
3706                 bitmap_daemon_work(mddev->bitmap);
3707
3708         if (mddev->ro)
3709                 return;
3710
3711         if (signal_pending(current)) {
3712                 if (mddev->pers->sync_request) {
3713                         printk(KERN_INFO "md: %s in immediate safe mode\n",
3714                                mdname(mddev));
3715                         mddev->safemode = 2;
3716                 }
3717                 flush_signals(current);
3718         }
3719
3720         if ( ! (
3721                 mddev->sb_dirty ||
3722                 test_bit(MD_RECOVERY_NEEDED, &mddev->recovery) ||
3723                 test_bit(MD_RECOVERY_DONE, &mddev->recovery) ||
3724                 (mddev->safemode == 1) ||
3725                 (mddev->safemode == 2 && ! atomic_read(&mddev->writes_pending)
3726                  && !mddev->in_sync && mddev->recovery_cp == MaxSector)
3727                 ))
3728                 return;
3729
3730         if (mddev_trylock(mddev)==0) {
3731                 int spares =0;
3732
3733                 spin_lock(&mddev->write_lock);
3734                 if (mddev->safemode && !atomic_read(&mddev->writes_pending) &&
3735                     !mddev->in_sync && mddev->recovery_cp == MaxSector) {
3736                         mddev->in_sync = 1;
3737                         mddev->sb_dirty = 1;
3738                 }
3739                 if (mddev->safemode == 1)
3740                         mddev->safemode = 0;
3741                 spin_unlock(&mddev->write_lock);
3742
3743                 if (mddev->sb_dirty)
3744                         md_update_sb(mddev);
3745
3746
3747                 if (test_bit(MD_RECOVERY_RUNNING, &mddev->recovery) &&
3748                     !test_bit(MD_RECOVERY_DONE, &mddev->recovery)) {
3749                         /* resync/recovery still happening */
3750                         clear_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3751                         goto unlock;
3752                 }
3753                 if (mddev->sync_thread) {
3754                         /* resync has finished, collect result */
3755                         md_unregister_thread(mddev->sync_thread);
3756                         mddev->sync_thread = NULL;
3757                         if (!test_bit(MD_RECOVERY_ERR, &mddev->recovery) &&
3758                             !test_bit(MD_RECOVERY_INTR, &mddev->recovery)) {
3759                                 /* success...*/
3760                                 /* activate any spares */
3761                                 mddev->pers->spare_active(mddev);
3762                         }
3763                         md_update_sb(mddev);
3764
3765                         /* if array is no-longer degraded, then any saved_raid_disk
3766                          * information must be scrapped
3767                          */
3768                         if (!mddev->degraded)
3769                                 ITERATE_RDEV(mddev,rdev,rtmp)
3770                                         rdev->saved_raid_disk = -1;
3771
3772                         mddev->recovery = 0;
3773                         /* flag recovery needed just to double check */
3774                         set_bit(MD_RECOVERY_NEEDED, &mddev->recovery);
3775                         goto unlock;
3776                 }
3777                 if (mddev->recovery)
3778                         /* probably just the RECOVERY_NEEDED flag */
3779                         mddev->recovery = 0;
3780
3781                 /* no recovery is running.
3782                  * remove any failed drives, then
3783                  * add spares if possible.
3784                  * Spare are also removed and re-added, to allow
3785                  * the personality to fail the re-add.
3786                  */
3787                 ITERATE_RDEV(mddev,rdev,rtmp)
3788                         if (rdev->raid_disk >= 0 &&
3789                             (rdev->faulty || ! rdev->in_sync) &&
3790                             atomic_read(&rdev->nr_pending)==0) {
3791                                 if (mddev->pers->hot_remove_disk(mddev, rdev->raid_disk)==0)
3792                                         rdev->raid_disk = -1;
3793                         }
3794
3795                 if (mddev->degraded) {
3796                         ITERATE_RDEV(mddev,rdev,rtmp)
3797                                 if (rdev->raid_disk < 0
3798                                     && !rdev->faulty) {
3799                                         if (mddev->pers->hot_add_disk(mddev,rdev))
3800                                                 spares++;
3801                                         else
3802                                                 break;
3803                                 }
3804                 }
3805
3806                 if (!spares && (mddev->recovery_cp == MaxSector )) {
3807                         /* nothing we can do ... */
3808                         goto unlock;
3809                 }
3810                 if (mddev->pers->sync_request) {
3811                         set_bit(MD_RECOVERY_RUNNING, &mddev->recovery);
3812                         if (!spares)
3813                                 set_bit(MD_RECOVERY_SYNC, &mddev->recovery);
3814                         if (spares && mddev->bitmap && ! mddev->bitmap->file) {
3815                                 /* We are adding a device or devices to an array
3816                                  * which has the bitmap stored on all devices.
3817                                  * So make sure all bitmap pages get written
3818                                  */
3819                                 bitmap_write_all(mddev->bitmap);
3820                         }
3821                         mddev->sync_thread = md_register_thread(md_do_sync,
3822                                                                 mddev,
3823                                                                 "%s_resync");
3824                         if (!mddev->sync_thread) {
3825                                 printk(KERN_ERR "%s: could not start resync"
3826                                         " thread...\n", 
3827                                         mdname(mddev));
3828                                 /* leave the spares where they are, it shouldn't hurt */
3829                                 mddev->recovery = 0;
3830                         } else {
3831                                 md_wakeup_thread(mddev->sync_thread);
3832                         }
3833                 }
3834         unlock:
3835                 mddev_unlock(mddev);
3836         }
3837 }
3838
3839 static int md_notify_reboot(struct notifier_block *this,
3840                             unsigned long code, void *x)
3841 {
3842         struct list_head *tmp;
3843         mddev_t *mddev;
3844
3845         if ((code == SYS_DOWN) || (code == SYS_HALT) || (code == SYS_POWER_OFF)) {
3846
3847                 printk(KERN_INFO "md: stopping all md devices.\n");
3848
3849                 ITERATE_MDDEV(mddev,tmp)
3850                         if (mddev_trylock(mddev)==0)
3851                                 do_md_stop (mddev, 1);
3852                 /*
3853                  * certain more exotic SCSI devices are known to be
3854                  * volatile wrt too early system reboots. While the
3855                  * right place to handle this issue is the given
3856                  * driver, we do want to have a safe RAID driver ...
3857                  */
3858                 mdelay(1000*1);
3859         }
3860         return NOTIFY_DONE;
3861 }
3862
3863 static struct notifier_block md_notifier = {
3864         .notifier_call  = md_notify_reboot,
3865         .next           = NULL,
3866         .priority       = INT_MAX, /* before any real devices */
3867 };
3868
3869 static void md_geninit(void)
3870 {
3871         struct proc_dir_entry *p;
3872
3873         dprintk("md: sizeof(mdp_super_t) = %d\n", (int)sizeof(mdp_super_t));
3874
3875         p = create_proc_entry("mdstat", S_IRUGO, NULL);
3876         if (p)
3877                 p->proc_fops = &md_seq_fops;
3878 }
3879
3880 static int __init md_init(void)
3881 {
3882         int minor;
3883
3884         printk(KERN_INFO "md: md driver %d.%d.%d MAX_MD_DEVS=%d,"
3885                         " MD_SB_DISKS=%d\n",
3886                         MD_MAJOR_VERSION, MD_MINOR_VERSION,
3887                         MD_PATCHLEVEL_VERSION, MAX_MD_DEVS, MD_SB_DISKS);
3888         printk(KERN_INFO "md: bitmap version %d.%d\n", BITMAP_MAJOR,
3889                         BITMAP_MINOR);
3890
3891         if (register_blkdev(MAJOR_NR, "md"))
3892                 return -1;
3893         if ((mdp_major=register_blkdev(0, "mdp"))<=0) {
3894                 unregister_blkdev(MAJOR_NR, "md");
3895                 return -1;
3896         }
3897         devfs_mk_dir("md");
3898         blk_register_region(MKDEV(MAJOR_NR, 0), MAX_MD_DEVS, THIS_MODULE,
3899                                 md_probe, NULL, NULL);
3900         blk_register_region(MKDEV(mdp_major, 0), MAX_MD_DEVS<<MdpMinorShift, THIS_MODULE,
3901                             md_probe, NULL, NULL);
3902
3903         for (minor=0; minor < MAX_MD_DEVS; ++minor)
3904                 devfs_mk_bdev(MKDEV(MAJOR_NR, minor),
3905                                 S_IFBLK|S_IRUSR|S_IWUSR,
3906                                 "md/%d", minor);
3907
3908         for (minor=0; minor < MAX_MD_DEVS; ++minor)
3909                 devfs_mk_bdev(MKDEV(mdp_major, minor<<MdpMinorShift),
3910                               S_IFBLK|S_IRUSR|S_IWUSR,
3911                               "md/mdp%d", minor);
3912
3913
3914         register_reboot_notifier(&md_notifier);
3915         raid_table_header = register_sysctl_table(raid_root_table, 1);
3916
3917         md_geninit();
3918         return (0);
3919 }
3920
3921
3922 #ifndef MODULE
3923
3924 /*
3925  * Searches all registered partitions for autorun RAID arrays
3926  * at boot time.
3927  */
3928 static dev_t detected_devices[128];
3929 static int dev_cnt;
3930
3931 void md_autodetect_dev(dev_t dev)
3932 {
3933         if (dev_cnt >= 0 && dev_cnt < 127)
3934                 detected_devices[dev_cnt++] = dev;
3935 }
3936
3937
3938 static void autostart_arrays(int part)
3939 {
3940         mdk_rdev_t *rdev;
3941         int i;
3942
3943         printk(KERN_INFO "md: Autodetecting RAID arrays.\n");
3944
3945         for (i = 0; i < dev_cnt; i++) {
3946                 dev_t dev = detected_devices[i];
3947
3948                 rdev = md_import_device(dev,0, 0);
3949                 if (IS_ERR(rdev))
3950                         continue;
3951
3952                 if (rdev->faulty) {
3953                         MD_BUG();
3954                         continue;
3955                 }
3956                 list_add(&rdev->same_set, &pending_raid_disks);
3957         }
3958         dev_cnt = 0;
3959
3960         autorun_devices(part);
3961 }
3962
3963 #endif
3964
3965 static __exit void md_exit(void)
3966 {
3967         mddev_t *mddev;
3968         struct list_head *tmp;
3969         int i;
3970         blk_unregister_region(MKDEV(MAJOR_NR,0), MAX_MD_DEVS);
3971         blk_unregister_region(MKDEV(mdp_major,0), MAX_MD_DEVS << MdpMinorShift);
3972         for (i=0; i < MAX_MD_DEVS; i++)
3973                 devfs_remove("md/%d", i);
3974         for (i=0; i < MAX_MD_DEVS; i++)
3975                 devfs_remove("md/d%d", i);
3976
3977         devfs_remove("md");
3978
3979         unregister_blkdev(MAJOR_NR,"md");
3980         unregister_blkdev(mdp_major, "mdp");
3981         unregister_reboot_notifier(&md_notifier);
3982         unregister_sysctl_table(raid_table_header);
3983         remove_proc_entry("mdstat", NULL);
3984         ITERATE_MDDEV(mddev,tmp) {
3985                 struct gendisk *disk = mddev->gendisk;
3986                 if (!disk)
3987                         continue;
3988                 export_array(mddev);
3989                 del_gendisk(disk);
3990                 put_disk(disk);
3991                 mddev->gendisk = NULL;
3992                 mddev_put(mddev);
3993         }
3994 }
3995
3996 module_init(md_init)
3997 module_exit(md_exit)
3998
3999 EXPORT_SYMBOL(register_md_personality);
4000 EXPORT_SYMBOL(unregister_md_personality);
4001 EXPORT_SYMBOL(md_error);
4002 EXPORT_SYMBOL(md_done_sync);
4003 EXPORT_SYMBOL(md_write_start);
4004 EXPORT_SYMBOL(md_write_end);
4005 EXPORT_SYMBOL(md_register_thread);
4006 EXPORT_SYMBOL(md_unregister_thread);
4007 EXPORT_SYMBOL(md_wakeup_thread);
4008 EXPORT_SYMBOL(md_print_devices);
4009 EXPORT_SYMBOL(md_check_recovery);
4010 MODULE_LICENSE("GPL");
4011 MODULE_ALIAS("md");