--- linux/fs/buffer.c.orig	Mon Aug  3 20:40:08 1998
+++ linux/fs/buffer.c	Sat Sep  5 20:15:55 1998
@@ -446,7 +446,7 @@
 		bh->b_next->b_prev = bh;
 }
 
-static inline struct buffer_head * find_buffer(kdev_t dev, int block, int size)
+struct buffer_head * find_buffer(kdev_t dev, int block, int size)
 {		
 	struct buffer_head * tmp;
 
@@ -754,6 +754,24 @@
 	goto repeat;
 }
 
+void init_buffer(struct buffer_head *bh, kdev_t dev, int block,
+                 bh_end_io_t *handler, void *dev_id)
+{
+	bh->b_count = 1;
+	bh->b_list = BUF_CLEAN;
+	bh->b_flushtime = 0;
+	bh->b_dev = dev;
+	bh->b_blocknr = block;
+	bh->b_end_io = handler;
+	bh->b_dev_id = dev_id;
+}
+
+static void end_buffer_io_sync(struct buffer_head *bh, int uptodate)
+{
+	mark_buffer_uptodate(bh, uptodate);
+	unlock_buffer(bh);
+}
+
 /*
  * Ok, this is getblk, and it isn't very clear, again to hinder
  * race-conditions. Most of the code is seldom used, (ie repeating),
@@ -794,12 +812,9 @@
 	/* OK, FINALLY we know that this buffer is the only one of its kind,
 	 * and that it's unused (b_count=0), unlocked (buffer_locked=0),
 	 * and clean */
-	bh->b_count=1;
-	bh->b_list=BUF_CLEAN;
-	bh->b_flushtime=0;
+	init_buffer(bh, dev, block, end_buffer_io_sync, NULL);
+	bh->b_lru_time  = jiffies;
 	bh->b_state=(1<<BH_Touched);
-	bh->b_dev=dev;
-	bh->b_blocknr=block;
 	insert_into_queues(bh);
 	return bh;
 
@@ -926,6 +941,7 @@
 	return NULL;
 }
 
+#if 0
 /*
  * Ok, breada can be used as bread, but additionally to mark other
  * blocks for reading as well. End the argument list with a negative
@@ -991,6 +1007,84 @@
 	return NULL;
 }
 
+#endif
+
+/*
+ * Ok, breada can be used as bread, but additionally to mark other
+ * blocks for reading as well. End the argument list with a negative
+ * number.
+ *
+ * __breada does the same but with block arguments. This is handy if a
+ * device is bigger than 2G on a 32-bit architecture.
+ */
+
+#define NBUF 16
+
+struct buffer_head * breada_blocks(kdev_t dev, int block, int bufsize, int blocks)
+{
+	struct buffer_head * bhlist[NBUF];
+	struct buffer_head * bh;
+	int index;
+	int i, j;
+
+	if (block < 0 || !(bh = getblk(dev,block,bufsize)))
+		return NULL;
+
+	index = BUFSIZE_INDEX(bh->b_size);
+
+	if (buffer_uptodate(bh))
+		return(bh);   
+	else
+		ll_rw_block(READ, 1, &bh);
+
+	if (blocks < (read_ahead[MAJOR(dev)] >> index))
+		blocks = read_ahead[MAJOR(dev)] >> index;
+	if (blocks > NBUF) 
+		blocks = NBUF;
+
+	bhlist[0] = bh;
+	j = 1;
+	for(i=1; i<blocks; i++) {
+		bh = getblk(dev,block+i,bufsize);
+		if (buffer_uptodate(bh)) {
+			brelse(bh);
+			break;
+		}
+		else bhlist[j++] = bh;
+	}
+
+	/* Request the read for these buffers, and then release them. */
+	if (j>1)  
+		ll_rw_block(READA, (j-1), bhlist+1); 
+	for(i=1; i<j; i++)
+		brelse(bhlist[i]);
+
+	/* Wait for this buffer, and then continue on. */
+	bh = bhlist[0];
+	wait_on_buffer(bh);
+	if (buffer_uptodate(bh))
+		return bh;
+	brelse(bh);
+	return NULL;
+}
+
+struct buffer_head * breada(kdev_t dev, int block, int bufsize,
+	unsigned int pos, unsigned int filesize)
+{
+	unsigned int blocks;
+	int index;
+
+	if (pos >= filesize)
+		return NULL;
+
+	index = BUFSIZE_INDEX(bufsize);
+
+	blocks = (filesize - pos) >> (9+index);
+
+	return (breada_blocks(dev,block,bufsize,blocks));
+}
+
+
 static void get_more_buffer_heads(void)
 {
 	struct wait_queue wait = { current, NULL };
@@ -1113,23 +1207,92 @@
  */
 static inline void free_async_buffers (struct buffer_head * bh)
 {
-	struct buffer_head * tmp;
+        struct buffer_head *tmp, *tail;
+
+        /*
+         * Link all the buffers into the b_next_free list,
+         * so we only have to do one xchg() operation ...
+         */
+        tail = bh;
+        while ((tmp = tail->b_this_page) != bh) {
+                tail->b_next_free = tmp;
+                tail = tmp;
+        };
+
+        /* Update the reuse list */
+        tail->b_next_free = xchg(&reuse_list, NULL);
+        reuse_list = bh;
+
+        /* Wake up any waiters ... */
+        wake_up(&buffer_wait);
+}
+
+static void end_buffer_io_async(struct buffer_head * bh, int uptodate)
+{
+	unsigned long flags;
+	struct buffer_head *tmp;
+	struct page *page;
+
+	mark_buffer_uptodate(bh, uptodate);
+	unlock_buffer(bh);
+
+	/* This is a temporary buffer used for page I/O. */
+	page = mem_map + MAP_NR(bh->b_data);
+	if (!PageLocked(page))
+		goto not_locked;
+	if (bh->b_count != 1)
+		goto bad_count;
+
+	if (!test_bit(BH_Uptodate, &bh->b_state))
+		set_bit(PG_error, &page->flags);
 
+	/*
+	 * Be _very_ careful from here on. Bad things can happen if
+	 * two buffer heads end IO at almost the same time and both
+	 * decide that the page is now completely done.
+	 *
+	 * Async buffer_heads are here only as labels for IO, and get
+	 * thrown away once the IO for this page is complete.  IO is
+	 * deemed complete once all buffers have been visited
+	 * (b_count==0) and are now unlocked. We must make sure that
+	 * only the _last_ buffer that decrements its count is the one
+	 * that free's the page..
+	 */
+	save_flags(flags);
+	cli();
+	bh->b_count--;
 	tmp = bh;
 	do {
-		if (!test_bit(BH_FreeOnIO, &tmp->b_state)) {
-			printk ("Whoops: unlock_buffer: "
-				"async IO mismatch on page.\n");
-			return;
-		}
-		tmp->b_next_free = reuse_list;
-		reuse_list = tmp;
-		clear_bit(BH_FreeOnIO, &tmp->b_state);
+		if (tmp->b_count)
+			goto still_busy;
 		tmp = tmp->b_this_page;
 	} while (tmp != bh);
+
+	/* OK, the async IO on this page is complete. */
+	free_async_buffers(bh);
+	restore_flags(flags);
+	clear_bit(PG_locked, &page->flags);
+	wake_up(&page->wait);
+	after_unlock_page(page);
+	return;
+
+still_busy:
+	restore_flags(flags);
+	return;
+
+not_locked:
+	printk ("Whoops: end_buffer_io_async: async io complete on unlocked page\n");
+	return;
+
+bad_count:
+	printk ("Whoops: end_buffer_io_async: b_count != 1 on async io.\n");
+	return;
 }
 
 /*
+ * This is called by end_request() when I/O has completed.
+ */
+/*
  * Start I/O on a page.
  * This function expects the page to be locked and may return before I/O is complete.
  * You then have to check page->locked, page->uptodate, and maybe wait on page->wait.
@@ -1160,12 +1323,7 @@
 		struct buffer_head * tmp;
 		block = *(b++);
 
-		set_bit(BH_FreeOnIO, &next->b_state);
-		next->b_list = BUF_CLEAN;
-		next->b_dev = dev;
-		next->b_blocknr = block;
-		next->b_count = 1;
-		next->b_flushtime = 0;
+		init_buffer(next, dev, block, end_buffer_io_async, NULL);
 		set_bit(BH_Uptodate, &next->b_state);
 
 		/*
@@ -1244,78 +1402,6 @@
 		return;
 	}
 	clear_bit(BH_Uptodate, &bh->b_state);
-}
-
-/*
- * This is called by end_request() when I/O has completed.
- */
-void unlock_buffer(struct buffer_head * bh)
-{
-	unsigned long flags;
-	struct buffer_head *tmp;
-	struct page *page;
-
-	if (!clear_bit(BH_Lock, &bh->b_state))
-		printk ("unlock_buffer: already unlocked on %s\n",
-			kdevname(bh->b_dev));
-	wake_up(&bh->b_wait);
-	if (waitqueue_active(&buffer_wait))
-		wake_up(&buffer_wait);
-
-	if (!test_bit(BH_FreeOnIO, &bh->b_state))
-		return;
-	/* This is a temporary buffer used for page I/O. */
-	page = mem_map + MAP_NR(bh->b_data);
-	if (!PageLocked(page))
-		goto not_locked;
-	if (bh->b_count != 1)
-		goto bad_count;
-
-	if (!test_bit(BH_Uptodate, &bh->b_state))
-		set_bit(PG_error, &page->flags);
-
-	/*
-	 * Be _very_ careful from here on. Bad things can happen if
-	 * two buffer heads end IO at almost the same time and both
-	 * decide that the page is now completely done.
-	 *
-	 * Async buffer_heads are here only as labels for IO, and get
-	 * thrown away once the IO for this page is complete.  IO is
-	 * deemed complete once all buffers have been visited
-	 * (b_count==0) and are now unlocked. We must make sure that
-	 * only the _last_ buffer that decrements its count is the one
-	 * that free's the page..
-	 */
-	save_flags(flags);
-	cli();
-	bh->b_count--;
-	tmp = bh;
-	do {
-		if (tmp->b_count)
-			goto still_busy;
-		tmp = tmp->b_this_page;
-	} while (tmp != bh);
-
-	/* OK, the async IO on this page is complete. */
-	free_async_buffers(bh);
-	restore_flags(flags);
-	clear_bit(PG_locked, &page->flags);
-	wake_up(&page->wait);
-	after_unlock_page(page);
-	wake_up(&buffer_wait);
-	return;
-
-still_busy:
-	restore_flags(flags);
-	return;
-
-not_locked:
-	printk ("Whoops: unlock_buffer: async io complete on unlocked page\n");
-	return;
-
-bad_count:
-	printk ("Whoops: unlock_buffer: b_count != 1 on async io.\n");
-	return;
 }
 
 /*
--- linux/kernel/sys.c.orig	Mon Aug  3 20:33:09 1998
+++ linux/kernel/sys.c	Sat Sep  5 20:15:55 1998
@@ -21,6 +21,7 @@
 #include <linux/fcntl.h>
 #include <linux/acct.h>
 #include <linux/tty.h>
+#include <linux/raid/md.h>
 #if defined(CONFIG_APM) && defined(CONFIG_APM_POWER_OFF)
 #include <linux/apm_bios.h>
 #endif
@@ -187,7 +188,11 @@
 		return -EPERM;
 	if (magic != 0xfee1dead || magic_too != 672274793)
 		return -EINVAL;
+
 	if (flag == 0x01234567) {
+#ifdef CONFIG_BLK_DEV_MD
+		md_notify_reboot(0,0,0);
+#endif
 #ifdef CONFIG_SCSI_GDTH
 		gdth_halt();
 #endif
@@ -197,6 +202,9 @@
 	else if (!flag)
 		C_A_D = 0;
 	else if (flag == 0xCDEF0123) {
+#ifdef CONFIG_BLK_DEV_MD
+		md_notify_reboot(0,0,0);
+#endif
 		printk(KERN_EMERG "System halted\n");
 		sys_kill(-1, SIGKILL);
 #if defined(CONFIG_APM) && defined(CONFIG_APM_POWER_OFF)
--- linux/kernel/ksyms.c.orig	Mon Aug  3 20:40:08 1998
+++ linux/kernel/ksyms.c	Sun Oct  4 16:25:25 1998
@@ -47,6 +47,8 @@
 #include <linux/swap.h>
 #include <linux/ctype.h>
 #include <linux/file.h>
+#include <linux/raid/md.h>
+#include <linux/raid/xor.h>
 
 extern unsigned char aux_device_present, kbd_read_mask;
 
@@ -166,7 +168,6 @@
 	X(brw_page),
 	X(__wait_on_buffer),
 	X(mark_buffer_uptodate),
-	X(unlock_buffer),
 	X(dcache_lookup),
 	X(dcache_add),
 	X(add_blkdev_randomness),
@@ -362,8 +363,28 @@
 
 #ifdef CONFIG_BLK_DEV_MD
 	X(disk_name),	/* for md.c */
+	X(md_size),
+	X(register_md_personality),
+	X(unregister_md_personality),
+	X(partition_name),
+	X(md_arrays),
+	X(md_error),
+	X(md_recover_arrays),
+	X(md_register_thread),
+	X(md_unregister_thread),
+	X(md_update_sb),
+	X(md_map),
+	X(md_wakeup_thread),
+	X(md_do_sync),
+	X(find_buffer),
+	X(init_buffer),
+	X(md_print_devices),
+	X(find_rdev_nr),
+	X(md_check_ordering),
+#ifdef CONFIG_MD_RAID5_MODULE
+	X(xor_block),
+#endif
 #endif
- 	
 	/* binfmt_aout */
 	X(get_write_access),
 	X(put_write_access),
--- linux/include/linux/md.h.orig	Mon Aug  3 20:41:26 1998
+++ linux/include/linux/md.h	Sat Sep  5 20:15:55 1998
@@ -1,275 +0,0 @@
-/*
-   md.h : Multiple Devices driver for Linux
-          Copyright (C) 1994-96 Marc ZYNGIER
-	  <zyngier@ufr-info-p7.ibp.fr> or
-	  <maz@gloups.fdn.fr>
-	  
-   This program is free software; you can redistribute it and/or modify
-   it under the terms of the GNU General Public License as published by
-   the Free Software Foundation; either version 2, or (at your option)
-   any later version.
-   
-   You should have received a copy of the GNU General Public License
-   (for example /usr/src/linux/COPYING); if not, write to the Free
-   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
-*/
-
-#ifndef _MD_H
-#define _MD_H
-
-#include <asm/segment.h>
-#include <linux/major.h>
-#include <linux/ioctl.h>
-#include <linux/types.h>
-
-/*
- * Different major versions are not compatible.
- * Different minor versions are only downward compatible.
- * Different patchlevel versions are downward and upward compatible.
- */
-#define MD_MAJOR_VERSION		0
-#define MD_MINOR_VERSION		36
-#define MD_PATCHLEVEL_VERSION		3
-
-/* ioctls */
-#define REGISTER_DEV _IO (MD_MAJOR, 1)
-#define START_MD     _IO (MD_MAJOR, 2)
-#define STOP_MD      _IO (MD_MAJOR, 3)
-
-/*
-   personalities :
-   Byte 0 : Chunk size factor
-   Byte 1 : Fault tolerance count for each physical device
-            (   0 means no fault tolerance,
-             0xFF means always tolerate faults), not used by now.
-   Byte 2 : Personality
-   Byte 3 : Reserved.
- */
-
-#define FAULT_SHIFT       8
-#define PERSONALITY_SHIFT 16
-
-#define FACTOR_MASK       0x000000FFUL
-#define FAULT_MASK        0x0000FF00UL
-#define PERSONALITY_MASK  0x00FF0000UL
-
-#define MD_RESERVED       0	/* Not used by now */
-#define LINEAR            (1UL << PERSONALITY_SHIFT)
-#define STRIPED           (2UL << PERSONALITY_SHIFT)
-#define RAID0             STRIPED
-#define RAID1             (3UL << PERSONALITY_SHIFT)
-#define RAID5             (4UL << PERSONALITY_SHIFT)
-#define MAX_PERSONALITY   5
-
-/*
- * MD superblock.
- *
- * The MD superblock maintains some statistics on each MD configuration.
- * Each real device in the MD set contains it near the end of the device.
- * Some of the ideas are copied from the ext2fs implementation.
- *
- * We currently use 4096 bytes as follows:
- *
- *	word offset	function
- *
- *	   0  -    31	Constant generic MD device information.
- *        32  -    63   Generic state information.
- *	  64  -   127	Personality specific information.
- *	 128  -   511	12 32-words descriptors of the disks in the raid set.
- *	 512  -   911	Reserved.
- *	 912  -  1023	Disk specific descriptor.
- */
-
-/*
- * If x is the real device size in bytes, we return an apparent size of:
- *
- *	y = (x & ~(MD_RESERVED_BYTES - 1)) - MD_RESERVED_BYTES
- *
- * and place the 4kB superblock at offset y.
- */
-#define MD_RESERVED_BYTES		(64 * 1024)
-#define MD_RESERVED_SECTORS		(MD_RESERVED_BYTES / 512)
-#define MD_RESERVED_BLOCKS		(MD_RESERVED_BYTES / BLOCK_SIZE)
-
-#define MD_NEW_SIZE_SECTORS(x)		((x & ~(MD_RESERVED_SECTORS - 1)) - MD_RESERVED_SECTORS)
-#define MD_NEW_SIZE_BLOCKS(x)		((x & ~(MD_RESERVED_BLOCKS - 1)) - MD_RESERVED_BLOCKS)
-
-#define MD_SB_BYTES			4096
-#define MD_SB_WORDS			(MD_SB_BYTES / 4)
-#define MD_SB_BLOCKS			(MD_SB_BYTES / BLOCK_SIZE)
-#define MD_SB_SECTORS			(MD_SB_BYTES / 512)
-
-/*
- * The following are counted in 32-bit words
- */
-#define	MD_SB_GENERIC_OFFSET		0
-#define MD_SB_PERSONALITY_OFFSET	64
-#define MD_SB_DISKS_OFFSET		128
-#define MD_SB_DESCRIPTOR_OFFSET		992
-
-#define MD_SB_GENERIC_CONSTANT_WORDS	32
-#define MD_SB_GENERIC_STATE_WORDS	32
-#define MD_SB_GENERIC_WORDS		(MD_SB_GENERIC_CONSTANT_WORDS + MD_SB_GENERIC_STATE_WORDS)
-#define MD_SB_PERSONALITY_WORDS		64
-#define MD_SB_DISKS_WORDS		384
-#define MD_SB_DESCRIPTOR_WORDS		32
-#define MD_SB_RESERVED_WORDS		(1024 - MD_SB_GENERIC_WORDS - MD_SB_PERSONALITY_WORDS - MD_SB_DISKS_WORDS - MD_SB_DESCRIPTOR_WORDS)
-#define MD_SB_EQUAL_WORDS		(MD_SB_GENERIC_WORDS + MD_SB_PERSONALITY_WORDS + MD_SB_DISKS_WORDS)
-#define MD_SB_DISKS			(MD_SB_DISKS_WORDS / MD_SB_DESCRIPTOR_WORDS)
-
-/*
- * Device "operational" state bits
- */
-#define MD_FAULTY_DEVICE		0	/* Device is faulty / operational */
-#define MD_ACTIVE_DEVICE		1	/* Device is a part or the raid set / spare disk */
-#define MD_SYNC_DEVICE			2	/* Device is in sync with the raid set */
-
-typedef struct md_device_descriptor_s {
-	__u32 number;		/* 0 Device number in the entire set */
-	__u32 major;		/* 1 Device major number */
-	__u32 minor;		/* 2 Device minor number */
-	__u32 raid_disk;	/* 3 The role of the device in the raid set */
-	__u32 state;		/* 4 Operational state */
-	__u32 reserved[MD_SB_DESCRIPTOR_WORDS - 5];
-} md_descriptor_t;
-
-#define MD_SB_MAGIC		0xa92b4efc
-
-/*
- * Superblock state bits
- */
-#define MD_SB_CLEAN		0
-#define MD_SB_ERRORS		1
-
-typedef struct md_superblock_s {
-
-	/*
-	 * Constant generic information
-	 */
-	__u32 md_magic;		/*  0 MD identifier */
-	__u32 major_version;	/*  1 major version to which the set conforms */
-	__u32 minor_version;	/*  2 minor version to which the set conforms */
-	__u32 patch_version;	/*  3 patchlevel version to which the set conforms */
-	__u32 gvalid_words;	/*  4 Number of non-reserved words in this section */
-	__u32 set_magic;	/*  5 Raid set identifier */
-	__u32 ctime;		/*  6 Creation time */
-	__u32 level;		/*  7 Raid personality (mirroring, raid5, ...) */
-	__u32 size;		/*  8 Apparent size of each individual disk, in kB */
-	__u32 nr_disks;		/*  9 Number of total disks in the raid set */
-	__u32 raid_disks;	/* 10 Number of disks in a fully functional raid set */
-	__u32 gstate_creserved[MD_SB_GENERIC_CONSTANT_WORDS - 11];
-
-	/*
-	 * Generic state information
-	 */
-	__u32 utime;		/*  0 Superblock update time */
-	__u32 state;		/*  1 State bits (clean, ...) */
-	__u32 active_disks;	/*  2 Number of currently active disks (some non-faulty disks might not be in sync) */
-	__u32 working_disks;	/*  3 Number of working disks */
-	__u32 failed_disks;	/*  4 Number of failed disks */
-	__u32 spare_disks;	/*  5 Number of spare disks */
-	__u32 gstate_sreserved[MD_SB_GENERIC_STATE_WORDS - 6];
-
-	/*
-	 * Personality information
-	 */
-	__u32 parity_algorithm;
-	__u32 chunk_size;
-	__u32 pstate_reserved[MD_SB_PERSONALITY_WORDS - 2];
-
-	/*
-	 * Disks information
-	 */
-	md_descriptor_t disks[MD_SB_DISKS];
-
-	/*
-	 * Reserved
-	 */
-	__u32 reserved[MD_SB_RESERVED_WORDS];
-
-	/*
-	 * Active descriptor
-	 */
-	md_descriptor_t descriptor;
-} md_superblock_t;
-
-#ifdef __KERNEL__
-
-#include <linux/mm.h>
-#include <linux/fs.h>
-#include <linux/blkdev.h>
-
-#define MAX_REAL     8		/* Max number of physical dev per md dev */
-#define MAX_MD_DEV   4		/* Max number of md dev */
-#define MAX_MD_THREADS 2	/* Max number of kernel threads */
-
-#define FACTOR(a)         ((a)->repartition & FACTOR_MASK)
-#define MAX_FAULT(a)      (((a)->repartition & FAULT_MASK)>>8)
-#define PERSONALITY(a)    ((a)->repartition & PERSONALITY_MASK)
-
-#define FACTOR_SHIFT(a) (PAGE_SHIFT + (a) - 10)
-
-struct real_dev
-{
-  kdev_t dev;			/* Device number */
-  int size;			/* Device size (in blocks) */
-  int offset;			/* Real device offset (in blocks) in md dev
-				   (only used in linear mode) */
-  struct inode *inode;		/* Lock inode */
-  md_superblock_t *sb;
-  u32 sb_offset;
-};
-
-struct md_dev;
-
-struct md_personality
-{
-  char *name;
-  int (*map)(struct md_dev *md_dev, kdev_t *rdev,
-	              unsigned long *rsector, unsigned long size);
-  int (*make_request)(struct md_dev *md_dev, int rw, struct buffer_head * bh);
-  void (*end_request)(struct buffer_head * bh, int uptodate);
-  int (*run)(int minor, struct md_dev *md_dev);
-  int (*stop)(int minor, struct md_dev *md_dev);
-  int (*status)(char *page, int minor, struct md_dev *md_dev);
-  int (*ioctl)(struct inode *inode, struct file *file,
-	       unsigned int cmd, unsigned long arg);
-  int max_invalid_dev;
-  int (*error_handler)(struct md_dev *md_dev, kdev_t dev);
-};
-
-struct md_dev
-{
-  struct real_dev devices[MAX_REAL];
-  struct md_personality *pers;
-  md_superblock_t *sb;
-  int sb_dirty;
-  int repartition;
-  int busy;
-  int nb_dev;
-  void *private;
-};
-
-struct md_thread {
-	void			(*run) (void *data);
-	void			*data;
-	struct wait_queue	*wqueue;
-	__u32			flags;
-};
-
-#define THREAD_WAKEUP	0
-
-extern struct md_dev md_dev[MAX_MD_DEV];
-extern int md_size[MAX_MD_DEV];
-
-extern char *partition_name (kdev_t dev);
-
-extern int register_md_personality (int p_num, struct md_personality *p);
-extern int unregister_md_personality (int p_num);
-extern struct md_thread *md_register_thread (void (*run) (void *data), void *data);
-extern void md_unregister_thread (struct md_thread *thread);
-extern void md_wakeup_thread(struct md_thread *thread);
-extern int md_update_sb (int minor);
-
-#endif __KERNEL__
-#endif _MD_H
--- linux/include/linux/raid/linear.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/linear.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,32 @@
+#ifndef _LINEAR_H
+#define _LINEAR_H
+
+#include <linux/raid/md.h>
+
+struct dev_info {
+	kdev_t		dev;
+	int		size;
+	unsigned int	offset;
+};
+
+typedef struct dev_info dev_info_t;
+
+struct linear_hash
+{
+	dev_info_t *dev0, *dev1;
+};
+
+struct linear_private_data
+{
+	struct linear_hash	*hash_table;
+	dev_info_t		disks[MD_SB_DISKS];
+	dev_info_t		*smallest;
+	int			nr_zones;
+};
+
+
+typedef struct linear_private_data linear_conf_t;
+
+#define mddev_to_conf(mddev) ((linear_conf_t *) mddev->private)
+
+#endif
--- linux/include/linux/raid/md.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/md.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,93 @@
+/*
+   md.h : Multiple Devices driver for Linux
+          Copyright (C) 1996-98 Ingo Molnar, Gadi Oxman
+          Copyright (C) 1994-96 Marc ZYNGIER
+	  <zyngier@ufr-info-p7.ibp.fr> or
+	  <maz@gloups.fdn.fr>
+	  
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+   
+   You should have received a copy of the GNU General Public License
+   (for example /usr/src/linux/COPYING); if not, write to the Free
+   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
+*/
+
+#ifndef _MD_H
+#define _MD_H
+
+#include <linux/mm.h>
+#include <linux/fs.h>
+#include <linux/blkdev.h>
+#include <asm/semaphore.h>
+#include <linux/major.h>
+#include <linux/ioctl.h>
+#include <linux/types.h>
+#include <asm/bitops.h>
+#include <linux/module.h>
+#include <linux/mm.h>
+#include <linux/hdreg.h>
+#include <linux/fs.h>
+#include <linux/proc_fs.h>
+#include <linux/smp_lock.h>
+#include <linux/delay.h>
+#include <net/checksum.h>
+#include <linux/random.h>
+#include <asm/io.h>
+
+#include <linux/raid/md_compatible.h>
+/*
+ * 'md_p.h' holds the 'physical' layout of RAID devices
+ * 'md_u.h' holds the user <=> kernel API
+ *
+ * 'md_k.h' holds kernel internal definitions
+ */
+
+#include <linux/raid/md_p.h>
+#include <linux/raid/md_u.h>
+#include <linux/raid/md_k.h>
+
+/*
+ * Different major versions are not compatible.
+ * Different minor versions are only downward compatible.
+ * Different patchlevel versions are downward and upward compatible.
+ */
+#define MD_MAJOR_VERSION                0
+#define MD_MINOR_VERSION                90
+#define MD_PATCHLEVEL_VERSION           0
+
+extern mddev_t md_arrays[MAX_MD_DEV];
+extern int md_size[MAX_MD_DEV];
+
+extern char * partition_name (kdev_t dev);
+
+extern int register_md_personality (int p_num, mdk_personality_t *p);
+extern int unregister_md_personality (int p_num);
+extern mdk_thread_t * md_register_thread (void (*run) (void *data),
+				void *data, const char * name);
+extern void md_unregister_thread (mdk_thread_t *thread);
+extern void md_wakeup_thread(mdk_thread_t *thread);
+extern void md_interrupt_thread (mdk_thread_t *thread);
+extern int md_update_sb (mddev_t * mddev);
+extern int md_do_sync(mddev_t *mddev, mdp_disk_t *spare);
+extern void md_recover_arrays (void);
+extern int md_check_ordering (mddev_t *mddev);
+extern void autodetect_raid(void);
+extern struct gendisk * find_gendisk (kdev_t dev);
+extern int md_notify_reboot(struct notifier_block *this,
+					unsigned long code, void *x);
+#if CONFIG_BLK_DEV_MD
+extern void raid_setup(char *str,int *ints) md__init;
+#endif
+#ifdef CONFIG_MD_BOOT
+extern void md_setup(char *str,int *ints) md__init;
+#endif
+
+extern void md_print_devices (void);
+
+#define MD_BUG(x...) { printk("md: bug in file %s, line %d\n", __FILE__, __LINE__); md_print_devices(); }
+
+#endif _MD_H
+
--- linux/include/linux/raid/md_k.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/md_k.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,290 @@
+/*
+   md_k.h : kernel internal structure of the Linux MD driver
+          Copyright (C) 1996-98 Ingo Molnar, Gadi Oxman
+	  
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+   
+   You should have received a copy of the GNU General Public License
+   (for example /usr/src/linux/COPYING); if not, write to the Free
+   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
+*/
+
+#ifndef _MD_K_H
+#define _MD_K_H
+
+#define MD_RESERVED       0UL
+#define LINEAR            1UL
+#define STRIPED           2UL
+#define RAID0             STRIPED
+#define RAID1             3UL
+#define RAID5             4UL
+#define MAX_PERSONALITY   5UL
+
+static inline int pers_to_level (int pers)
+{
+	switch (pers) {
+		case LINEAR:	return -1;
+		case RAID0:	return 0;
+		case RAID1:	return 1;
+		case RAID5:	return 5;
+	}
+	return -2;
+}
+
+static inline int level_to_pers (int level)
+{
+	switch (level) {
+		case -1: return LINEAR;
+		case 0: return RAID0;
+		case 1: return RAID1;
+		case 4:
+		case 5: return RAID5;
+	}
+	return MD_RESERVED;
+}
+
+#define MAX_REAL     12		/* Max number of physical dev per md dev */
+#define MAX_MD_DEV   16		/* Max number of md dev */
+
+/*
+ * options passed in raidrun:
+ */
+
+#define MAX_CHUNK_SIZE (4096*1024)
+
+/*
+ * default readahead
+ */
+#define MD_READAHEAD	(256 * 1024)
+
+static inline int disk_faulty(mdp_disk_t * d)
+{
+	return d->state & (1 << MD_DISK_FAULTY);
+}
+
+static inline int disk_active(mdp_disk_t * d)
+{
+	return d->state & (1 << MD_DISK_ACTIVE);
+}
+
+static inline int disk_sync(mdp_disk_t * d)
+{
+	return d->state & (1 << MD_DISK_SYNC);
+}
+
+static inline int disk_spare(mdp_disk_t * d)
+{
+	return !disk_sync(d) && !disk_active(d) && !disk_faulty(d);
+}
+
+static inline int disk_removed(mdp_disk_t * d)
+{
+	return d->state & (1 << MD_DISK_REMOVED);
+}
+
+static inline void mark_disk_faulty(mdp_disk_t * d)
+{
+	d->state |= (1 << MD_DISK_FAULTY);
+}
+
+static inline void mark_disk_active(mdp_disk_t * d)
+{
+	d->state |= (1 << MD_DISK_ACTIVE);
+}
+
+static inline void mark_disk_sync(mdp_disk_t * d)
+{
+	d->state |= (1 << MD_DISK_SYNC);
+}
+
+static inline void mark_disk_spare(mdp_disk_t * d)
+{
+	d->state = 0;
+}
+
+static inline void mark_disk_removed(mdp_disk_t * d)
+{
+	d->state = (1 << MD_DISK_FAULTY) | (1 << MD_DISK_REMOVED);
+}
+
+static inline void mark_disk_inactive(mdp_disk_t * d)
+{
+	d->state &= ~(1 << MD_DISK_ACTIVE);
+}
+
+static inline void mark_disk_nonsync(mdp_disk_t * d)
+{
+	d->state &= ~(1 << MD_DISK_SYNC);
+}
+
+typedef struct mddev_s mddev_t;
+typedef struct mdk_rdev_s mdk_rdev_t;
+
+/*
+ * MD's 'extended' device
+ */
+struct mdk_rdev_s
+{
+	struct md_list_head same_set;	/* RAID devices within the same set */
+	struct md_list_head raid_managed;/* managed RAID devices */
+
+	kdev_t dev;			/* Device number */
+	kdev_t old_dev;			/*  "" when it was last imported */
+	int size;			/* Device size (in blocks) */
+	mddev_t *mddev;			/* RAID array if running */
+
+	struct inode *inode;		/* Lock inode */
+
+	mdp_super_t *sb;
+	int sb_offset;
+
+	int faulty;			/* if faulty do not issue IO requests */
+	int desc_nr;			/* descriptor index in the superblock */
+};
+
+
+/*
+ * disk operations in a working array:
+ */
+#define DISKOP_SPARE_INACTIVE	0
+#define DISKOP_SPARE_WRITE	1
+#define DISKOP_SPARE_ACTIVE	2
+#define DISKOP_HOT_REMOVE_DISK	3
+#define DISKOP_HOT_ADD_DISK	4
+
+typedef struct mdk_personality_s mdk_personality_t;
+
+struct mddev_s
+{
+	void				*private;
+	mdk_personality_t		*pers;
+	int				__minor;
+	mdp_super_t			*sb;
+	int				nb_dev;
+	struct md_list_head 		disks;
+	int				sb_dirty;
+	mdu_param_t			param;
+	int				busy;
+	int				ro;
+	unsigned int			curr_resync;
+	unsigned long			resync_start;
+	char				*name;
+	int				recovery_running;
+	struct semaphore		recovery_sem;
+};
+
+extern mddev_t md_arrays[MAX_MD_DEV];
+
+struct mdk_personality_s
+{
+	char *name;
+	int (*map)(mddev_t *mddev, kdev_t *rdev,
+		unsigned long *rsector, unsigned long size);
+	int (*make_request)(mddev_t *mddev, int rw, struct buffer_head * bh);
+	void (*end_request)(struct buffer_head * bh, int uptodate);
+	int (*run)(mddev_t *mddev);
+	int (*stop)(mddev_t *mddev);
+	int (*status)(char *page, mddev_t *mddev);
+	int (*ioctl)(struct inode *inode, struct file *file,
+		unsigned int cmd, unsigned long arg);
+	int max_invalid_dev;
+	int (*error_handler)(mddev_t *mddev, kdev_t dev);
+
+/*
+ * Some personalities (RAID-1, RAID-5) can have disks hot-added and
+ * hot-removed. Hot removal is different from failure. (failure marks
+ * a disk inactive, but the disk is still part of the array) The interface
+ * to such operations is the 'pers->diskop()' function, can be NULL.
+ *
+ * the diskop function can change the pointer pointing to the incoming
+ * descriptor, but must do so very carefully. (currently only
+ * SPARE_ACTIVE expects such a change)
+ */
+	int (*diskop) (mddev_t *mddev, mdp_disk_t **descriptor, int state);
+
+	int (*stop_resync)(mddev_t *mddev);
+	int (*restart_resync)(mddev_t *mddev);
+};
+
+
+/*
+ * Currently we index md_array directly, based on the minor
+ * number. This will have to change to dynamic allocation
+ * once we start supporting partitioning of md devices.
+ */
+extern inline int mdidx (mddev_t * mddev)
+{
+	return mddev->__minor;
+}
+
+extern inline kdev_t mddev_to_kdev(mddev_t * mddev)
+{
+	return MKDEV(MD_MAJOR, mdidx(mddev));
+}
+
+extern inline mddev_t * kdev_to_mddev(kdev_t dev)
+{
+	if (MAJOR(dev) != MD_MAJOR)
+		panic("md: cannot transform non-MD devices!");
+
+	return md_arrays + MINOR(dev);
+}
+
+extern mdk_rdev_t * find_rdev(mddev_t * mddev, kdev_t dev);
+extern mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr);
+
+/*
+ * iterates through the 'disks' ringlist, it's safe to remove the
+ * current 'rdev'. Dont touch 'tmp' though.
+ */
+#define ITERATE_RDEV(mddev,rdev,tmp)					\
+									\
+	for (tmp = mddev->disks.next;					\
+		rdev = md_list_entry(tmp, mdk_rdev_t, same_set),	\
+			tmp = tmp->next, tmp->prev != &mddev->disks	\
+		; )
+
+/*
+ * Same as above, but assumes that the device has rdev->desc_nr numbered
+ * from 0 to mddev->nb_dev, and iterates through rdevs in ascending order.
+ */
+#define ITERATE_RDEV_ORDERED(mddev,rdev,i)				\
+	for (i = 0; rdev = find_rdev_nr(mddev, i), i < mddev->nb_dev; i++)
+
+
+/*
+ * Iterates through the 'managed disks' ringlist
+ */
+#define ITERATE_RDEV_MANAGED(rdev,tmp)					\
+									\
+	for (tmp = raid_managed_devices.next;				\
+		rdev = md_list_entry(tmp, mdk_rdev_t, raid_managed),	\
+		tmp = tmp->next, tmp->prev != &raid_managed_devices	\
+	; )
+
+#define xchg_values(x,y) do { __typeof__(x) __tmp = x; \
+				x = y; y = __tmp; } while (0)
+
+typedef struct mdk_thread_s {
+	void			(*run) (void *data);
+	void			*data;
+	struct wait_queue	*wqueue;
+	unsigned long           flags;
+	struct semaphore	*sem;
+	struct task_struct	*tsk;
+	const char		*name;
+} mdk_thread_t;
+
+#define THREAD_WAKEUP  0
+
+typedef struct dev_name_s {
+	struct md_list_head list;
+	kdev_t dev;
+	char name [MAX_DISKNAME_LEN];
+} dev_name_t;
+
+#endif _MD_K_H
+
--- linux/include/linux/raid/md_p.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/md_p.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,158 @@
+/*
+   md_p.h : physical layout of Linux RAID devices
+          Copyright (C) 1996-98 Ingo Molnar, Gadi Oxman
+	  
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+   
+   You should have received a copy of the GNU General Public License
+   (for example /usr/src/linux/COPYING); if not, write to the Free
+   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
+*/
+
+#ifndef _MD_P_H
+#define _MD_P_H
+
+/*
+ * RAID superblock.
+ *
+ * The RAID superblock maintains some statistics on each RAID configuration.
+ * Each real device in the RAID set contains it near the end of the device.
+ * Some of the ideas are copied from the ext2fs implementation.
+ *
+ * We currently use 4096 bytes as follows:
+ *
+ *	word offset	function
+ *
+ *	   0  -    31	Constant generic RAID device information.
+ *        32  -    63   Generic state information.
+ *	  64  -   127	Personality specific information.
+ *	 128  -   511	12 32-words descriptors of the disks in the raid set.
+ *	 512  -   911	Reserved.
+ *	 912  -  1023	Disk specific descriptor.
+ */
+
+/*
+ * If x is the real device size in bytes, we return an apparent size of:
+ *
+ *	y = (x & ~(MD_RESERVED_BYTES - 1)) - MD_RESERVED_BYTES
+ *
+ * and place the 4kB superblock at offset y.
+ */
+#define MD_RESERVED_BYTES		(64 * 1024)
+#define MD_RESERVED_SECTORS		(MD_RESERVED_BYTES / 512)
+#define MD_RESERVED_BLOCKS		(MD_RESERVED_BYTES / BLOCK_SIZE)
+
+#define MD_NEW_SIZE_SECTORS(x)		((x & ~(MD_RESERVED_SECTORS - 1)) - MD_RESERVED_SECTORS)
+#define MD_NEW_SIZE_BLOCKS(x)		((x & ~(MD_RESERVED_BLOCKS - 1)) - MD_RESERVED_BLOCKS)
+
+#define MD_SB_BYTES			4096
+#define MD_SB_WORDS			(MD_SB_BYTES / 4)
+#define MD_SB_BLOCKS			(MD_SB_BYTES / BLOCK_SIZE)
+#define MD_SB_SECTORS			(MD_SB_BYTES / 512)
+
+/*
+ * The following are counted in 32-bit words
+ */
+#define	MD_SB_GENERIC_OFFSET		0
+#define MD_SB_PERSONALITY_OFFSET	64
+#define MD_SB_DISKS_OFFSET		128
+#define MD_SB_DESCRIPTOR_OFFSET		992
+
+#define MD_SB_GENERIC_CONSTANT_WORDS	32
+#define MD_SB_GENERIC_STATE_WORDS	32
+#define MD_SB_GENERIC_WORDS		(MD_SB_GENERIC_CONSTANT_WORDS + MD_SB_GENERIC_STATE_WORDS)
+#define MD_SB_PERSONALITY_WORDS		64
+#define MD_SB_DISKS_WORDS		384
+#define MD_SB_DESCRIPTOR_WORDS		32
+#define MD_SB_RESERVED_WORDS		(1024 - MD_SB_GENERIC_WORDS - MD_SB_PERSONALITY_WORDS - MD_SB_DISKS_WORDS - MD_SB_DESCRIPTOR_WORDS)
+#define MD_SB_EQUAL_WORDS		(MD_SB_GENERIC_WORDS + MD_SB_PERSONALITY_WORDS + MD_SB_DISKS_WORDS)
+#define MD_SB_DISKS			(MD_SB_DISKS_WORDS / MD_SB_DESCRIPTOR_WORDS)
+
+/*
+ * Device "operational" state bits
+ */
+#define MD_DISK_FAULTY		0 /* disk is faulty / operational */
+#define MD_DISK_ACTIVE		1 /* disk is running or spare disk */
+#define MD_DISK_SYNC		2 /* disk is in sync with the raid set */
+#define MD_DISK_REMOVED		3 /* disk is in sync with the raid set */
+
+typedef struct mdp_device_descriptor_s {
+	__u32 number;		/* 0 Device number in the entire set	      */
+	__u32 major;		/* 1 Device major number		      */
+	__u32 minor;		/* 2 Device minor number		      */
+	__u32 raid_disk;	/* 3 The role of the device in the raid set   */
+	__u32 state;		/* 4 Operational state			      */
+	__u32 reserved[MD_SB_DESCRIPTOR_WORDS - 5];
+} mdp_disk_t;
+
+#define MD_SB_MAGIC		0xa92b4efc
+
+/*
+ * Superblock state bits
+ */
+#define MD_SB_CLEAN		0
+#define MD_SB_ERRORS		1
+
+typedef struct mdp_superblock_s {
+	/*
+	 * Constant generic information
+	 */
+	__u32 md_magic;		/*  0 MD identifier 			      */
+	__u32 major_version;	/*  1 major version to which the set conforms */
+	__u32 minor_version;	/*  2 minor version ...			      */
+	__u32 patch_version;	/*  3 patchlevel version ...		      */
+	__u32 gvalid_words;	/*  4 Number of used words in this section    */
+	__u32 set_uuid0;	/*  5 Raid set identifier		      */
+	__u32 ctime;		/*  6 Creation time			      */
+	__u32 level;		/*  7 Raid personality			      */
+	__u32 size;		/*  8 Apparent size of each individual disk   */
+	__u32 nr_disks;		/*  9 total disks in the raid set	      */
+	__u32 raid_disks;	/* 10 disks in a fully functional raid set    */
+	__u32 md_minor;		/* 11 preferred MD minor device number	      */
+	__u32 not_persistent;	/* 12 does it have a persistent superblock    */
+	__u32 set_uuid1;	/* 13 Raid set identifier #2		      */
+	__u32 set_uuid2;	/* 14 Raid set identifier #3		      */
+	__u32 set_uuid3;	/* 14 Raid set identifier #4		      */
+	__u32 gstate_creserved[MD_SB_GENERIC_CONSTANT_WORDS - 16];
+
+	/*
+	 * Generic state information
+	 */
+	__u32 utime;		/*  0 Superblock update time		      */
+	__u32 state;		/*  1 State bits (clean, ...)		      */
+	__u32 active_disks;	/*  2 Number of currently active disks	      */
+	__u32 working_disks;	/*  3 Number of working disks		      */
+	__u32 failed_disks;	/*  4 Number of failed disks		      */
+	__u32 spare_disks;	/*  5 Number of spare disks		      */
+	__u32 sb_csum;		/*  6 checksum of the whole superblock        */
+	__u32 gstate_sreserved[MD_SB_GENERIC_STATE_WORDS - 7];
+
+	/*
+	 * Personality information
+	 */
+	__u32 layout;		/*  0 the array's physical layout	      */
+	__u32 chunk_size;	/*  1 chunk size in bytes		      */
+	__u32 pstate_reserved[MD_SB_PERSONALITY_WORDS - 2];
+
+	/*
+	 * Disks information
+	 */
+	mdp_disk_t disks[MD_SB_DISKS];
+
+	/*
+	 * Reserved
+	 */
+	__u32 reserved[MD_SB_RESERVED_WORDS];
+
+	/*
+	 * Active descriptor
+	 */
+	mdp_disk_t this_disk;
+
+} mdp_super_t;
+
+#endif _MD_P_H
+
--- linux/include/linux/raid/md_u.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/md_u.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,113 @@
+/*
+   md_u.h : user <=> kernel API between Linux raidtools and RAID drivers
+          Copyright (C) 1998 Ingo Molnar
+	  
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+   
+   You should have received a copy of the GNU General Public License
+   (for example /usr/src/linux/COPYING); if not, write to the Free
+   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
+*/
+
+#ifndef _MD_U_H
+#define _MD_U_H
+
+/* ioctls */
+
+/* status */
+#define RAID_VERSION		_IOR (MD_MAJOR, 0x10, mdu_version_t)
+#define GET_ARRAY_INFO		_IOR (MD_MAJOR, 0x11, mdu_array_info_t)
+#define GET_DISK_INFO		_IOR (MD_MAJOR, 0x12, mdu_disk_info_t)
+
+/* configuration */
+#define CLEAR_ARRAY		_IO (MD_MAJOR, 0x20)
+#define ADD_NEW_DISK		_IOW (MD_MAJOR, 0x21, mdu_disk_info_t)
+#define HOT_REMOVE_DISK		_IO (MD_MAJOR, 0x22)
+#define SET_ARRAY_INFO		_IOW (MD_MAJOR, 0x23, mdu_array_info_t)
+#define SET_DISK_INFO		_IO (MD_MAJOR, 0x24)
+#define WRITE_RAID_INFO		_IO (MD_MAJOR, 0x25)
+#define UNPROTECT_ARRAY		_IO (MD_MAJOR, 0x26)
+#define PROTECT_ARRAY		_IO (MD_MAJOR, 0x27)
+#define HOT_ADD_DISK		_IO (MD_MAJOR, 0x28)
+
+/* usage */
+#define RUN_ARRAY		_IOW (MD_MAJOR, 0x30, mdu_param_t)
+#define START_ARRAY		_IO (MD_MAJOR, 0x31)
+#define STOP_ARRAY		_IO (MD_MAJOR, 0x32)
+#define STOP_ARRAY_RO		_IO (MD_MAJOR, 0x33)
+#define RESTART_ARRAY_RW	_IO (MD_MAJOR, 0x34)
+
+typedef struct mdu_version_s {
+	int major;
+	int minor;
+	int patchlevel;
+} mdu_version_t;
+
+typedef struct mdu_array_info_s {
+	/*
+	 * Generic constant information
+	 */
+	int major_version;
+	int minor_version;
+	int patch_version;
+	int ctime;
+	int level;
+	int size;
+	int nr_disks;
+	int raid_disks;
+	int md_minor;
+	int not_persistent;
+
+	/*
+	 * Generic state information
+	 */
+	int utime;		/*  0 Superblock update time		      */
+	int state;		/*  1 State bits (clean, ...)		      */
+	int active_disks;	/*  2 Number of currently active disks	      */
+	int working_disks;	/*  3 Number of working disks		      */
+	int failed_disks;	/*  4 Number of failed disks		      */
+	int spare_disks;	/*  5 Number of spare disks		      */
+
+	/*
+	 * Personality information
+	 */
+	int layout;		/*  0 the array's physical layout	      */
+	int chunk_size;	/*  1 chunk size in bytes		      */
+
+} mdu_array_info_t;
+
+typedef struct mdu_disk_info_s {
+	/*
+	 * configuration/status of one particular disk
+	 */
+	int number;
+	int major;
+	int minor;
+	int raid_disk;
+	int state;
+
+} mdu_disk_info_t;
+
+typedef struct mdu_start_info_s {
+	/*
+	 * configuration/status of one particular disk
+	 */
+	int major;
+	int minor;
+	int raid_disk;
+	int state;
+
+} mdu_start_info_t;
+
+typedef struct mdu_param_s
+{
+	int			personality;	/* 1,2,3,4 */
+	int			chunk_size;	/* in bytes */
+	int			max_fault;	/* unused for now */
+} mdu_param_t;
+
+#endif _MD_U_H
+
--- linux/include/linux/raid/raid0.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/raid0.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,33 @@
+#ifndef _RAID0_H
+#define _RAID0_H
+
+#include <linux/raid/md.h>
+
+struct strip_zone
+{
+	int zone_offset;		/* Zone offset in md_dev */
+	int dev_offset;			/* Zone offset in real dev */
+	int size;			/* Zone size */
+	int nb_dev;			/* # of devices attached to the zone */
+	mdk_rdev_t *dev[MAX_REAL]; /* Devices attached to the zone */
+};
+
+struct raid0_hash
+{
+	struct strip_zone *zone0, *zone1;
+};
+
+struct raid0_private_data
+{
+	struct raid0_hash *hash_table; /* Dynamically allocated */
+	struct strip_zone *strip_zone; /* This one too */
+	int nr_strip_zones;
+	struct strip_zone *smallest;
+	int nr_zones;
+};
+
+typedef struct raid0_private_data raid0_conf_t;
+
+#define mddev_to_conf(mddev) ((raid0_conf_t *) mddev->private)
+
+#endif
--- linux/include/linux/raid/raid1.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/raid1.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,62 @@
+#ifndef _RAID1_H
+#define _RAID1_H
+
+#include <linux/raid/md.h>
+
+struct mirror_info {
+	int		number;
+	int		raid_disk;
+	kdev_t		dev;
+	int		next;
+	int		sect_limit;
+
+	/*
+	 * State bits:
+	 */
+	int		operational;
+	int		write_only;
+	int		spare;
+
+	int		used_slot;
+};
+
+struct raid1_private_data {
+	mddev_t			*mddev;
+	struct mirror_info	mirrors[MD_SB_DISKS];
+	int			nr_disks;
+	int			raid_disks;
+	int			working_disks;
+	int			last_used;
+	unsigned long		next_sect;
+	int			sect_count;
+	mdk_thread_t		*thread, *resync_thread;
+	int			resync_mirrors;
+	struct mirror_info	*spare;
+};
+
+typedef struct raid1_private_data raid1_conf_t;
+
+/*
+ * this is the only point in the RAID code where we violate
+ * C type safety. mddev->private is an 'opaque' pointer.
+ */
+#define mddev_to_conf(mddev) ((raid1_conf_t *) mddev->private)
+
+/*
+ * this is our 'private' 'collective' RAID1 buffer head.
+ * it contains information about what kind of IO operations were started
+ * for this RAID1 operation, and about their status:
+ */
+
+struct raid1_bh {
+	unsigned int		remaining;
+	int			cmd;
+	unsigned long		state;
+	mddev_t			*mddev;
+	struct buffer_head	*master_bh;
+	struct buffer_head	*mirror_bh [MD_SB_DISKS];
+	struct buffer_head	bh_req;
+	struct buffer_head	*next_retry;
+};
+
+#endif
--- linux/include/linux/raid/raid5.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/raid5.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,112 @@
+#ifndef _RAID5_H
+#define _RAID5_H
+
+#include <linux/raid/md.h>
+#include <linux/raid/xor.h>
+
+struct disk_info {
+	kdev_t	dev;
+	int	operational;
+	int	number;
+	int	raid_disk;
+	int	write_only;
+	int	spare;
+	int	used_slot;
+};
+
+struct stripe_head {
+	struct stripe_head	*hash_next, **hash_pprev; /* hash pointers */
+	struct stripe_head	*free_next;		/* pool of free sh's */
+	struct buffer_head	*buffer_pool;		/* pool of free buffers */
+	struct buffer_head	*bh_pool;		/* pool of free bh's */
+	struct raid5_private_data	*raid_conf;
+	struct buffer_head	*bh_old[MD_SB_DISKS];	/* disk image */
+	struct buffer_head	*bh_new[MD_SB_DISKS];	/* buffers of the MD device (present in buffer cache) */
+	struct buffer_head	*bh_copy[MD_SB_DISKS];	/* copy on write of bh_new (bh_new can change from under us) */
+	struct buffer_head	*bh_req[MD_SB_DISKS];	/* copy of bh_new (only the buffer heads), queued to the lower levels */
+	int			cmd_new[MD_SB_DISKS];	/* READ/WRITE for new */
+	int			new[MD_SB_DISKS];	/* buffer added since the last handle_stripe() */
+	unsigned long		sector;			/* sector of this row */
+	int			size;			/* buffers size */
+	int			pd_idx;			/* parity disk index */
+	int			nr_pending;		/* nr of pending cmds */
+	unsigned long		state;			/* state flags */
+	int			cmd;			/* stripe cmd */
+	int			count;			/* nr of waiters */
+	int			write_method;		/* reconstruct-write / read-modify-write */
+	int			phase;			/* PHASE_BEGIN, ..., PHASE_COMPLETE */
+	struct wait_queue	*wait;			/* processes waiting for this stripe */
+};
+
+/*
+ * Phase
+ */
+#define PHASE_BEGIN		0
+#define PHASE_READ_OLD		1
+#define PHASE_WRITE		2
+#define PHASE_READ		3
+#define PHASE_COMPLETE		4
+
+/*
+ * Write method
+ */
+#define METHOD_NONE		0
+#define RECONSTRUCT_WRITE	1
+#define READ_MODIFY_WRITE	2
+
+/*
+ * Stripe state
+ */
+#define STRIPE_LOCKED		0
+#define STRIPE_ERROR		1
+
+/*
+ * Stripe commands
+ */
+#define STRIPE_NONE		0
+#define	STRIPE_WRITE		1
+#define STRIPE_READ		2
+
+struct raid5_private_data {
+	struct stripe_head	**stripe_hashtbl;
+	mddev_t			*mddev;
+	mdk_thread_t		*thread, *resync_thread;
+	struct disk_info	disks[MD_SB_DISKS];
+	struct disk_info	*spare;
+	int			buffer_size;
+	int			chunk_size, level, algorithm;
+	int			raid_disks, working_disks, failed_disks;
+	int			sector_count;
+	unsigned long		next_sector;
+	atomic_t		nr_handle;
+	struct stripe_head	*next_free_stripe;
+	int			nr_stripes;
+	int			resync_parity;
+	int			max_nr_stripes;
+	int			clock;
+	int			nr_hashed_stripes;
+	int			nr_locked_stripes;
+	int			nr_pending_stripes;
+	int			nr_cached_stripes;
+
+	/*
+	 * Free stripes pool
+	 */
+	int			nr_free_sh;
+	struct stripe_head	*free_sh_list;
+	struct wait_queue	*wait_for_stripe;
+};
+
+typedef struct raid5_private_data raid5_conf_t;
+
+#define mddev_to_conf(mddev) ((raid5_conf_t *) mddev->private)
+
+/*
+ * Our supported algorithms
+ */
+#define ALGORITHM_LEFT_ASYMMETRIC	0
+#define ALGORITHM_RIGHT_ASYMMETRIC	1
+#define ALGORITHM_LEFT_SYMMETRIC	2
+#define ALGORITHM_RIGHT_SYMMETRIC	3
+
+#endif
--- linux/include/linux/raid/md_compatible.h.orig	Sat Sep  5 20:15:55 1998
+++ linux/include/linux/raid/md_compatible.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,342 @@
+
+/*
+   md.h : Multiple Devices driver compatibility layer for Linux 2.0/2.2
+          Copyright (C) 1998 Ingo Molnar
+	  
+   This program is free software; you can redistribute it and/or modify
+   it under the terms of the GNU General Public License as published by
+   the Free Software Foundation; either version 2, or (at your option)
+   any later version.
+   
+   You should have received a copy of the GNU General Public License
+   (for example /usr/src/linux/COPYING); if not, write to the Free
+   Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
+*/
+
+#include <linux/version.h>
+
+#ifndef _MD_COMPATIBLE_H
+#define _MD_COMPATIBLE_H
+
+#define LinuxVersionCode(v, p, s) (((v)<<16)+((p)<<8)+(s))
+
+#if LINUX_VERSION_CODE < LinuxVersionCode(2,1,0)
+
+/* 000 */
+#define md__get_free_pages(x,y) __get_free_pages(x,y,GFP_KERNEL)
+
+#ifdef __i386__
+/* 001 */
+extern __inline__ int md_cpu_has_mmx(void)
+{
+	return x86_capability & 0x00800000;
+}
+#endif
+
+/* 002 */
+#define md_clear_page(page)        memset((void *)(page), 0, PAGE_SIZE)
+
+/* 003 */
+/*
+ * FIXME: someone please suggest a sane compatibility layer for modules
+ */
+#define MD_EXPORT_SYMBOL(x)
+
+/* 004 */
+static inline unsigned long
+md_copy_from_user(void *to, const void *from, unsigned long n)
+{
+	int err;
+
+	err = verify_area(VERIFY_READ,from,n);
+	if (!err)
+		memcpy_fromfs(to, from, n);
+	return err; 
+}
+
+/* 005 */
+extern inline unsigned long
+md_copy_to_user(void *to, const void *from, unsigned long n)
+{
+	int err;
+
+	err = verify_area(VERIFY_WRITE,to,n);
+	if (!err)
+		memcpy_tofs(to, from, n);
+	return err; 
+}
+
+/* 006 */
+#define md_put_user(x,ptr)						\
+({									\
+	int __err;							\
+									\
+	__err = verify_area(VERIFY_WRITE,ptr,sizeof(*ptr));		\
+	if (!__err)							\
+		put_user(x,ptr);					\
+	__err;								\
+})
+
+/* 007 */
+extern inline int md_capable_admin(void)
+{
+	return suser();
+}
+ 
+/* 008 */
+#define MD_FILE_TO_INODE(file) ((file)->f_inode)
+
+/* 009 */
+extern inline void md_flush_signals (void)
+{
+	current->signal = 0;
+}
+ 
+/* 010 */
+#define __S(nr) (1<<((nr)-1))
+extern inline void md_init_signals (void)
+{
+        current->exit_signal = SIGCHLD;
+        current->blocked = ~(__S(SIGKILL) | __S(SIGINT) | __S(SIGTERM));
+}
+#undef __S
+
+/* 011 */
+extern inline unsigned long md_signal_pending (struct task_struct * tsk)
+{
+	return (tsk->signal & ~tsk->blocked);
+}
+
+/* 012 */
+#define md_set_global_readahead(x) read_ahead[MD_MAJOR] = MD_READAHEAD
+
+/* 013 */
+#define md_mdelay(n) (\
+	{unsigned long msec=(n); while (msec--) udelay(1000);})
+
+/* 014 */
+#define MD_SYS_DOWN 0
+#define MD_SYS_HALT 0
+
+/* 015 */
+#define md_register_reboot_notifier(x)
+
+/* 016 */
+extern __inline__ unsigned long
+md_test_and_set_bit(int nr, void * addr)
+{
+	unsigned long flags;
+	unsigned long oldbit;
+
+	save_flags(flags);
+	cli();
+	oldbit = test_bit(nr,addr);
+	set_bit(nr,addr);
+	restore_flags(flags);
+	return oldbit;
+}
+
+/* 017 */
+extern __inline__ unsigned long
+md_test_and_clear_bit(int nr, void * addr)
+{
+	unsigned long flags;
+	unsigned long oldbit;
+
+	save_flags(flags);
+	cli();
+	oldbit = test_bit(nr,addr);
+	clear_bit(nr,addr);
+	restore_flags(flags);
+	return oldbit;
+}
+
+/* 018 */
+#define md_atomic_read(x) (*(volatile int *)(x))
+
+/* 019 */
+extern __inline__ void md_lock_kernel (void)
+{
+#if __SMP__
+	lock_kernel();
+	syscall_count++;
+#endif
+}
+
+/* 020 */
+
+#define md__init
+#define md__initdata
+#define md__initfunc(__arginit) __arginit
+
+/* 021 */
+
+/* FIXME: no iotrace for 2.0 yet */
+
+/* 022 */
+
+struct md_list_head {
+	struct md_list_head *next, *prev;
+};
+
+#define MD_LIST_HEAD(name) \
+	struct md_list_head name = { &name, &name }
+
+#define MD_INIT_LIST_HEAD(ptr) do { \
+	(ptr)->next = (ptr); (ptr)->prev = (ptr); \
+} while (0)
+
+static __inline__ void md__list_add(struct md_list_head * new,
+	struct md_list_head * prev,
+	struct md_list_head * next)
+{
+	next->prev = new;
+	new->next = next;
+	new->prev = prev;
+	prev->next = new;
+}
+
+static __inline__ void md_list_add(struct md_list_head *new,
+						struct md_list_head *head)
+{
+	md__list_add(new, head, head->next);
+}
+
+static __inline__ void md__list_del(struct md_list_head * prev,
+					struct md_list_head * next)
+{
+	next->prev = prev;
+	prev->next = next;
+}
+
+static __inline__ void md_list_del(struct md_list_head *entry)
+{
+	md__list_del(entry->prev, entry->next);
+}
+
+static __inline__ int md_list_empty(struct md_list_head *head)
+{
+	return head->next == head;
+}
+
+#define md_list_entry(ptr, type, member) \
+	((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
+
+
+/* END */
+
+#else
+
+#include <linux/reboot.h>
+
+/* 000 */
+#define md__get_free_pages(x,y) __get_free_pages(x,y)
+
+#ifdef __i386__
+/* 001 */
+extern __inline__ int md_cpu_has_mmx(void)
+{
+	return boot_cpu_data.x86_capability & X86_FEATURE_MMX;
+}
+#endif
+
+/* 002 */
+#define md_clear_page(page)        clear_page(page)
+
+/* 003 */
+#define MD_EXPORT_SYMBOL(x) EXPORT_SYMBOL(x)
+
+/* 004 */
+#define md_copy_to_user(x,y,z) copy_to_user(x,y,z)
+
+/* 005 */
+#define md_copy_from_user(x,y,z) copy_from_user(x,y,z)
+
+/* 006 */
+#define md_put_user put_user
+
+/* 007 */
+extern inline int md_capable_admin(void)
+{
+	return capable(CAP_SYS_ADMIN);
+}
+
+/* 008 */
+#define MD_FILE_TO_INODE(file) ((file)->f_dentry->d_inode)
+
+/* 009 */
+extern inline void md_flush_signals (void)
+{
+	spin_lock(&current->sigmask_lock);
+	flush_signals(current);
+	spin_unlock(&current->sigmask_lock);
+}
+ 
+/* 010 */
+extern inline void md_init_signals (void)
+{
+        current->exit_signal = SIGCHLD;
+        siginitsetinv(&current->blocked,
+		sigmask(SIGKILL) | sigmask(SIGINT) | sigmask(SIGTERM));
+}
+
+/* 011 */
+#define md_signal_pending signal_pending
+
+/* 012 */
+extern inline void md_set_global_readahead(int * table)
+{
+	max_readahead[MD_MAJOR] = table;
+}
+
+/* 013 */
+#define md_mdelay(x) mdelay(x)
+
+/* 014 */
+#define MD_SYS_DOWN SYS_DOWN
+#define MD_SYS_HALT SYS_HALT
+
+/* 015 */
+#define md_register_reboot_notifier register_reboot_notifier
+
+/* 016 */
+#define md_test_and_set_bit test_and_set_bit
+
+/* 017 */
+#define md_test_and_clear_bit test_and_clear_bit
+
+/* 018 */
+#define md_atomic_read atomic_read
+
+/* 019 */
+#define md_lock_kernel lock_kernel
+
+/* 020 */
+
+#include <linux/init.h>
+
+#define md__init __init
+#define md__initdata __initdata
+#define md__initfunc(__arginit) __initfunc(__arginit)
+
+/* 021 */
+
+#include <linux/io_trace.h>
+
+/* 022 */
+
+#define md_list_head list_head
+#define MD_LIST_HEAD(name) LIST_HEAD(name)
+#define MD_INIT_LIST_HEAD(ptr) INIT_LIST_HEAD(ptr)
+#define md_list_add list_add
+#define md_list_del list_del
+#define md_list_empty list_empty
+
+#define md_list_entry(ptr, type, member) list_entry(ptr, type, member)
+
+/* END */
+
+#endif
+
+#endif _MD_COMPATIBLE_H
+
--- linux/include/linux/raid/xor.h.orig	Tue Sep 22 12:59:06 1998
+++ linux/include/linux/raid/xor.h	Fri Feb  2 01:14:54 1996
@@ -0,0 +1,9 @@
+#ifndef _XOR_H
+#define _XOR_H
+
+#include <linux/raid/md.h>
+
+extern void calibrate_xor_block(void);
+extern void (*xor_block)(struct buffer_head *dest, struct buffer_head *source);
+
+#endif
--- linux/include/linux/raid0.h.orig	Tue Oct 29 14:20:35 1996
+++ linux/include/linux/raid0.h	Sat Sep  5 20:15:55 1998
@@ -1,27 +0,0 @@
-#ifndef _RAID0_H
-#define _RAID0_H
-
-struct strip_zone
-{
-  int zone_offset;		/* Zone offset in md_dev */
-  int dev_offset;		/* Zone offset in real dev */
-  int size;			/* Zone size */
-  int nb_dev;			/* Number of devices attached to the zone */
-  struct real_dev *dev[MAX_REAL]; /* Devices attached to the zone */
-};
-
-struct raid0_hash
-{
-  struct strip_zone *zone0, *zone1;
-};
-
-struct raid0_data
-{
-  struct raid0_hash *hash_table; /* Dynamically allocated */
-  struct strip_zone *strip_zone; /* This one too */
-  int nr_strip_zones;
-  struct strip_zone *smallest;
-  int nr_zones;
-};
-
-#endif
--- linux/include/linux/raid1.h.orig	Mon Aug  3 20:40:08 1998
+++ linux/include/linux/raid1.h	Sat Sep  5 20:15:55 1998
@@ -1,41 +0,0 @@
-#ifndef _RAID1_H
-#define _RAID1_H
-
-#include <linux/md.h>
-
-struct mirror_info {
-	int		number;
-	int		raid_disk;
-	kdev_t		dev;
-	int		operational;
-	int		next;
-	int		sect_limit;
-};
-
-struct raid1_data {
-	struct md_dev *mddev;
-	struct mirror_info mirrors[MD_SB_DISKS];  	/* RAID1 devices, 2 to MD_SB_DISKS */
-	int raid_disks;
-	int working_disks;			/* Number of working disks */
-	int last_used;
-	unsigned long	next_sect;
-	int		sect_count;
-};
-
-/*
- * this is our 'private' 'collective' RAID1 buffer head.
- * it contains information about what kind of IO operations were started
- * for this RAID5 operation, and about their status:
- */
-
-struct raid1_bh {
-	unsigned int remaining;
-	unsigned int state;
-	int cmd;
-	struct md_dev *mddev;                    /* we could use bh->personality? */
-	struct buffer_head *master_bh;
-	struct buffer_head *mirror_bh [MD_SB_DISKS];
-	struct buffer_head *next_retry;
-};
-
-#endif
--- linux/include/linux/raid5.h.orig	Mon Aug  3 20:40:08 1998
+++ linux/include/linux/raid5.h	Sat Sep  5 20:15:55 1998
@@ -1,34 +0,0 @@
-#ifndef _RAID5_H
-#define _RAID5_H
-
-#include <linux/md.h>
-#include <asm/atomic.h>
-
-struct disk_info {
-	kdev_t	dev;
-	int	operational;
-	int	number;
-	int	raid_disk;
-};
-
-struct raid5_data {
-	struct md_dev		*mddev;
-	struct md_thread	*thread;
-	struct disk_info	disks[MD_SB_DISKS];
-	int			buffer_size;
-	int			chunk_size, level, algorithm;
-	int			raid_disks, working_disks, failed_disks;
-	int			sector_count;
-	unsigned long		next_sector;
-	atomic_t		nr_handle;
-};
-
-/*
- * Our supported algorithms
- */
-#define ALGORITHM_LEFT_ASYMMETRIC	0
-#define ALGORITHM_RIGHT_ASYMMETRIC	1
-#define ALGORITHM_LEFT_SYMMETRIC	2
-#define ALGORITHM_RIGHT_SYMMETRIC	3
-
-#endif
--- linux/include/linux/linear.h.orig	Mon Feb 26 12:51:45 1996
+++ linux/include/linux/linear.h	Sat Sep  5 20:15:55 1998
@@ -1,34 +0,0 @@
-
-#ifndef _LINEAR_H
-#define _LINEAR_H
-
-struct linear_hash
-{
-  struct real_dev *dev0, *dev1;
-};
-
-struct linear_data
-{
-  struct linear_hash *hash_table; /* Dynamically allocated */
-  struct real_dev *smallest;
-  int nr_zones;
-};
-
-#endif
-
-#ifndef _LINEAR_H
-#define _LINEAR_H
-
-struct linear_hash
-{
-  struct real_dev *dev0, *dev1;
-};
-
-struct linear_data
-{
-  struct linear_hash *hash_table; /* Dynamically allocated */
-  struct real_dev *smallest;
-  int nr_zones;
-};
-
-#endif
--- linux/include/linux/genhd.h.orig	Mon Aug  3 20:41:26 1998
+++ linux/include/linux/genhd.h	Sun Oct  4 15:51:05 1998
@@ -10,6 +10,7 @@
  */
 
 #include <linux/config.h>
+#include <asm/unaligned.h>
 
 #define CONFIG_MSDOS_PARTITION 1
 
@@ -27,11 +28,20 @@
 #define LINUX_EXTENDED_PARTITION 0x85
 #define WIN98_EXTENDED_PARTITION 0x0f
 
+#define LINUX_SWAP_PARTITION		0x82
+#define LINUX_RAID_PARTITION		0xfd	/* autodetect RAID partition */
+#define LINUX_OLD_RAID_PARTITION	0x86
+
+#ifdef CONFIG_SOLARIS_X86_PARTITION
+#define SOLARIS_X86_PARTITION	LINUX_SWAP_PARTITION
+#endif
+
 #define DM6_PARTITION		0x54	/* has DDO: use xlated geom & offset */
 #define EZD_PARTITION		0x55	/* EZ-DRIVE:  same as DM6 (we think) */
 #define DM6_AUX1PARTITION	0x51	/* no DDO:  use xlated geom */
 #define DM6_AUX3PARTITION	0x53	/* no DDO:  use xlated geom */
 	
+
 struct partition {
 	unsigned char boot_ind;		/* 0x80 - active */
 	unsigned char head;		/* starting head */
@@ -43,13 +53,39 @@
 	unsigned char end_cyl;		/* end cylinder */
 	unsigned int start_sect;	/* starting sector counting from 0 */
 	unsigned int nr_sects;		/* nr of sectors in partition */
-};
+} __attribute__((packed));
 
 struct hd_struct {
 	long start_sect;
 	long nr_sects;
+	int type;		/* RAID or normal */
 };
 
+/*
+ * partition types Linux cares about.
+ *
+ * currently there are 'normal' and RAID types.
+ */
+
+static inline unsigned int ptype (struct partition * p)
+{
+	unsigned int raw_type = get_unaligned(&p->sys_ind);
+
+	switch (raw_type) {
+		case LINUX_OLD_RAID_PARTITION:
+			return LINUX_OLD_RAID_PARTITION;
+		case LINUX_RAID_PARTITION:
+			return LINUX_RAID_PARTITION;
+		default:
+	}
+	return 0;
+}
+
+/*
+ * the maximum length a given partition name can take (eg. "scd11")
+ */
+#define MAX_DISKNAME_LEN 32
+
 struct gendisk {
 	int major;			/* major number of driver */
 	const char *major_name;		/* name of major driver */
@@ -66,6 +102,34 @@
 	void *real_devices;		/* internal use */
 	struct gendisk *next;
 };
+
+#ifdef CONFIG_SOLARIS_X86_PARTITION
+
+#define SOLARIS_X86_NUMSLICE	8
+#define SOLARIS_X86_VTOC_SANE	(0x600DDEEEUL)
+
+struct solaris_x86_slice {
+	ushort	s_tag;			/* ID tag of partition */
+	ushort	s_flag;			/* permision flags */
+	daddr_t s_start;		/* start sector no of partition */
+	long	s_size;			/* # of blocks in partition */
+};
+
+struct solaris_x86_vtoc {
+		unsigned long v_bootinfo[3];	/* info needed by mboot (unsupported) */
+	unsigned long v_sanity;		/* to verify vtoc sanity */
+	unsigned long v_version;	/* layout version */
+	char	v_volume[8];		/* volume name */
+	ushort	v_sectorsz;		/* sector size in bytes */
+	ushort	v_nparts;		/* number of partitions */
+	unsigned long v_reserved[10];	/* free space */
+	struct solaris_x86_slice
+		v_slice[SOLARIS_X86_NUMSLICE]; /* slice headers */
+	time_t	timestamp[SOLARIS_X86_NUMSLICE]; /* timestamp (unsupported) */
+	char	v_asciilabel[128];	/* for compatibility */
+};
+
+#endif /* CONFIG_SOLARIS_X86_PARTITION */
 
 #ifdef CONFIG_BSD_DISKLABEL
 /*
--- linux/include/linux/blk.h.orig	Mon Aug  3 20:41:26 1998
+++ linux/include/linux/blk.h	Sun Oct  4 15:51:05 1998
@@ -367,6 +367,17 @@
 
 #endif /* !defined(IDE_DRIVER) */
 
+/*
+ * end_request() and friends. Must be called with the request queue spinlock
+ * acquired. All functions called within end_request() _must_be_ atomic.
+ *
+ * Several drivers define their own end_request and call end_that_request_first()
+ * and end_that_request_last() for parts of the original function. This prevents * code duplication in drivers.
+ */
+
+extern int end_that_request_first(struct request *req, int uptodate, char *name);
+extern void end_that_request_last(struct request *req);
+
 /* end_request() - SCSI devices have their own version */
 /*               - IDE drivers have their own copy too */
 
@@ -377,78 +388,34 @@
 #else
 
 #ifdef IDE_DRIVER
+#define DEVICE_NAME "ide"
 void ide_end_request(byte uptodate, ide_hwgroup_t *hwgroup) {
 	struct request *req = hwgroup->rq;
 #else
 static void end_request(int uptodate) {
 	struct request *req = CURRENT;
 #endif /* IDE_DRIVER */
-	struct buffer_head * bh;
-	int nsect;
-
-	req->errors = 0;
-	if (!uptodate) {
-		printk("end_request: I/O error, dev %s, sector %lu\n",
-			kdevname(req->rq_dev), req->sector);
-		if ((bh = req->bh) != NULL) {
-			nsect = bh->b_size >> 9;
-			req->nr_sectors--;
-			req->nr_sectors &= ~(nsect - 1);
-			req->sector += nsect;
-			req->sector &= ~(nsect - 1);
-		}
-	}
-
-	if ((bh = req->bh) != NULL) {
-		req->bh = bh->b_reqnext;
-		bh->b_reqnext = NULL;
- 
- 		/*
- 		 * This is our 'MD IO has finished' event handler.
- 		 * note that b_state should be cached in a register
- 		 * anyways, so the overhead if this checking is almost 
- 		 * zero. But anyways .. we never get OO for free :)
- 		 */
- 		if (test_bit(BH_MD, &bh->b_state)) {
- 			struct md_personality * pers=(struct md_personality *)bh->personality;
- 			pers->end_request(bh,uptodate);
- 		}
- 		/*
- 		 * the normal (nonmirrored and no RAID5) case:
- 		 */
- 		else {
- 			mark_buffer_uptodate(bh, uptodate);
- 			unlock_buffer(bh);
- 		}
-		if ((bh = req->bh) != NULL) {
-			req->current_nr_sectors = bh->b_size >> 9;
-			if (req->nr_sectors < req->current_nr_sectors) {
-				req->nr_sectors = req->current_nr_sectors;
-				printk("end_request: buffer-list destroyed\n");
-			}
-			req->buffer = bh->b_data;
+		if (end_that_request_first(req, uptodate, DEVICE_NAME))
 			return;
-		}
+	#ifndef DEVICE_NO_RANDOM
+		add_blkdev_randomness(MAJOR(req->rq_dev));
+	#endif
+
+	#ifdef IDE_DRIVER
+		blk_dev[MAJOR(req->rq_dev)].current_request = req->next;
+		hwgroup->rq = NULL;
+	#else
+		DEVICE_OFF(req->rq_dev);
+		CURRENT = req->next;
+	#endif /* IDE_DRIVER */
+		end_that_request_last(req);
 	}
-#ifndef DEVICE_NO_RANDOM
-	add_blkdev_randomness(MAJOR(req->rq_dev));
-#endif
-#ifdef IDE_DRIVER
-	blk_dev[MAJOR(req->rq_dev)].current_request = req->next;
-	hwgroup->rq = NULL;
-#else
-	DEVICE_OFF(req->rq_dev);
-	CURRENT = req->next;
-#endif /* IDE_DRIVER */
-	if (req->sem != NULL)
-		up(req->sem);
-	req->rq_status = RQ_INACTIVE;
-	wake_up(&wait_for_request);
-}
-#endif /* defined(IDE_DRIVER) && !defined(_IDE_C) */
-#endif /* ! SCSI_BLK_MAJOR(MAJOR_NR) */
-#endif /* (MAJOR_NR != SCSI_TAPE_MAJOR) */
 
-#endif /* defined(MAJOR_NR) || defined(IDE_DRIVER) */
+	#endif /* defined(IDE_DRIVER) && !defined(_IDE_C) */
+
+	#endif /* ! SCSI_BLK_MAJOR(MAJOR_NR) */
+	#endif /* (MAJOR_NR != SCSI_TAPE_MAJOR) */
+
+	#endif /* defined(MAJOR_NR) || defined(IDE_DRIVER) */
 
 #endif /* _BLK_H */
--- linux/include/linux/fs.h.orig	Mon Aug  3 20:41:26 1998
+++ linux/include/linux/fs.h	Sun Oct  4 15:51:05 1998
@@ -190,14 +190,17 @@
 	struct buffer_head * b_prev_free;	/* doubly linked list of buffers */
 	struct buffer_head * b_reqnext;		/* request queue */
 
-/*
- * Some MD stuff like RAID5 needs special event handlers and
- * special private buffer_head fields:
- */
-	void * personality;
-	void * private_bh;
+	/*
+	 * I/O completion
+	 */
+	void (*b_end_io)(struct buffer_head *bh, int uptodate);
+	void *b_dev_id;
 };
 
+typedef void (bh_end_io_t)(struct buffer_head *bh, int uptodate);
+void init_buffer(struct buffer_head *bh, kdev_t dev, int block,
+			bh_end_io_t *handler, void *dev_id);
+
 static inline int buffer_uptodate(struct buffer_head * bh)
 {
 	return test_bit(BH_Uptodate, &bh->b_state);
@@ -657,10 +660,12 @@
 extern int close_fp(struct file *filp);
 extern struct buffer_head * get_hash_table(kdev_t dev, int block, int size);
 extern struct buffer_head * getblk(kdev_t dev, int block, int size);
+extern struct buffer_head * find_buffer(kdev_t dev, int block, int size);
 extern void ll_rw_block(int rw, int nr, struct buffer_head * bh[]);
 extern void ll_rw_page(int rw, kdev_t dev, unsigned long nr, char * buffer);
 extern void ll_rw_swap_file(int rw, kdev_t dev, unsigned int *b, int nb, char *buffer);
 extern int is_read_only(kdev_t dev);
+extern int is_device_idle(kdev_t);
 extern void __brelse(struct buffer_head *buf);
 extern inline void brelse(struct buffer_head *buf)
 {
@@ -677,6 +682,8 @@
 extern struct buffer_head * bread(kdev_t dev, int block, int size);
 extern struct buffer_head * breada(kdev_t dev,int block, int size, 
 				   unsigned int pos, unsigned int filesize);
+extern struct buffer_head * breada_blocks(kdev_t dev,int block,
+					int size, int blocks);
 
 extern int generic_readpage(struct inode *, struct page *);
 extern int generic_file_read(struct inode *, struct file *, char *, int);
--- linux/include/linux/locks.h.orig	Sat Sep  5 20:24:30 1998
+++ linux/include/linux/locks.h	Sun Oct  4 15:51:05 1998
@@ -32,7 +32,11 @@
 		__wait_on_buffer(bh);
 }
 
-void unlock_buffer(struct buffer_head *);
+extern inline void unlock_buffer(struct buffer_head *bh)
+{
+	clear_bit(BH_Lock, &bh->b_state);
+	wake_up(&bh->b_wait);
+}
 
 
 /*
--- linux/include/asm-i386/irq.h.orig	Mon Aug  3 20:33:08 1998
+++ linux/include/asm-i386/irq.h	Sat Sep  5 20:15:55 1998
@@ -184,7 +184,7 @@
 	"6: movl "SYMBOL_NAME_STR(smp_loops_per_tick)", %ecx\n\t" \
 	"cmpb "SYMBOL_NAME_STR(boot_cpu_id)", %al\n\t" \
 	"jne 2b\n\t" \
-	"incl "SYMBOL_NAME_STR(jiffies)"\n\t" \
+	"lock; incl "SYMBOL_NAME_STR(jiffies)"\n\t" \
 	"jmp 2b\n\t" \
 	"3: " \
 	"movb %al, "SYMBOL_NAME_STR(active_kernel_processor)"\n\t" \
--- linux/drivers/block/md.c.orig	Mon Aug  3 20:40:04 1998
+++ linux/drivers/block/md.c	Fri Feb  2 01:14:54 1996
@@ -1,17 +1,18 @@
 
 /*
    md.c : Multiple Devices driver for Linux
-          Copyright (C) 1994-96 Marc ZYNGIER
-	  <zyngier@ufr-info-p7.ibp.fr> or
-	  <maz@gloups.fdn.fr>
+          Copyright (C) 1998 Ingo Molnar
 
-   A lot of inspiration came from hd.c ...
+     completely rewritten, based on the MD driver code from Marc Zyngier
 
-   kerneld support by Boris Tobotras <boris@xtalk.msk.su>
+   Changes:
+
+   - RAID-1/RAID-5 extensions by Miguel de Icaza, Gadi Oxman, Ingo Molnar
+   - boot support for linear and striped mode by Harald Hoyer <HarryH@Royal.Net>
+   - kerneld support by Boris Tobotras <boris@xtalk.msk.su>
+   - kmod support by: Cyrus Durgin
+   - RAID0 bugfixes: Mark Anthony Lisher <markal@iname.com>
 
-   RAID-1/RAID-5 extensions by:
-        Ingo Molnar, Miguel de Icaza, Gadi Oxman
-   
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2, or (at your option)
@@ -22,26 +23,22 @@
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  
 */
 
-#include <linux/config.h>
-#include <linux/module.h>
-#include <linux/version.h>
-#include <linux/malloc.h>
-#include <linux/mm.h>
-#include <linux/md.h>
-#include <linux/hdreg.h>
-#include <linux/stat.h>
-#include <linux/fs.h>
-#include <linux/proc_fs.h>
-#include <linux/blkdev.h>
-#include <linux/genhd.h>
-#include <linux/smp_lock.h>
-#ifdef CONFIG_KERNELD
-#include <linux/kerneld.h>
-#endif
-#include <linux/errno.h>
 /*
- * For kernel_thread()
+ * Current RAID-1,4,5 parallel reconstruction 'guaranteed speed limit'
+ * is 100 KB/sec, so the extra system load does not show up that much.
+ * Increase it if you want to have more _guaranteed_ speed. Note that
+ * the RAID driver will use the maximum available bandwith if the IO
+ * subsystem is idle.
  */
+#define SPEED_LIMIT 100
+
+#include <linux/raid/md.h>
+#include <linux/raid/xor.h>
+
+#ifdef CONFIG_KMOD
+#include <linux/kmod.h>
+#endif
+
 #define __KERNEL_SYSCALLS__
 #include <linux/unistd.h>
 
@@ -49,850 +46,3393 @@
 #define MD_DRIVER
 
 #include <linux/blk.h>
-#include <asm/bitops.h>
-#include <asm/atomic.h>
 
+#ifdef CONFIG_MD_BOOT
+extern kdev_t name_to_kdev_t(char *line) md__init;
+#endif
+
+static mdk_personality_t *pers[MAX_PERSONALITY] = {NULL, };
+
+/*
+ * holds all information about one array
+ */
+mddev_t md_arrays[MAX_MD_DEV];
+
+/*
+ * these have to be allocated separately because external
+ * subsystems want to have a pre-defined structure
+ */
 static struct hd_struct md_hd_struct[MAX_MD_DEV];
 static int md_blocksizes[MAX_MD_DEV];
-static struct md_thread md_threads[MAX_MD_THREADS];
+static int md_maxreadahead[MAX_MD_DEV];
+static mdk_thread_t *md_recovery_thread = NULL;
 
-int md_size[MAX_MD_DEV]={0, };
+int md_size[MAX_MD_DEV] = {0, };
 
 static void md_geninit (struct gendisk *);
 
 static struct gendisk md_gendisk=
 {
-  MD_MAJOR,
-  "md",
-  0,
-  1,
-  MAX_MD_DEV,
-  md_geninit,
-  md_hd_struct,
-  md_size,
-  MAX_MD_DEV,
-  NULL,
-  NULL
+	MD_MAJOR,
+	"md",
+	0,
+	1,
+	MAX_MD_DEV,
+	md_geninit,
+	md_hd_struct,
+	md_size,
+	MAX_MD_DEV,
+	NULL,
+	NULL
 };
 
-static struct md_personality *pers[MAX_PERSONALITY]={NULL, };
+int md_thread(void * arg);
+
+struct gendisk * find_gendisk (kdev_t dev)
+{
+	struct gendisk *tmp = gendisk_head;
 
-struct md_dev md_dev[MAX_MD_DEV];
+	while (tmp != NULL) {
+		if (tmp->major == MAJOR(dev))
+			return (tmp);
+		tmp = tmp->next;
+	}
+	return (NULL);
+}
 
-static struct gendisk *find_gendisk (kdev_t dev)
+mdk_rdev_t * find_rdev_nr(mddev_t *mddev, int nr)
 {
-  struct gendisk *tmp=gendisk_head;
+	mdk_rdev_t * rdev;
+	struct md_list_head *tmp;
 
-  while (tmp != NULL)
-  {
-    if (tmp->major==MAJOR(dev))
-      return (tmp);
-    
-    tmp=tmp->next;
-  }
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->desc_nr == nr)
+			return rdev;
+	}
+	return NULL;
+}
+
+mdk_rdev_t * find_rdev(mddev_t * mddev, kdev_t dev)
+{
+	struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
 
-  return (NULL);
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->dev == dev)
+			return rdev;
+	}
+	return NULL;
 }
 
+static MD_LIST_HEAD(device_names);
 
-char *partition_name (kdev_t dev)
+char * partition_name (kdev_t dev)
 {
-  static char name[40];		/* This should be long
-				   enough for a device name ! */
-  struct gendisk *hd = find_gendisk (dev);
+	struct gendisk *hd;
+	static char nomem [] = "<nomem>";
+	dev_name_t *dname;
+	struct md_list_head *tmp = device_names.next;
+
+	while (tmp != &device_names) {
+		dname = md_list_entry(tmp, dev_name_t, list);
+		if (dname->dev == dev)
+			return dname->name;
+		tmp = tmp->next;
+	}
 
-  if (!hd)
-  {
-    sprintf (name, "[dev %s]", kdevname(dev));
-    return (name);
-  }
+	dname = (dev_name_t *) kmalloc(sizeof(*dname), GFP_KERNEL);
 
-  return disk_name (hd, MINOR(dev), name);  /* routine in genhd.c */
-}
+	if (!dname)
+		return nomem;
+	/*
+	 * ok, add this new device name to the list
+	 */
+	hd = find_gendisk (dev);
 
+	if (!hd)
+		sprintf (dname->name, "[dev %s]", kdevname(dev));
+	else
+		disk_name (hd, MINOR(dev), dname->name);
 
-static void set_ra (void)
-{
-  int i, j, minra=INT_MAX;
+	dname->dev = dev;
+	md_list_add(&dname->list, &device_names);
 
-  for (i=0; i<MAX_MD_DEV; i++)
-  {
-    if (!md_dev[i].pers)
-      continue;
-    
-    for (j=0; j<md_dev[i].nb_dev; j++)
-      if (read_ahead[MAJOR(md_dev[i].devices[j].dev)]<minra)
-	minra=read_ahead[MAJOR(md_dev[i].devices[j].dev)];
-  }
-  
-  read_ahead[MD_MAJOR]=minra;
+	return dname->name;
 }
 
-static int legacy_raid_sb (int minor, int pnum)
+static unsigned int calc_dev_sboffset (kdev_t dev, mddev_t *mddev,
+						int persistent)
 {
-	int i, factor;
+	unsigned int size;
 
-	factor = 1 << FACTOR_SHIFT(FACTOR((md_dev+minor)));
-
-	/*****
-	 * do size and offset calculations.
-	 */
-	for (i=0; i<md_dev[minor].nb_dev; i++) {
-		md_dev[minor].devices[i].size &= ~(factor - 1);
-		md_size[minor] += md_dev[minor].devices[i].size;
-		md_dev[minor].devices[i].offset=i ? (md_dev[minor].devices[i-1].offset + 
-							md_dev[minor].devices[i-1].size) : 0;
-	}
-	return 0;
+	size = blk_size[MAJOR(dev)][MINOR(dev)];
+	if (persistent)
+		size = MD_NEW_SIZE_BLOCKS(size);
+	return size;
 }
 
-static void free_sb (struct md_dev *mddev)
+static unsigned int calc_dev_size (kdev_t dev, mddev_t *mddev, int persistent)
 {
-	int i;
-	struct real_dev *realdev;
+	unsigned int size;
 
-	if (mddev->sb) {
-		free_page((unsigned long) mddev->sb);
-		mddev->sb = NULL;
-	}
-	for (i = 0; i <mddev->nb_dev; i++) {
-		realdev = mddev->devices + i;
-		if (realdev->sb) {
-			free_page((unsigned long) realdev->sb);
-			realdev->sb = NULL;
-		}
+	size = calc_dev_sboffset(dev, mddev, persistent);
+	if (!mddev->sb) {
+		MD_BUG();
+		return size;
 	}
+	if (mddev->sb->chunk_size)
+		size &= ~(mddev->sb->chunk_size/1024 - 1);
+	return size;
 }
 
-static int analyze_sb (int minor, int pnum)
+/*
+ * We check wether all devices are numbered from 0 to nb_dev-1. The
+ * order is guaranteed even after device name changes.
+ *
+ * Some personalities (raid0, linear) use this. Personalities that
+ * provide data have to be able to deal with loss of individual
+ * disks, so they do their checking themselves.
+ */
+int md_check_ordering (mddev_t *mddev)
 {
-	int i;
-	struct md_dev *mddev = md_dev + minor;
-	struct buffer_head *bh;
-	kdev_t dev;
-	struct real_dev *realdev;
-	u32 sb_offset, device_size;
-	md_superblock_t *sb = NULL;
+	int i, c;
+	mdk_rdev_t *rdev;
+	struct md_list_head *tmp;
 
 	/*
-	 * raid-0 and linear don't use a raid superblock
-	 */
-	if (pnum == RAID0 >> PERSONALITY_SHIFT || pnum == LINEAR >> PERSONALITY_SHIFT)
-		return legacy_raid_sb(minor, pnum);
-	
-	/*
-	 * Verify the raid superblock on each real device
+	 * First, all devices must be fully functional
 	 */
-	for (i = 0; i < mddev->nb_dev; i++) {
-		realdev = mddev->devices + i;
-		dev = realdev->dev;
-		device_size = blk_size[MAJOR(dev)][MINOR(dev)];
-		realdev->sb_offset = sb_offset = MD_NEW_SIZE_BLOCKS(device_size);
-		set_blocksize(dev, MD_SB_BYTES);
-		bh = bread(dev, sb_offset / MD_SB_BLOCKS, MD_SB_BYTES);
-		if (bh) {
-			sb = (md_superblock_t *) bh->b_data;
-			if (sb->md_magic != MD_SB_MAGIC) {
-				printk("md: %s: invalid raid superblock magic (%x) on block %u\n", kdevname(dev), sb->md_magic, sb_offset);
-				goto abort;
-			}
-			if (!mddev->sb) {
-				mddev->sb = (md_superblock_t *) __get_free_page(GFP_KERNEL);
-				if (!mddev->sb)
-					goto abort;
-				memcpy(mddev->sb, sb, MD_SB_BYTES);
-			}
-			realdev->sb = (md_superblock_t *) __get_free_page(GFP_KERNEL);
-			if (!realdev->sb)
-				goto abort;
-			memcpy(realdev->sb, bh->b_data, MD_SB_BYTES);
-
-			if (memcmp(mddev->sb, sb, MD_SB_GENERIC_CONSTANT_WORDS * 4)) {
-				printk(KERN_ERR "md: superblock inconsistenty -- run ckraid\n");
-				goto abort;
-			}
-			/*
-			 * Find the newest superblock version
-			 */
-			if (sb->utime != mddev->sb->utime) {
-				printk(KERN_ERR "md: superblock update time inconsistenty -- using the most recent one\n");
-				if (sb->utime > mddev->sb->utime)
-					memcpy(mddev->sb, sb, MD_SB_BYTES);
-			}
-			realdev->size = sb->size;
-		} else
-			printk(KERN_ERR "md: disabled device %s\n", kdevname(dev));
-	}
-	if (!mddev->sb) {
-		printk(KERN_ERR "md: couldn't access raid array %s\n", kdevname(MKDEV(MD_MAJOR, minor)));
-		goto abort;
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty) {
+			printk("md: md%d's device %s faulty, aborting.\n",
+				mdidx(mddev), partition_name(rdev->dev));
+			goto abort;
+		}
 	}
-	sb = mddev->sb;
 
-	/*
-	 * Check if we can support this raid array
-	 */
-	if (sb->major_version != MD_MAJOR_VERSION || sb->minor_version > MD_MINOR_VERSION) {
-		printk("md: %s: unsupported raid array version %d.%d.%d\n", kdevname(MKDEV(MD_MAJOR, minor)),
-		sb->major_version, sb->minor_version, sb->patch_version);
+	c = 0;
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		c++;
+	}
+	if (c != mddev->nb_dev) {
+		MD_BUG();
 		goto abort;
 	}
-	if (sb->state != (1 << MD_SB_CLEAN)) {
-		printk(KERN_ERR "md: %s: raid array is not clean -- run ckraid\n", kdevname(MKDEV(MD_MAJOR, minor)));
+	if (mddev->nb_dev != mddev->sb->raid_disks) {
+		printk("md: md%d, array needs %d disks, has %d, aborting.\n",
+			mdidx(mddev), mddev->sb->raid_disks, mddev->nb_dev);
 		goto abort;
 	}
-	switch (sb->level) {
-		case 1:
-			md_size[minor] = sb->size;
-			break;
-		case 4:
-		case 5:
-			md_size[minor] = sb->size * (sb->raid_disks - 1);
-			break;
-		default:
-			printk(KERN_ERR "md: %s: unsupported raid level %d\n", kdevname(MKDEV(MD_MAJOR, minor)), sb->level);
+	/*
+	 * Now the numbering check
+	 */
+	for (i = 0; i < mddev->nb_dev; i++) {
+		c = 0;
+		ITERATE_RDEV(mddev,rdev,tmp) {
+			if (rdev->desc_nr == i)
+				c++;
+		}
+		if (c == 0) {
+			printk("md: md%d, missing disk #%d, aborting.\n",
+				mdidx(mddev), i);
+			goto abort;
+		}
+		if (c > 1) {
+			printk("md: md%d, too many disks #%d, aborting.\n",
+				mdidx(mddev), i);
 			goto abort;
+		}
 	}
 	return 0;
 abort:
-	free_sb(mddev);
 	return 1;
 }
 
-int md_update_sb(int minor)
+static unsigned int zoned_raid_size (mddev_t *mddev)
 {
-	struct md_dev *mddev = md_dev + minor;
-	struct buffer_head *bh;
-	md_superblock_t *sb = mddev->sb;
-	struct real_dev *realdev;
-	kdev_t dev;
-	int i;
-	u32 sb_offset;
+	unsigned int mask;
+	mdk_rdev_t * rdev;
+	struct md_list_head *tmp;
 
-	sb->utime = CURRENT_TIME;
-	for (i = 0; i < mddev->nb_dev; i++) {
-		realdev = mddev->devices + i;
-		if (!realdev->sb)
-			continue;
-		dev = realdev->dev;
-		sb_offset = realdev->sb_offset;
-		set_blocksize(dev, MD_SB_BYTES);
-		printk("md: updating raid superblock on device %s, sb_offset == %u\n", kdevname(dev), sb_offset);
-		bh = getblk(dev, sb_offset / MD_SB_BLOCKS, MD_SB_BYTES);
-		if (bh) {
-			sb = (md_superblock_t *) bh->b_data;
-			memcpy(sb, mddev->sb, MD_SB_BYTES);
-			memcpy(&sb->descriptor, sb->disks + realdev->sb->descriptor.number, MD_SB_DESCRIPTOR_WORDS * 4);
-			mark_buffer_uptodate(bh, 1);
-			mark_buffer_dirty(bh, 1);
-			ll_rw_block(WRITE, 1, &bh);
-			wait_on_buffer(bh);
-			bforget(bh);
-			fsync_dev(dev);
-			invalidate_buffers(dev);
-		} else
-			printk(KERN_ERR "md: getblk failed for device %s\n", kdevname(dev));
+	if (!mddev->sb) {
+		MD_BUG();
+		return -EINVAL;
+	}
+	/*
+	 * do size and offset calculations.
+	 */
+	mask = ~(mddev->sb->chunk_size/1024 - 1);
+printk("mask %08x\n", mask);
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+printk(" rdev->size: %d\n", rdev->size);
+		rdev->size &= mask;
+printk(" masked rdev->size: %d\n", rdev->size);
+		md_size[mdidx(mddev)] += rdev->size;
+printk("  new md_size: %d\n", md_size[mdidx(mddev)]);
 	}
+	if (level_to_pers(mddev->sb->level) == RAID0)
+		md_maxreadahead[mdidx(mddev)] = MD_READAHEAD * mddev->nb_dev;
 	return 0;
 }
 
-static int do_md_run (int minor, int repart)
+static void remove_descriptor (mdp_disk_t *disk, mdp_super_t *sb)
 {
-  int pnum, i, min, factor, current_ra, err;
-
-  if (!md_dev[minor].nb_dev)
-    return -EINVAL;
-  
-  if (md_dev[minor].pers)
-    return -EBUSY;
+	if (disk_active(disk)) {
+		sb->working_disks--;
+	} else {
+		if (disk_spare(disk)) {
+			sb->spare_disks--;
+			sb->working_disks--;
+		} else	{
+			sb->failed_disks--;
+		}
+	}
+	sb->nr_disks--;
+	disk->major = 0;
+	disk->minor = 0;
+	mark_disk_removed(disk);
+}
 
-  md_dev[minor].repartition=repart;
-  
-  if ((pnum=PERSONALITY(&md_dev[minor]) >> (PERSONALITY_SHIFT))
-      >= MAX_PERSONALITY)
-    return -EINVAL;
-
-  /* Only RAID-1 and RAID-5 can have MD devices as underlying devices */
-  if (pnum != (RAID1 >> PERSONALITY_SHIFT) && pnum != (RAID5 >> PERSONALITY_SHIFT)){
-	  for (i = 0; i < md_dev [minor].nb_dev; i++)
-		  if (MAJOR (md_dev [minor].devices [i].dev) == MD_MAJOR)
-			  return -EINVAL;
-  }
-  if (!pers[pnum])
-  {
-#ifdef CONFIG_KERNELD
-    char module_name[80];
-    sprintf (module_name, "md-personality-%d", pnum);
-    request_module (module_name);
-    if (!pers[pnum])
-#endif
-      return -EINVAL;
-  }
-  
-  factor = min = 1 << FACTOR_SHIFT(FACTOR((md_dev+minor)));
-  
-  for (i=0; i<md_dev[minor].nb_dev; i++)
-    if (md_dev[minor].devices[i].size<min)
-    {
-      printk ("Dev %s smaller than %dk, cannot shrink\n",
-	      partition_name (md_dev[minor].devices[i].dev), min);
-      return -EINVAL;
-    }
-
-  for (i=0; i<md_dev[minor].nb_dev; i++) {
-    fsync_dev(md_dev[minor].devices[i].dev);
-    invalidate_buffers(md_dev[minor].devices[i].dev);
-  }
-  
-  /* Resize devices according to the factor. It is used to align
-     partitions size on a given chunk size. */
-  md_size[minor]=0;
-
-  /*
-   * Analyze the raid superblock
-   */ 
-  if (analyze_sb(minor, pnum))
-    return -EINVAL;
+#define BAD_MAGIC KERN_ERR \
+"md: invalid raid superblock magic on %s\n"
 
-  md_dev[minor].pers=pers[pnum];
-  
-  if ((err=md_dev[minor].pers->run (minor, md_dev+minor)))
-  {
-    md_dev[minor].pers=NULL;
-    free_sb(md_dev + minor);
-    return (err);
-  }
-
-  if (pnum != RAID0 >> PERSONALITY_SHIFT && pnum != LINEAR >> PERSONALITY_SHIFT)
-  {
-    md_dev[minor].sb->state &= ~(1 << MD_SB_CLEAN);
-    md_update_sb(minor);
-  }
-
-  /* FIXME : We assume here we have blocks
-     that are twice as large as sectors.
-     THIS MAY NOT BE TRUE !!! */
-  md_hd_struct[minor].start_sect=0;
-  md_hd_struct[minor].nr_sects=md_size[minor]<<1;
-  
-  /* It would be better to have a per-md-dev read_ahead. Currently,
-     we only use the smallest read_ahead among md-attached devices */
-  
-  current_ra=read_ahead[MD_MAJOR];
-  
-  for (i=0; i<md_dev[minor].nb_dev; i++)
-    if (current_ra>read_ahead[MAJOR(md_dev[minor].devices[i].dev)])
-      current_ra=read_ahead[MAJOR(md_dev[minor].devices[i].dev)];
-  
-  read_ahead[MD_MAJOR]=current_ra;
-  
-  return (0);
-}
+#define BAD_MINOR KERN_ERR \
+"md: %s: invalid raid minor (%x)\n"
 
+#define OUT_OF_MEM KERN_ALERT \
+"md: out of memory.\n"
 
-static int do_md_stop (int minor, struct inode *inode)
-{
-  int i;
-  
-  if (inode->i_count>1 || md_dev[minor].busy>1) /* ioctl : one open channel */
-  {
-    printk ("STOP_MD md%x failed : i_count=%ld, busy=%d\n", minor, inode->i_count, md_dev[minor].busy);
-    return -EBUSY;
-  }
-  
-  if (md_dev[minor].pers)
-  {
-    /*  The device won't exist anymore -> flush it now */
-    fsync_dev (inode->i_rdev);
-    invalidate_buffers (inode->i_rdev);
-    if (md_dev[minor].sb)
-    {
-      md_dev[minor].sb->state |= 1 << MD_SB_CLEAN;
-      md_update_sb(minor);
-    }
-    md_dev[minor].pers->stop (minor, md_dev+minor);
-  }
-  
-  /* Remove locks. */
-  if (md_dev[minor].sb)
-    free_sb(md_dev + minor);
-  for (i=0; i<md_dev[minor].nb_dev; i++)
-    clear_inode (md_dev[minor].devices[i].inode);
-
-  md_dev[minor].nb_dev=md_size[minor]=0;
-  md_hd_struct[minor].nr_sects=0;
-  md_dev[minor].pers=NULL;
-  
-  set_ra ();			/* calculate new read_ahead */
-  
-  return (0);
-}
+#define NO_SB KERN_ERR \
+"md: disabled device %s, could not read superblock.\n"
 
+#define BAD_CSUM KERN_WARNING \
+"md: invalid superblock checksum on %s\n"
 
-static int do_md_add (int minor, kdev_t dev)
+static int alloc_array_sb (mddev_t * mddev)
 {
-  int i;
-
-  if (md_dev[minor].nb_dev==MAX_REAL)
-    return -EINVAL;
-  
-  if (!fs_may_mount (dev) || md_dev[minor].pers)
-    return -EBUSY;
+	if (mddev->sb) {
+		MD_BUG();
+		return 0;
+	}
 
-  i=md_dev[minor].nb_dev++;
-  md_dev[minor].devices[i].dev=dev;
-  
-  /* Lock the device by inserting a dummy inode. This doesn't
-     smell very good, but I need to be consistent with the
-     mount stuff, specially with fs_may_mount. If someone have
-     a better idea, please help ! */
-  
-  md_dev[minor].devices[i].inode=get_empty_inode ();
-  md_dev[minor].devices[i].inode->i_dev=dev; /* don't care about
-						other fields */
-  insert_inode_hash (md_dev[minor].devices[i].inode);
-  
-  /* Sizes are now rounded at run time */
-  
-/*  md_dev[minor].devices[i].size=gen_real->sizes[MINOR(dev)]; HACKHACK*/
+	mddev->sb = (mdp_super_t *) __get_free_page (GFP_KERNEL);
+	if (!mddev->sb)
+		return -ENOMEM;
+	md_clear_page((unsigned long)mddev->sb);
+	return 0;
+}
 
-  if (blk_size[MAJOR(dev)][MINOR(dev)] == 0) {
-	printk("md_add(): zero device size, huh, bailing out.\n");
-  }
+static int alloc_disk_sb (mdk_rdev_t * rdev)
+{
+	if (rdev->sb)
+		MD_BUG();
 
-  md_dev[minor].devices[i].size=blk_size[MAJOR(dev)][MINOR(dev)];
+	rdev->sb = (mdp_super_t *) __get_free_page(GFP_KERNEL);
+	if (!rdev->sb) {
+		printk (OUT_OF_MEM);
+		return -EINVAL;
+	}
+	md_clear_page((unsigned long)rdev->sb);
 
-  printk ("REGISTER_DEV %s to md%x done\n", partition_name(dev), minor);
-  return (0);
+	return 0;
 }
 
-
-static int md_ioctl (struct inode *inode, struct file *file,
-                     unsigned int cmd, unsigned long arg)
+static void free_disk_sb (mdk_rdev_t * rdev)
 {
-  int minor, err;
-  struct hd_geometry *loc = (struct hd_geometry *) arg;
+	if (rdev->sb) {
+		free_page((unsigned long) rdev->sb);
+		rdev->sb = NULL;
+		rdev->sb_offset = 0;
+		rdev->size = 0;
+	} else {
+		if (!rdev->faulty)
+			MD_BUG();
+	}
+}
 
-  if (!suser())
-    return -EACCES;
+static void mark_rdev_faulty (mdk_rdev_t * rdev)
+{
+	unsigned long flags;
 
-  if (((minor=MINOR(inode->i_rdev)) & 0x80) &&
-      (minor & 0x7f) < MAX_PERSONALITY &&
-      pers[minor & 0x7f] &&
-      pers[minor & 0x7f]->ioctl)
-    return (pers[minor & 0x7f]->ioctl (inode, file, cmd, arg));
-  
-  if (minor >= MAX_MD_DEV)
-    return -EINVAL;
+	if (!rdev) {
+		MD_BUG();
+		return;
+	}
+	save_flags(flags);
+	cli();
+	free_disk_sb(rdev);
+	rdev->faulty = 1;
+	restore_flags(flags);
+}
 
-  switch (cmd)
-  {
-    case REGISTER_DEV:
-      return do_md_add (minor, to_kdev_t ((dev_t) arg));
-
-    case START_MD:
-      return do_md_run (minor, (int) arg);
-
-    case STOP_MD:
-      return do_md_stop (minor, inode);
-      
-    case BLKGETSIZE:   /* Return device size */
-    if  (!arg)  return -EINVAL;
-    err=verify_area (VERIFY_WRITE, (long *) arg, sizeof(long));
-    if (err)
-      return err;
-    put_user (md_hd_struct[MINOR(inode->i_rdev)].nr_sects, (long *) arg);
-    break;
-
-    case BLKFLSBUF:
-    fsync_dev (inode->i_rdev);
-    invalidate_buffers (inode->i_rdev);
-    break;
-
-    case BLKRASET:
-    if (arg > 0xff)
-      return -EINVAL;
-    read_ahead[MAJOR(inode->i_rdev)] = arg;
-    return 0;
-    
-    case BLKRAGET:
-    if  (!arg)  return -EINVAL;
-    err=verify_area (VERIFY_WRITE, (long *) arg, sizeof(long));
-    if (err)
-      return err;
-    put_user (read_ahead[MAJOR(inode->i_rdev)], (long *) arg);
-    break;
-
-    /* We have a problem here : there is no easy way to give a CHS
-       virtual geometry. We currently pretend that we have a 2 heads
-       4 sectors (with a BIG number of cylinders...). This drives dosfs
-       just mad... ;-) */
-    
-    case HDIO_GETGEO:
-    if (!loc)  return -EINVAL;
-    err = verify_area(VERIFY_WRITE, loc, sizeof(*loc));
-    if (err)
-      return err;
-    put_user (2, (char *) &loc->heads);
-    put_user (4, (char *) &loc->sectors);
-    put_user (md_hd_struct[minor].nr_sects/8, (short *) &loc->cylinders);
-    put_user (md_hd_struct[MINOR(inode->i_rdev)].start_sect,
-		(long *) &loc->start);
-    break;
-    
-    RO_IOCTLS(inode->i_rdev,arg);
-    
-    default:
-    printk ("Unknown md_ioctl %d\n", cmd);
-    return -EINVAL;
-  }
+static int read_disk_sb (mdk_rdev_t * rdev)
+{
+	int ret = -EINVAL;
+	struct buffer_head *bh = NULL;
+	kdev_t dev = rdev->dev;
+	mdp_super_t *sb;
+	u32 sb_offset;
 
-  return (0);
+	if (!rdev->sb) {
+		MD_BUG();
+		goto abort;
+	}	
+	
+	/*
+	 * Calculate the position of the superblock,
+	 * it's at the end of the disk
+	 */
+	sb_offset = calc_dev_sboffset(rdev->dev, rdev->mddev, 1);
+	rdev->sb_offset = sb_offset;
+	printk("(read) %s's sb offset: %d\n", partition_name(dev),
+							 sb_offset);
+	set_blocksize (dev, MD_SB_BYTES);
+	bh = bread (dev, sb_offset / MD_SB_BLOCKS, MD_SB_BYTES);
+
+	if (bh) {
+		sb = (mdp_super_t *) bh->b_data;
+		memcpy (rdev->sb, sb, MD_SB_BYTES);
+	} else {
+		printk (NO_SB,partition_name(rdev->dev));
+		goto abort;
+	}
+	ret = 0;
+abort:
+	if (bh)
+		brelse (bh);
+	return ret;
 }
 
-
-static int md_open (struct inode *inode, struct file *file)
+static unsigned int calc_sb_csum (mdp_super_t * sb)
 {
-  int minor=MINOR(inode->i_rdev);
+	unsigned int disk_csum, csum;
 
-  md_dev[minor].busy++;
-  return (0);			/* Always succeed */
+	disk_csum = sb->sb_csum;
+	sb->sb_csum = 0;
+	csum = csum_partial((void *)sb, MD_SB_BYTES, 0);
+	sb->sb_csum = disk_csum;
+	return csum;
 }
 
+/*
+ * Check one RAID superblock for generic plausibility
+ */
 
-static void md_release (struct inode *inode, struct file *file)
+static int check_disk_sb (mdk_rdev_t * rdev)
 {
-  int minor=MINOR(inode->i_rdev);
-
-  sync_dev (inode->i_rdev);
-  md_dev[minor].busy--;
-}
+	mdp_super_t *sb;
+	int ret = -EINVAL;
 
+	sb = rdev->sb;
+	if (!sb) {
+		MD_BUG();
+		goto abort;
+	}
 
-static int md_read (struct inode *inode, struct file *file,
-		    char *buf, int count)
-{
-  int minor=MINOR(inode->i_rdev);
+	if (sb->md_magic != MD_SB_MAGIC) {
+		printk (BAD_MAGIC, partition_name(rdev->dev));
+		goto abort;
+	}
 
-  if (!md_dev[minor].pers)	/* Check if device is being run */
-    return -ENXIO;
+	if (sb->md_minor >= MAX_MD_DEV) {
+		printk (BAD_MINOR, partition_name(rdev->dev),
+							sb->md_minor);
+		goto abort;
+	}
 
-  return block_read (inode, file, buf, count);
+	if (calc_sb_csum(sb) != sb->sb_csum)
+		printk(BAD_CSUM, partition_name(rdev->dev));
+	ret = 0;
+abort:
+	return ret;
 }
 
-static int md_write (struct inode *inode, struct file *file,
-		     const char *buf, int count)
+static void bind_rdev_to_array (mdk_rdev_t * rdev, mddev_t * mddev)
 {
-  int minor=MINOR(inode->i_rdev);
-
-  if (!md_dev[minor].pers)	/* Check if device is being run */
-    return -ENXIO;
-
-  return block_write (inode, file, buf, count);
+	if (rdev->mddev) {
+		MD_BUG();
+		return;
+	}
+	md_list_add(&rdev->same_set, &mddev->disks);
+	rdev->mddev = mddev;
+	mddev->nb_dev++;
+	printk("bind<%s,%d>\n", partition_name(rdev->dev), mddev->nb_dev);
 }
 
-static struct file_operations md_fops=
+static void unbind_rdev_from_array (mdk_rdev_t * rdev)
 {
-  NULL,
-  md_read,
-  md_write,
-  NULL,
-  NULL,
-  md_ioctl,
-  NULL,
-  md_open,
-  md_release,
-  block_fsync
-};
+	if (!rdev->mddev) {
+		MD_BUG();
+		return;
+	}
+	md_list_del(&rdev->same_set);
+	rdev->mddev->nb_dev--;
+	printk("unbind<%s,%d>\n", partition_name(rdev->dev),
+						 rdev->mddev->nb_dev);
+	rdev->mddev = NULL;
+}
 
-int md_map (int minor, kdev_t *rdev, unsigned long *rsector, unsigned long size)
+/*
+ * prevent the device from being mounted or otherwise reused in
+ * a RAID array (or any other kernel subsystem), but adding
+ * a dummy inode
+ */
+static void lock_rdev (mdk_rdev_t *rdev)
 {
-  if ((unsigned int) minor >= MAX_MD_DEV)
-  {
-    printk ("Bad md device %d\n", minor);
-    return (-1);
-  }
-  
-  if (!md_dev[minor].pers)
-  {
-    printk ("Oops ! md%d not running, giving up !\n", minor);
-    return (-1);
-  }
-
-  return (md_dev[minor].pers->map(md_dev+minor, rdev, rsector, size));
+	/*
+	 * Insert dummy inode to 'lock' the device
+	 */
+	rdev->inode = get_empty_inode();
+ 	/*
+	 * we dont care about other fields
+	 */
+	rdev->inode->i_dev = rdev->dev;
+	insert_inode_hash(rdev->inode);
 }
-  
-int md_make_request (int minor, int rw, struct buffer_head * bh)
+
+static void unlock_rdev (mdk_rdev_t *rdev)
 {
-	if (md_dev [minor].pers->make_request) {
-		if (buffer_locked(bh))
-			return 0;
-		if (rw == WRITE || rw == WRITEA) {
-			if (!buffer_dirty(bh))
-				return 0;
-			set_bit(BH_Lock, &bh->b_state);
-		}
-		if (rw == READ || rw == READA) {
-			if (buffer_uptodate(bh))
-				return 0;
-			set_bit (BH_Lock, &bh->b_state);
-		}
-		return (md_dev[minor].pers->make_request(md_dev+minor, rw, bh));
-	} else {
-		make_request (MAJOR(bh->b_rdev), rw, bh);
-		return 0;
-	}
+	clear_inode(rdev->inode);
 }
 
-static void do_md_request (void)
+static void export_rdev (mdk_rdev_t * rdev)
 {
-  printk ("Got md request, not good...");
-  return;
-}  
+	printk("export_rdev(%s)\n",partition_name(rdev->dev));
+	if (rdev->mddev)
+		MD_BUG();
+	unlock_rdev(rdev);
+	free_disk_sb(rdev);
+	rdev->dev = 0;
+	rdev->faulty = 0;
+	md_list_del(&rdev->raid_managed);
+	kfree(rdev);
+}
 
-/*
- * We run MAX_MD_THREADS from md_init() and arbitrate them in run time.
- * This is not so elegant, but how can we use kernel_thread() from within
- * loadable modules?
- */
-struct md_thread *md_register_thread (void (*run) (void *), void *data)
+static void export_array (mddev_t *mddev)
 {
-	int i;
-	for (i = 0; i < MAX_MD_THREADS; i++) {
-		if (md_threads[i].run == NULL) {
-			md_threads[i].run = run;
-			md_threads[i].data = data;
-			return md_threads + i;
+	struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
+	mdp_super_t *sb = mddev->sb;
+
+	if (mddev->sb) {
+		mddev->sb = NULL;
+		free_page((unsigned long) sb);
+	}
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (!rdev->mddev) {
+			MD_BUG();
+			continue;
 		}
+		unbind_rdev_from_array(rdev);
+		export_rdev(rdev);
 	}
-	return NULL;
+	if (mddev->nb_dev)
+		MD_BUG();
 }
 
+#undef BAD_CSUM
+#undef BAD_MAGIC
+#undef OUT_OF_MEM
+#undef NO_SB
 
-void md_unregister_thread (struct md_thread *thread)
+static void print_desc(mdp_disk_t *desc)
 {
-	thread->run = NULL;
-	thread->data = NULL;
-	thread->flags = 0;
+	printk(" DISK<N:%d,%s(%d,%d),R:%d,S:%d>\n", desc->number,
+		partition_name(MKDEV(desc->major,desc->minor)),
+		desc->major,desc->minor,desc->raid_disk,desc->state);
 }
 
-void md_wakeup_thread(struct md_thread *thread)
+static void print_sb(mdp_super_t *sb)
 {
-	set_bit(THREAD_WAKEUP, &thread->flags);
-	wake_up(&thread->wqueue);
+	int i;
+
+	printk("  SB: (V:%d.%d.%d) ID:<%08x.%08x.%08x.%08x> CT:%08x\n",
+		sb->major_version, sb->minor_version, sb->patch_version,
+		sb->set_uuid0, sb->set_uuid1, sb->set_uuid2, sb->set_uuid3,
+		sb->ctime);
+	printk("     L%d S%08d ND:%d RD:%d md%d LO:%d CS:%d\n", sb->level,
+		sb->size, sb->nr_disks, sb->raid_disks, sb->md_minor,
+		sb->layout, sb->chunk_size);
+	printk("     UT:%08x ST:%d AD:%d WD:%d FD:%d SD:%d CSUM:%08x\n",
+		sb->utime, sb->state, sb->active_disks, sb->working_disks,
+		sb->failed_disks, sb->spare_disks, sb->sb_csum);
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		mdp_disk_t *desc;
+
+		desc = sb->disks + i;
+		printk("     D %2d: ", i);
+		print_desc(desc);
+	}
+	printk("     THIS: ");
+	print_desc(&sb->this_disk);
+
 }
 
-struct buffer_head *efind_buffer(kdev_t dev, int block, int size);
+static void print_rdev(mdk_rdev_t *rdev)
+{
+	printk(" rdev %s: O:%s, SZ:%08d F:%d DN:%d ",
+		partition_name(rdev->dev), partition_name(rdev->old_dev),
+		rdev->size, rdev->faulty, rdev->desc_nr);
+	if (rdev->sb) {
+		printk("rdev superblock:\n");
+		print_sb(rdev->sb);
+	} else
+		printk("no rdev superblock!\n");
+}
 
-static struct symbol_table md_symbol_table=
+void md_print_devices (void)
 {
-#include <linux/symtab_begin.h>
+	mddev_t *mddev;
+	int i;
+	struct md_list_head *tmp2;
 
-  X(md_size),
-  X(register_md_personality),
-  X(unregister_md_personality),
-  X(partition_name),
-  X(md_dev),
-  X(md_error),
-  X(md_register_thread),
-  X(md_unregister_thread),
-  X(md_update_sb),
-  X(md_map),
-  X(md_wakeup_thread),
-  X(efind_buffer),
+	printk("\n");
+	printk("       **********************************\n");
+	printk("       * <COMPLETE RAID STATE PRINTOUT> *\n");
+	printk("       **********************************\n");
+	for (i = 0; i < MAX_MD_DEV; i++) {
+		mddev = md_arrays+i;
+		printk("md%d: ", i);
+		tmp2 = mddev->disks.next;
+		
+		while (tmp2 != &mddev->disks) {
+			mdk_rdev_t *rdev = md_list_entry(tmp2, mdk_rdev_t,
+								same_set);
 
-#include <linux/symtab_end.h>
-};
+			printk("<%s>", partition_name(rdev->dev));
+			tmp2 = tmp2->next;
+		}
+		if (mddev->sb) {
+			printk(" array superblock:\n");
+			print_sb(mddev->sb);
+		} else
+			printk(" no array superblock.\n");
 
-static void md_geninit (struct gendisk *gdisk)
-{
-  int i;
-  
-  for(i=0;i<MAX_MD_DEV;i++)
-  {
-    md_blocksizes[i] = 1024;
-    md_gendisk.part[i].start_sect=-1; /* avoid partition check */
-    md_gendisk.part[i].nr_sects=0;
-    md_dev[i].pers=NULL;
-  }
-
-  blksize_size[MAJOR_NR] = md_blocksizes;
-  register_symtab (&md_symbol_table);
-
-  proc_register(&proc_root,
-		&(struct proc_dir_entry)
-	      {
-		PROC_MD, 6, "mdstat",
-		S_IFREG | S_IRUGO, 1, 0, 0,
-	      });
-}
-
-int md_error (kdev_t mddev, kdev_t rdev)
-{
-    unsigned int minor = MINOR (mddev);
-    if (MAJOR(mddev) != MD_MAJOR || minor > MAX_MD_DEV)
-	panic ("md_error gets unknown device\n");
-    if (!md_dev [minor].pers)
-	panic ("md_error gets an error for an unknown device\n");
-    if (md_dev [minor].pers->error_handler)
-	return (md_dev [minor].pers->error_handler (md_dev+minor, rdev));
-    return 0;
+		tmp2 = mddev->disks.next;
+		
+		while (tmp2 != &mddev->disks) {
+			mdk_rdev_t *rdev = md_list_entry(tmp2, mdk_rdev_t,
+								same_set);
+
+			print_rdev(rdev);
+			tmp2 = tmp2->next;
+		}
+	}
+	printk("       **********************************\n");
+	printk("\n");
 }
 
-int get_md_status (char *page)
+static int sb_equal ( mdp_super_t *sb1, mdp_super_t *sb2)
 {
-  int sz=0, i, j, size;
-
-  sz+=sprintf( page+sz, "Personalities : ");
-  for (i=0; i<MAX_PERSONALITY; i++)
-    if (pers[i])
-      sz+=sprintf (page+sz, "[%d %s] ", i, pers[i]->name);
-
-  page[sz-1]='\n';
-
-  sz+=sprintf (page+sz, "read_ahead ");
-  if (read_ahead[MD_MAJOR]==INT_MAX)
-    sz+=sprintf (page+sz, "not set\n");
-  else
-    sz+=sprintf (page+sz, "%d sectors\n", read_ahead[MD_MAJOR]);
-  
-  for (i=0; i<MAX_MD_DEV; i++)
-  {
-    sz+=sprintf (page+sz, "md%d : %sactive", i, md_dev[i].pers ? "" : "in");
+	int ret;
+	mdp_super_t *tmp1, *tmp2;
 
-    if (md_dev[i].pers)
-      sz+=sprintf (page+sz, " %s", md_dev[i].pers->name);
+	tmp1 = kmalloc(sizeof(*tmp1),GFP_KERNEL);
+	tmp2 = kmalloc(sizeof(*tmp2),GFP_KERNEL);
 
-    size=0;
-    for (j=0; j<md_dev[i].nb_dev; j++)
-    {
-      sz+=sprintf (page+sz, " %s",
-		   partition_name(md_dev[i].devices[j].dev));
-      size+=md_dev[i].devices[j].size;
-    }
+	if (!tmp1 || !tmp2) {
+		ret = 0;
+		goto abort;
+	}
 
-    if (md_dev[i].nb_dev) {
-      if (md_dev[i].pers)
-        sz+=sprintf (page+sz, " %d blocks", md_size[i]);
-      else
-        sz+=sprintf (page+sz, " %d blocks", size);
-    }
+	*tmp1 = *sb1;
+	*tmp2 = *sb2;
 
-    if (!md_dev[i].pers)
-    {
-      sz+=sprintf (page+sz, "\n");
-      continue;
-    }
+	/*
+	 * nr_disks is not constant
+	 */
+	tmp1->nr_disks = 0;
+	tmp2->nr_disks = 0;
 
-    if (md_dev[i].pers->max_invalid_dev)
-      sz+=sprintf (page+sz, " maxfault=%ld", MAX_FAULT(md_dev+i));
+	if (memcmp(tmp1, tmp2, MD_SB_GENERIC_CONSTANT_WORDS * 4))
+		ret = 0;
+	else
+		ret = 1;
 
-    sz+=md_dev[i].pers->status (page+sz, i, md_dev+i);
-    sz+=sprintf (page+sz, "\n");
-  }
+abort:
+	if (tmp1)
+		kfree(tmp1);
+	if (tmp2)
+		kfree(tmp2);
 
-  return (sz);
+	return ret;
 }
 
-int register_md_personality (int p_num, struct md_personality *p)
-{
-  int i=(p_num >> PERSONALITY_SHIFT);
+static MD_LIST_HEAD(raid_managed_devices);
 
-  if (i >= MAX_PERSONALITY)
-    return -EINVAL;
+static mdk_rdev_t * find_rdev_all (kdev_t dev)
+{
+	struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
 
-  if (pers[i])
-    return -EBUSY;
-  
-  pers[i]=p;
-  printk ("%s personality registered\n", p->name);
-  return 0;
+	tmp = raid_managed_devices.next;
+	while (tmp != &raid_managed_devices) {
+		rdev = md_list_entry(tmp, mdk_rdev_t, raid_managed);
+		if (rdev->dev == dev)
+			return rdev;
+		tmp = tmp->next;
+	}
+	return NULL;
 }
 
-int unregister_md_personality (int p_num)
+#define GETBLK_FAILED KERN_ERR \
+"md: getblk failed for device %s\n"
+
+static int write_disk_sb(mdk_rdev_t * rdev)
 {
-  int i=(p_num >> PERSONALITY_SHIFT);
+	struct buffer_head *bh;
+	kdev_t dev;
+	u32 sb_offset, size;
+	mdp_super_t *sb;
 
-  if (i >= MAX_PERSONALITY)
-    return -EINVAL;
+	if (!rdev->sb) {
+		MD_BUG();
+		return -1;
+	}
+	if (rdev->faulty) {
+		MD_BUG();
+		return -1;
+	}
+	if (rdev->sb->md_magic != MD_SB_MAGIC)
+		MD_BUG();
+
+	dev = rdev->dev;
+	sb_offset = calc_dev_sboffset(dev, rdev->mddev, 1);
+	if (rdev->sb_offset != sb_offset) {
+		printk("%s's sb offset has changed from %d to %d, skipping\n", partition_name(dev), rdev->sb_offset, sb_offset);
+		goto skip;
+	}
+	/*
+	 * If the disk went offline meanwhile and it's just a spare, then
+	 * it's size has changed to zero silently, and the MD code does
+	 * not yet know that it's faulty.
+	 */
+	size = calc_dev_size(dev, rdev->mddev, 1);
+	if (size != rdev->size) {
+		printk("%s's size has changed from %d to %d since import, skipping\n", partition_name(dev), rdev->size, size);
+		goto skip;
+	}
+
+	printk("(write) %s's sb offset: %d\n", partition_name(dev), sb_offset);
+	set_blocksize(dev, MD_SB_BYTES);
+	bh = getblk(dev, sb_offset / MD_SB_BLOCKS, MD_SB_BYTES);
+	if (!bh) {
+		printk(GETBLK_FAILED, partition_name(dev));
+		return 1;
+	}
+	memset(bh->b_data,0,bh->b_size);
+	sb = (mdp_super_t *) bh->b_data;
+	memcpy(sb, rdev->sb, MD_SB_BYTES);
+
+	mark_buffer_uptodate(bh, 1);
+	mark_buffer_dirty(bh, 1);
+	ll_rw_block(WRITE, 1, &bh);
+	wait_on_buffer(bh);
+	brelse(bh);
+	fsync_dev(dev);
+skip:
+	return 0;
+}
+#undef GETBLK_FAILED KERN_ERR
+
+static void set_this_disk(mddev_t *mddev, mdk_rdev_t *rdev)
+{
+	int i, ok = 0;
+	mdp_disk_t *desc;
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		desc = mddev->sb->disks + i;
+#if 0
+		if (disk_faulty(desc)) {
+			if (MKDEV(desc->major,desc->minor) == rdev->dev)
+				ok = 1;
+			continue;
+		}
+#endif
+		if (MKDEV(desc->major,desc->minor) == rdev->dev) {
+			rdev->sb->this_disk = *desc;
+			rdev->desc_nr = desc->number;
+			ok = 1;
+			break;
+		}
+	}
+
+	if (!ok) {
+		MD_BUG();
+	}
+}
+
+static int sync_sbs(mddev_t * mddev)
+{
+	mdk_rdev_t *rdev;
+	mdp_super_t *sb;
+        struct md_list_head *tmp;
+
+        ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		sb = rdev->sb;
+		*sb = *mddev->sb;
+		set_this_disk(mddev, rdev);
+		sb->sb_csum = calc_sb_csum(sb);
+	}
+	return 0;
+}
+
+int md_update_sb(mddev_t * mddev)
+{
+	int first, err, count = 100;
+        struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
+
+repeat:
+	mddev->sb->utime = CURRENT_TIME;
+	sync_sbs(mddev);
+
+	/*
+	 * do not write anything to disk if using
+	 * nonpersistent superblocks
+	 */
+	if (mddev->sb->not_persistent)
+		return 0;
+
+	printk(KERN_INFO "md: updating md%d RAID superblock on device\n",
+					mdidx(mddev));
+
+	first = 1;
+	err = 0;
+        ITERATE_RDEV(mddev,rdev,tmp) {
+		if (!first) {
+			first = 0;
+			printk(", ");
+		}
+		if (rdev->faulty)
+			printk("(skipping faulty ");
+		printk("%s", partition_name(rdev->dev));
+		if (!rdev->faulty)
+			err += write_disk_sb(rdev);
+		else
+			printk(")\n");
+	}
+	printk(".\n");
+	if (err) {
+		printk("errors occured during superblock update, repeating\n");
+		if (--count)
+			goto repeat;
+		printk("excessive errors occured during superblock update, exiting\n");
+	}
+	return 0;
+}
+
+/*
+ * Import a device. If 'on_disk', then sanity check the superblock
+ *
+ * mark the device faulty if:
+ *
+ *   - the device is nonexistent (zero size)
+ *   - the device has no valid superblock
+ *
+ * a faulty rdev _never_ has rdev->sb set.
+ */
+static int md_import_device (kdev_t newdev, int on_disk)
+{
+	int err = 0;
+	mdk_rdev_t *rdev;
+	unsigned int size;
+
+	if (find_rdev_all(newdev))
+		return -EEXIST;
+
+	rdev = (mdk_rdev_t *) kmalloc(sizeof(*rdev), GFP_KERNEL);
+	if (!rdev) {
+		printk("could not alloc mem for %s!\n", partition_name(newdev));
+		return -ENOMEM;
+	}
+	memset(rdev, 0, sizeof(*rdev));
+
+	if (!fs_may_mount(newdev)) {
+		printk("md: can not import %s, has active inodes!\n",
+			partition_name(newdev));
+		err = -EBUSY;
+		goto abort_free;
+	}
+
+	if ((err = alloc_disk_sb(rdev)))
+		goto abort_free;
+
+	rdev->dev = newdev;
+	lock_rdev(rdev);
+	rdev->desc_nr = -1;
+	rdev->faulty = 0;
+
+	size = blk_size[MAJOR(newdev)][MINOR(newdev)];
+	if (!size) {
+		printk("md: %s has zero size, marking faulty!\n",
+				partition_name(newdev));
+		rdev->faulty = 1;
+		goto out_faulty;
+	}
+
+	if (on_disk) {
+		if ((err = read_disk_sb(rdev))) {
+			printk("md: %s has zero size,marking faulty!\n",
+					partition_name(newdev));
+			rdev->faulty = 1;
+			goto out_faulty;
+		}
+		if ((err = check_disk_sb(rdev))) {
+			printk("md: %s has invalid sb, marking faulty!\n",
+					partition_name(newdev));
+			rdev->faulty = 1;
+			goto out_faulty;
+		}
+
+		rdev->old_dev = MKDEV(rdev->sb->this_disk.major,
+					rdev->sb->this_disk.minor);
+		rdev->desc_nr = rdev->sb->this_disk.number;
+	}
+out_faulty:
+	md_list_add(&rdev->raid_managed, &raid_managed_devices);
+	if (rdev->faulty && rdev->sb)
+		free_disk_sb(rdev);
+	return 0;
+
+abort_free:
+	kfree(rdev);
+	return err;
+}
+/*
+ * Check a full RAID array for plausibility
+ */
+
+#define INCONSISTENT KERN_ERR \
+"md: fatal superblock inconsistency in %s -- removing from array\n"
+
+#define OUT_OF_DATE KERN_ERR \
+"md: superblock update time inconsistency -- using the most recent one\n"
+
+#define OLD_VERSION KERN_ALERT \
+"md: md%d: unsupported raid array version %d.%d.%d\n"
+
+#define NOT_CLEAN_IGNORE KERN_ERR \
+"md: md%d: raid array is not clean -- starting background reconstruction\n"
+
+#define UNKNOWN_LEVEL KERN_ERR \
+"md: md%d: unsupported raid level %d\n"
+
+static int analyze_sbs (mddev_t * mddev)
+{
+	int out_of_date = 0, i, duplicate, nr;
+	struct md_list_head *tmp, *tmp2;
+	mdk_rdev_t *rdev, *rdev2, *best_rdev;
+	mdp_super_t *sb, *freshest = NULL;
+
+	/*
+	 * Verify the RAID superblock on each real device
+	 */
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if (check_disk_sb(rdev))
+			goto abort;
+	}
+
+	/*
+	 * The superblock constant part has to be the same
+	 * for all disks in the array.
+	 */
+	sb = NULL;
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if (!rdev->sb) {
+			MD_BUG();
+			continue;
+		}
+		if (!sb) {
+			sb = rdev->sb;
+			continue;
+		}
+		if (!sb_equal(sb, rdev->sb)) {
+			printk (INCONSISTENT, partition_name(rdev->dev));
+			unbind_rdev_from_array(rdev);
+			export_rdev(rdev);
+			continue;
+		}
+	}
+
+	/*
+	 * OK, we have all disks and the array is ready to run. Let's
+	 * find the freshest superblock, that one will be the superblock
+	 * that represents the whole array.
+	 */
+	if (!mddev->sb)
+		if (alloc_array_sb(mddev))
+			goto abort;
+	sb = mddev->sb;
+	freshest = NULL;
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if (!rdev->sb) {
+			MD_BUG();
+			continue;
+		}
+		/*
+		 * if the checksum is invalid, use the superblock
+		 * only as a last resort. (decrease it's age by
+		 * one jiffy)
+		 */
+		if (calc_sb_csum(rdev->sb) != rdev->sb->sb_csum)
+			rdev->sb->utime--;
+
+		if (!freshest) {
+			freshest = rdev->sb;
+			continue;
+		}
+		/*
+		 * Find the newest superblock version
+		 */
+		if (rdev->sb->utime != freshest->utime) {
+			out_of_date = 1;
+			if (rdev->sb->utime > freshest->utime)
+				freshest = rdev->sb;
+		}
+	}
+	if (out_of_date)
+		printk(OUT_OF_DATE);
+	memcpy (sb, freshest, sizeof(*freshest));
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+
+		/*
+		 * Mark all non-fresh devices faulty
+		 */
+		if (rdev->sb->utime+1 < sb->utime) {
+			printk("md: marking non-fresh %s faulty!\n",
+						partition_name(rdev->dev));
+			rdev->desc_nr = -1;
+			mark_rdev_faulty(rdev);
+		}
+	}
+	/*
+	 * Fix up changed device names ... but only if this disk has a
+	 * recent update time. Use faulty checksum ones too.
+	 */
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if ((rdev->dev != rdev->old_dev) &&
+				((rdev->sb->utime == sb->utime) ||
+				 (rdev->sb->utime == sb->utime-1))) {
+			mdp_disk_t *desc;
+
+			printk("md: device name has changed from %s to %s since last import!\n", partition_name(rdev->old_dev), partition_name(rdev->dev));
+			if (rdev->desc_nr == -1) {
+				MD_BUG();
+				continue;
+			}
+			desc = &sb->disks[rdev->desc_nr];
+			if (rdev->old_dev != MKDEV(desc->major, desc->minor)) {
+				MD_BUG();
+				continue;
+			}
+			desc->major = MAJOR(rdev->dev);
+			desc->minor = MINOR(rdev->dev);
+			desc = &rdev->sb->this_disk;
+			desc->major = MAJOR(rdev->dev);
+			desc->minor = MINOR(rdev->dev);
+		}
+	}
+
+	/*
+	 * Remove unavailable devices and mark devices faulty ...
+	 *
+	 * note that if an array becomes completely unrunnable due to
+	 * missing devices, we do not write the superblock back, so the
+	 * administrator has a chance to fix things up. The removal thus
+	 * only happens if it's nonfatal to the contents of the array.
+	 */
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		int found;
+		mdp_disk_t *desc;
+		kdev_t dev;
+
+		desc = sb->disks + i;
+		dev = MKDEV(desc->major, desc->minor);
+
+		if (disk_faulty(desc)) {
+			ITERATE_RDEV(mddev,rdev,tmp) {
+				if (rdev->faulty)
+					continue;
+				if (rdev->desc_nr == -1) {
+					MD_BUG();
+					continue;
+				}
+				if (rdev->desc_nr == desc->number) {
+					printk("md: marking faulty %s descriptor's rdev faulty too!\n",
+						partition_name(rdev->dev));
+					mark_rdev_faulty(rdev);
+					break;
+				}
+			}
+			continue;
+		}
+
+		if (dev == MKDEV(0,0))
+			continue;
+		found = 0;
+		ITERATE_RDEV(mddev,rdev,tmp) {
+			if (rdev->faulty)
+				continue;
+			if ((rdev->dev == dev) &&
+					(rdev->desc_nr == desc->number)) {
+				found = 1;
+				break;
+			}
+		}
+		if (found) 
+			continue;
+
+		printk("md: former device %s is unavailable, removing from array!\n", partition_name(dev));
+		remove_descriptor(desc, sb);
+	}
+
+	/*
+	 * another subtle issue, if device names change, it's not possible
+	 * to distinct between say an old /dev/sda4 and another device
+	 * that was sda4 previously. We choose the one with a fresher
+	 * superblock and remove the other one.
+	 */
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if (rdev->desc_nr == -1) {
+			MD_BUG();
+			continue;
+		}
+		nr = rdev->desc_nr;
+		best_rdev = rdev;
+
+		duplicate = 0;
+		ITERATE_RDEV(mddev,rdev2,tmp2) {
+			if (rdev2->faulty)
+				continue;
+			if (rdev2->desc_nr == -1) {
+				MD_BUG();
+				continue;
+			}
+			if ((rdev2 != rdev) && (rdev2->desc_nr == nr)) {
+				duplicate = 1;
+				if (rdev2->sb->utime > best_rdev->sb->utime)
+					best_rdev = rdev2;
+				break;
+			}
+		}
+		if (duplicate) {
+			printk("md: duplicate disk#%d, marking old ones faulty!\n", nr);
+			
+			ITERATE_RDEV(mddev,rdev2,tmp2) {
+				if (rdev2->faulty)
+					continue;
+				if (rdev2->desc_nr == -1) {
+					MD_BUG();
+					continue;
+				}
+				if ((rdev2->desc_nr == nr) &&
+						(rdev2 != best_rdev)) {
+					rdev2->desc_nr = -1;
+					mark_rdev_faulty(rdev2);
+				}
+			}
+		}
+	}
+
+	/*
+	 * Check wether all devices mentioned in the superblock are
+	 * in the rdev ring. Also fill out rdev->desc_nr for faulty
+	 * devices. (as they have no reliable superblock themselves,
+	 * this info can only be obtained here)
+	 */
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		mdp_disk_t *desc;
+		kdev_t dev;
+
+		desc = sb->disks + i;
+		dev = MKDEV(desc->major, desc->minor);
+		if (dev == MKDEV(0,0))
+			continue;
+
+		rdev = find_rdev_all(dev);
+		if (!rdev) {
+			printk("md: device %s mentioned in sb but is unavailable, removing from array.\n", partition_name(dev));
+			remove_descriptor(desc, sb);
+			continue;
+		}
+		if (rdev->mddev != mddev) {
+			MD_BUG();
+			continue;
+		}
+		if (disk_faulty(desc)) {
+			if (!rdev->faulty) {
+				MD_BUG();
+				continue;
+			}
+			if (rdev->desc_nr != -1) {
+				if (rdev->desc_nr != desc->number)
+					MD_BUG();
+				continue;
+			}
+			rdev->desc_nr = desc->number;
+		} else {
+			if (rdev->faulty) {
+				printk("md: marking faulty %s rdev's descriptor faulty too!\n",
+						partition_name(rdev->dev));
+				if (disk_active(desc))
+					sb->active_disks--;
+				if (disk_spare(desc))
+					sb->spare_disks--;
+				sb->working_disks--;
+				sb->failed_disks++;
+				mark_disk_faulty(desc);
+				mark_disk_inactive(desc);
+				mark_disk_nonsync(desc);
+
+				if (rdev->desc_nr != -1) {
+					MD_BUG();
+					continue;
+				}
+				rdev->desc_nr = desc->number;
+			} else {
+				if (rdev->desc_nr == -1) {
+					MD_BUG();
+					continue;
+				}
+			}
+		}
+	}
+
+	/*
+	 * Finally, remove faulty devices without descritors.
+	 */
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (!rdev->faulty)
+			continue;
+		if (rdev->desc_nr == -1) {
+			printk("md: dropping descriptor-less faulty %s\n",
+				partition_name(rdev->dev));
+			unbind_rdev_from_array(rdev);
+			export_rdev(rdev);
+		}
+	}
+
+	/*
+	 * Do a final reality check.
+	 */
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->desc_nr == -1) {
+			MD_BUG();
+			goto abort;
+		}
+		/*
+		 * is the desc_nr unique?
+		 */
+		ITERATE_RDEV(mddev,rdev2,tmp2) {
+			if ((rdev2 != rdev) &&
+					(rdev2->desc_nr == rdev->desc_nr)) {
+				MD_BUG();
+				goto abort;
+			}
+		}
+		/*
+		 * is the device unique?
+		 */
+		ITERATE_RDEV(mddev,rdev2,tmp2) {
+			if ((rdev2 != rdev) &&
+					(rdev2->dev == rdev->dev)) {
+				MD_BUG();
+				goto abort;
+			}
+		}
+	}
+	/*
+	 * Check if we can support this RAID array
+	 */
+	if (sb->major_version != MD_MAJOR_VERSION ||
+			sb->minor_version > MD_MINOR_VERSION) {
+
+		printk (OLD_VERSION, mdidx(mddev), sb->major_version,
+				sb->minor_version, sb->patch_version);
+		goto abort;
+	}
+
+	if ((sb->state != (1 << MD_SB_CLEAN)) && (sb->level > 0))
+		printk (NOT_CLEAN_IGNORE, mdidx(mddev));
+
+	return 0;
+abort:
+	return 1;
+}
+
+#undef INCONSISTENT
+#undef OUT_OF_DATE
+#undef OLD_VERSION
+#undef OLD_LEVEL
+
+static int device_size_calculation (mddev_t * mddev)
+{
+	int uniform_size = 0, persistent;
+	mdp_super_t *sb = mddev->sb;
+	struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
+
+	/*
+	 * Do device size calculation. Bail out if too small.
+	 * (we have to do this after having validated chunk_size,
+	 * because device size has to be modulo chunk_size)
+	 */ 
+	persistent = !mddev->sb->not_persistent;
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if (rdev->size) {
+			MD_BUG();
+			continue;
+		}
+		rdev->size = calc_dev_size(rdev->dev, mddev, persistent);
+		if (rdev->size < sb->chunk_size / 1024) {
+			printk (KERN_WARNING
+				"Dev %s smaller than chunk_size: %dk < %dk\n",
+				partition_name(rdev->dev),
+				rdev->size, sb->chunk_size / 1024);
+			return -EINVAL;
+		}
+	}
+
+	switch (sb->level) {
+		case -1:
+		case 0:
+			zoned_raid_size(mddev);
+			break;
+		case 1:
+			uniform_size = 1;
+			break;
+		case 4:
+		case 5:
+			uniform_size = sb->raid_disks-1;
+			break;
+		default:
+			printk (UNKNOWN_LEVEL, mdidx(mddev), sb->level);
+			goto abort;
+	}
+	if (uniform_size) {
+		md_size[mdidx(mddev)] = sb->size * uniform_size;
+		md_maxreadahead[mdidx(mddev)] = MD_READAHEAD * uniform_size;
+	}
+	return 0;
+abort:
+	return 1;
+}
+
+
+#define TOO_BIG_CHUNKSIZE KERN_ERR \
+"too big chunk_size: %d > %d\n"
+
+#define TOO_SMALL_CHUNKSIZE KERN_ERR \
+"too small chunk_size: %d < %ld\n"
+
+#define BAD_CHUNKSIZE KERN_ERR \
+"no chunksize specified, see 'man raidtab'\n"
+
+static int do_md_run (mddev_t * mddev)
+{
+	int pnum, err;
+	int chunk_size;
+	struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
+
+
+	if (!mddev->nb_dev) {
+		MD_BUG();
+		return -EINVAL;
+	}
+  
+	if (mddev->pers)
+		return -EBUSY;
+
+	/*
+	 * Resize disks to align partitions size on a given
+	 * chunk size.
+	 */
+	md_size[mdidx(mddev)] = 0;
+
+	/*
+	 * Analyze all RAID superblock(s)
+	 */ 
+	if (analyze_sbs(mddev)) {
+		MD_BUG();
+		return -EINVAL;
+	}
+
+	chunk_size = mddev->sb->chunk_size;
+	pnum = level_to_pers(mddev->sb->level);
+
+	mddev->param.chunk_size = chunk_size;
+	mddev->param.personality = pnum;
+
+	if (chunk_size > MAX_CHUNK_SIZE) {
+		printk(TOO_BIG_CHUNKSIZE, chunk_size, MAX_CHUNK_SIZE);
+		return -EINVAL;
+	}
+	/*
+	 * chunk-size has to be a power of 2 and multiples of PAGE_SIZE
+	 */
+	if ( (1 << (ffs(chunk_size) - 1)) != chunk_size) {
+		MD_BUG();
+		return -EINVAL;
+	}
+	if (chunk_size < PAGE_SIZE) {
+		printk(TOO_SMALL_CHUNKSIZE, chunk_size, PAGE_SIZE);
+		return -EINVAL;
+	}
+
+	if (pnum >= MAX_PERSONALITY) {
+		MD_BUG();
+		return -EINVAL;
+	}
+
+	if ((pnum != RAID1) && (pnum != LINEAR) && !chunk_size) {
+		/*
+		 * 'default chunksize' in the old md code used to
+		 * be PAGE_SIZE, baaad.
+		 * we abort here to be on the safe side. We dont
+		 * want to continue the bad practice.
+		 */
+		printk(BAD_CHUNKSIZE);
+		return -EINVAL;
+	}
+
+	if (!pers[pnum])
+	{
+#ifdef CONFIG_KMOD
+		char module_name[80];
+		sprintf (module_name, "md-personality-%d", pnum);
+		request_module (module_name);
+		if (!pers[pnum])
+#endif
+			return -EINVAL;
+	}
+  
+	if (device_size_calculation(mddev))
+		return -EINVAL;
+
+	/*
+	 * Drop all container device buffers, from now on
+	 * the only valid external interface is through the md
+	 * device.
+	 */
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		fsync_dev(rdev->dev);
+		invalidate_buffers(rdev->dev);
+	}
+  
+	mddev->pers = pers[pnum];
+  
+	err = mddev->pers->run(mddev);
+	if (err) {
+		printk("pers->run() failed ...\n");
+		mddev->pers = NULL;
+		return -EINVAL;
+	}
+
+	mddev->sb->state &= ~(1 << MD_SB_CLEAN);
+	md_update_sb(mddev);
+
+	/*
+	 * FIXME : We assume here we have blocks
+	 * that are twice as large as sectors.
+	 * THIS MAY NOT BE TRUE !!!
+	 */
+	md_hd_struct[mdidx(mddev)].start_sect = 0;
+	md_hd_struct[mdidx(mddev)].nr_sects = md_size[mdidx(mddev)] << 1;
+  
+	read_ahead[MD_MAJOR] = 128;
+	return (0);
+}
+
+#undef TOO_BIG_CHUNKSIZE
+#undef BAD_CHUNKSIZE
+
+#define OUT(x) do { err = (x); goto out; } while (0)
+
+static int restart_array (mddev_t *mddev)
+{
+	int err = 0;
+ 
+	/*
+	 * Complain if it has no devices
+	 */
+	if (!mddev->nb_dev)
+		OUT(-ENXIO);
+
+	if (mddev->pers) {
+		if (!mddev->ro)
+			OUT(-EBUSY);
+
+		mddev->ro = 0;
+		set_device_ro(mddev_to_kdev(mddev), 0);
+
+		printk (KERN_INFO
+			"md%d switched to read-write mode.\n", mdidx(mddev));
+		/*
+		 * Kick recovery or resync if necessary
+		 */
+		md_recover_arrays();
+		if (mddev->pers->restart_resync)
+			mddev->pers->restart_resync(mddev);
+	} else
+		err = -EINVAL;
+ 
+out:
+	return err;
+}
+
+#define STILL_MOUNTED KERN_WARNING \
+"md: md%d still mounted.\n"
+
+static int do_md_stop (mddev_t * mddev, int ro)
+{
+	int err = 0, resync_interrupted = 0;
+	kdev_t dev = mddev_to_kdev(mddev);
+ 
+	if (!ro && !fs_may_mount (dev)) {
+		printk (STILL_MOUNTED, mdidx(mddev));
+		OUT(-EBUSY);
+	}
+  
+	/*
+	 * complain if it's already stopped
+	 */
+	if (!mddev->nb_dev)
+		OUT(-ENXIO);
+
+	if (mddev->pers) {
+		/*
+		 * It is safe to call stop here, it only frees private
+		 * data. Also, it tells us if a device is unstoppable
+		 * (eg. resyncing is in progress)
+		 */
+		if (mddev->pers->stop_resync)
+			if (mddev->pers->stop_resync(mddev))
+				resync_interrupted = 1;
+
+		if (mddev->recovery_running)
+			md_interrupt_thread(md_recovery_thread);
+
+		/*
+		 * This synchronizes with signal delivery to the
+		 * resync or reconstruction thread. It also nicely
+		 * hangs the process if some reconstruction has not
+		 * finished.
+		 */
+		down(&mddev->recovery_sem);
+		up(&mddev->recovery_sem);
+
+		/*
+		 *  sync and invalidate buffers because we cannot kill the
+		 *  main thread with valid IO transfers still around.
+		 *  the kernel lock protects us from new requests being
+		 *  added after invalidate_buffers().
+		 */
+		fsync_dev (dev);
+		invalidate_buffers (dev);
+
+		if (ro) {
+			if (mddev->ro)
+				OUT(-ENXIO);
+			mddev->ro = 1;
+		} else {
+			if (mddev->ro)
+				set_device_ro(dev, 0);
+			if (mddev->pers->stop(mddev)) {
+				if (mddev->ro)
+					set_device_ro(dev, 1);
+				OUT(-EBUSY);
+			}
+			if (mddev->ro)
+				mddev->ro = 0;
+		}
+		if (mddev->sb) {
+			/*
+			 * mark it clean only if there was no resync
+			 * interrupted.
+			 */
+			if (!mddev->recovery_running && !resync_interrupted)
+				mddev->sb->state |= 1 << MD_SB_CLEAN;
+			md_update_sb(mddev);
+		}
+		if (ro)
+			set_device_ro(dev, 1);
+	}
+ 
+	/*
+	 * Free resources if final stop
+	 */
+	if (!ro) {
+		mddev->pers = NULL;
+		md_size[mdidx(mddev)] = 0;
+		md_hd_struct[mdidx(mddev)].nr_sects = 0;
+		mddev->curr_resync = 0;
+		mddev->recovery_running = 0;
+		export_array(mddev);
+
+		printk (KERN_INFO "md%d stopped.\n", mdidx(mddev));
+	} else
+		printk (KERN_INFO
+			"md%d switched to read-only mode.\n", mdidx(mddev));
+out:
+	return err;
+}
+
+#undef OUT
+
+/*
+ * We have to safely support old arrays too.
+ */
+int detect_old_array (mdp_super_t *sb)
+{
+	if (sb->major_version > 0)
+		return 0;
+	if (sb->minor_version >= 90)
+		return 0;
+
+	return -EINVAL;
+}
+
+
+static void autorun_array (mddev_t *mddev)
+{
+	mdk_rdev_t *rdev;
+        struct md_list_head *tmp;
+	int err;
+
+	if (mddev->disks.prev == &mddev->disks) {
+		MD_BUG();
+		return;
+	}
+
+	printk("running: ");
+
+        ITERATE_RDEV(mddev,rdev,tmp) {
+		printk("<%s>", partition_name(rdev->dev));
+	}
+	printk("\nnow!\n");
+
+	err = do_md_run (mddev);
+	if (err) {
+		printk("do_md_run() returned %d\n", err);
+		/*
+		 * prevent the writeback of an unrunnable array
+		 */
+		mddev->sb_dirty = 0;
+		do_md_stop (mddev, 0);
+	}
+}
+
+static void autorun_devices (void)
+{
+	mddev_t *mddev;
+	int i;
+
+	for (i = 0; i < MAX_MD_DEV; i++) {
+		mddev = md_arrays+i;
+		if (mddev->disks.prev != &mddev->disks) {
+			printk("autorunning md%d\n", mdidx(mddev));
+			autorun_array(mddev);
+		}
+	}
+}
+
+/*
+ * import RAID devices based on one partition
+ * if possible, the array gets run as well.
+ */
+
+#define BAD_VERSION KERN_ERR \
+"md: %s has RAID superblock version 0.%d, autodetect needs v0.90 or higher\n"
+
+#define OUT_OF_MEM KERN_ALERT \
+"md: out of memory.\n"
+
+#define NO_DEVICE KERN_ERR \
+"md: disabled device %s\n"
+
+#define AUTOADD_FAILED KERN_ERR \
+"md: auto-adding devices to md%d FAILED (error %d).\n"
+
+#define AUTOADD_FAILED_USED KERN_ERR \
+"md: cannot auto-add device %s to md%d, already used.\n"
+
+#define AUTORUN_FAILED KERN_ERR \
+"md: auto-running md%d FAILED (error %d).\n"
+
+#define MDDEV_BUSY KERN_ERR \
+"md: cannot auto-add to md%d, already running.\n"
+
+#define AUTOADDING KERN_INFO \
+"md: auto-adding devices to md%d, based on %s's superblock.\n"
+
+#define AUTORUNNING KERN_INFO \
+"md: auto-running md%d.\n"
+
+static int autostart_array (kdev_t startdev)
+{
+	int err = -EINVAL, i;
+	mdp_super_t *sb = NULL;
+	mdk_rdev_t *start_rdev = NULL, *rdev;
+	mddev_t *mddev;
+
+	if (md_import_device(startdev, 1)) {
+		printk("could not import %s!\n", partition_name(startdev));
+		goto abort;
+	}
+
+	start_rdev = find_rdev_all(startdev);
+	if (!start_rdev) {
+		MD_BUG();
+		goto abort;
+	}
+	if (start_rdev->faulty) {
+		printk("can not autostart based on faulty %s!\n",
+						partition_name(startdev));
+		goto abort;
+	}
+
+	sb = start_rdev->sb;
+
+	err = detect_old_array(sb);
+	if (err) {
+		printk("array version is too old to be autostarted, use raidtools 0.90 mkraid --upgrade\nto upgrade the array without data loss!\n");
+		goto abort;
+	}
+
+	/*
+	 * cycle through devices and import+bind them
+	 */
+	mddev = md_arrays + sb->md_minor;
+	bind_rdev_to_array(start_rdev, mddev);
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		mdp_disk_t *desc;
+		kdev_t dev;
+
+		desc = sb->disks + i;
+		dev = MKDEV(desc->major, desc->minor);
+
+		if (dev == MKDEV(0,0))
+			continue;
+		if (dev == startdev)
+			continue;
+		md_import_device(dev, 1);
+		rdev = find_rdev_all(dev);
+		if (!rdev)
+			goto abort_stop;
+		bind_rdev_to_array(rdev, mddev);
+	}
+
+	printk (AUTORUNNING, mdidx(mddev));
+	err = do_md_run (mddev);
+	if (err) {
+		printk (AUTORUN_FAILED, mdidx(mddev), err);
+		mddev->sb_dirty = 0;
+		goto abort_stop;
+	}
+	return 0;
+
+abort_stop:
+	do_md_stop (mddev, 0);
+	return err;
+abort:
+	if (start_rdev)
+		export_rdev(start_rdev);
+	return err;
+}
+
+#undef BAD_VERSION
+#undef OUT_OF_MEM
+#undef NO_DEVICE
+#undef AUTOADD_FAILED_USED
+#undef AUTOADD_FAILED
+#undef AUTORUN_FAILED
+#undef AUTOADDING
+#undef AUTORUNNING
+
+/*
+ * Searches all registered partitions for autorun RAID arrays
+ * at boot time.
+ */
+md__initfunc(void autodetect_raid(void))
+{
+#ifdef CONFIG_AUTODETECT_RAID
+	struct gendisk *disk;
+	int i;
+
+	printk(KERN_INFO "autodetecting RAID arrays\n");
+
+	for (disk = gendisk_head ; disk ; disk = disk->next)
+		for (i = 0; i < disk->max_p*disk->max_nr; i++) {
+			kdev_t dev = MKDEV(disk->major,i);
+
+			if (disk->part[i].type == LINUX_OLD_RAID_PARTITION) {
+				printk(KERN_ALERT
+"md: %s's partition type has to be changed from type 0x86 to type 0xfd\n"
+"    to maintain interoperability with other OSs! Autodetection support for\n"
+"    type 0x86 will be deleted after some migration timeout. Sorry.\n",
+					partition_name(dev));
+				disk->part[i].type = LINUX_RAID_PARTITION;
+			}
+			if (disk->part[i].type == LINUX_RAID_PARTITION) {
+				mdk_rdev_t *rdev;
+				mddev_t *mddev;
+
+				md_import_device(dev,1);
+				rdev = find_rdev_all(dev);
+				if (!rdev) {
+					printk(KERN_ALERT "could not import %s alhough marked RAID partition!\n", partition_name(dev));
+					continue;
+				}
+				if (rdev->faulty) {
+					printk(KERN_ALERT "could not autorun faulty %s, although marked as RAID partition!\n", partition_name(dev));
+					export_rdev(rdev);
+					continue;
+				}
+				mddev = md_arrays + rdev->sb->md_minor;
+				bind_rdev_to_array(rdev, mddev);
+			}
+		}
+
+	autorun_devices();
+#endif
+}
+
+static int get_version (void * arg)
+{
+	mdu_version_t ver;
+
+	ver.major = MD_MAJOR_VERSION;
+	ver.minor = MD_MINOR_VERSION;
+	ver.patchlevel = MD_PATCHLEVEL_VERSION;
+
+	if (md_copy_to_user(arg, &ver, sizeof(ver)))
+		return -EFAULT;
+
+	return 0;
+}
+
+#define SET_FROM_SB(x) info.x = mddev->sb->x
+static int get_array_info (mddev_t * mddev, void * arg)
+{
+	mdu_array_info_t info;
+
+	if (!mddev->sb)
+		return -EINVAL;
+
+	SET_FROM_SB(major_version);
+	SET_FROM_SB(minor_version);
+	SET_FROM_SB(patch_version);
+	SET_FROM_SB(ctime);
+	SET_FROM_SB(level);
+	SET_FROM_SB(size);
+	SET_FROM_SB(nr_disks);
+	SET_FROM_SB(raid_disks);
+	SET_FROM_SB(md_minor);
+	SET_FROM_SB(not_persistent);
+
+	SET_FROM_SB(utime);
+	SET_FROM_SB(state);
+	SET_FROM_SB(active_disks);
+	SET_FROM_SB(working_disks);
+	SET_FROM_SB(failed_disks);
+	SET_FROM_SB(spare_disks);
+
+	SET_FROM_SB(layout);
+	SET_FROM_SB(chunk_size);
+
+	if (md_copy_to_user(arg, &info, sizeof(info)))
+		return -EFAULT;
+
+	return 0;
+}
+#undef SET_FROM_SB
+
+#define SET_FROM_SB(x) info.x = mddev->sb->disks[nr].x
+static int get_disk_info (mddev_t * mddev, void * arg)
+{
+	mdu_disk_info_t info;
+	unsigned int nr;
+
+	if (!mddev->sb)
+		return -EINVAL;
+
+	if (md_copy_from_user(&info, arg, sizeof(info)))
+		return -EFAULT;
+
+	nr = info.number;
+	if (nr >= mddev->sb->nr_disks)
+		return -EINVAL;
+
+	SET_FROM_SB(major);
+	SET_FROM_SB(minor);
+	SET_FROM_SB(raid_disk);
+	SET_FROM_SB(state);
+
+	if (md_copy_to_user(arg, &info, sizeof(info)))
+		return -EFAULT;
+
+	return 0;
+}
+#undef SET_FROM_SB
+
+#define SET_SB(x) mddev->sb->disks[nr].x = info.x
+
+static int add_new_disk (mddev_t * mddev, void * arg)
+{
+	int err, size, persistent;
+	mdu_disk_info_t info;
+	mdk_rdev_t *rdev;
+	unsigned int nr;
+	kdev_t dev;
+
+	if (!mddev->sb)
+		return -EINVAL;
+
+	if (md_copy_from_user(&info, arg, sizeof(info)))
+		return -EFAULT;
+
+	nr = info.number;
+	if (nr >= mddev->sb->nr_disks)
+		return -EINVAL;
+
+	dev = MKDEV(info.major,info.minor);
+
+	if (find_rdev_all(dev)) {
+		printk("device %s already used in a RAID array!\n", 
+				partition_name(dev));
+		return -EBUSY;
+	}
+
+	SET_SB(number);
+	SET_SB(major);
+	SET_SB(minor);
+	SET_SB(raid_disk);
+	SET_SB(state);
+
+	err = md_import_device (dev, 0);
+	if (err) {
+		printk("md: error, md_import_device() returned %d\n", err);
+		return -EINVAL;
+	}
+	rdev = find_rdev_all(dev);
+	if (!rdev) {
+		MD_BUG();
+		return -EINVAL;
+	}
+
+	rdev->old_dev = dev;
+	rdev->desc_nr = info.number;
+
+	bind_rdev_to_array(rdev, mddev);
+
+	persistent = !mddev->sb->not_persistent;
+	if (!persistent)
+		printk("nonpersistent superblock ...\n");
+	if (!mddev->sb->chunk_size)
+		printk("no chunksize?\n");
+
+	size = calc_dev_size(dev, mddev, persistent);
+	rdev->sb_offset = calc_dev_sboffset(dev, mddev, persistent);
+
+	if (!mddev->sb->size || (mddev->sb->size > size))
+		mddev->sb->size = size;
+
+	/*
+	 * sync all other superblocks with the main superblock
+	 */
+	sync_sbs(mddev);
+
+	return 0;
+}
+#undef SET_SB
+
+static int hot_remove_disk (mddev_t * mddev, kdev_t dev)
+{
+	int err;
+	mdk_rdev_t *rdev;
+	mdp_disk_t *disk;
+
+	if (!mddev->pers)
+		return -ENODEV;
+
+	printk("trying to remove %s from md%d ... \n",
+		partition_name(dev), mdidx(mddev));
+
+	if (!mddev->pers->diskop) {
+		printk("md%d: personality does not support diskops!\n",
+								 mdidx(mddev));
+		return -EINVAL;
+	}
+
+	rdev = find_rdev(mddev, dev);
+	if (!rdev)
+		return -ENXIO;
+
+	if (rdev->desc_nr == -1) {
+		MD_BUG();
+		return -EINVAL;
+	}
+	disk = &mddev->sb->disks[rdev->desc_nr];
+	if (disk_active(disk))
+		goto busy;
+	if (disk_removed(disk)) {
+		MD_BUG();
+		return -EINVAL;
+	}
+	
+	err = mddev->pers->diskop(mddev, &disk, DISKOP_HOT_REMOVE_DISK);
+	if (err == -EBUSY)
+		goto busy;
+	if (err) {
+		MD_BUG();
+		return -EINVAL;
+	}
+
+	remove_descriptor(disk, mddev->sb);
+	unbind_rdev_from_array(rdev);
+	export_rdev(rdev);
+	mddev->sb_dirty = 1;
+	md_update_sb(mddev);
+
+	return 0;
+busy:
+	printk("cannot remove active disk %s from md%d ... \n",
+		partition_name(dev), mdidx(mddev));
+	return -EBUSY;
+}
+
+static int hot_add_disk (mddev_t * mddev, kdev_t dev)
+{
+	int i, err, persistent;
+	unsigned int size;
+	mdk_rdev_t *rdev;
+	mdp_disk_t *disk;
+
+	if (!mddev->pers)
+		return -ENODEV;
+
+	printk("trying to hot-add %s to md%d ... \n",
+		partition_name(dev), mdidx(mddev));
+
+	if (!mddev->pers->diskop) {
+		printk("md%d: personality does not support diskops!\n",
+								 mdidx(mddev));
+		return -EINVAL;
+	}
+
+	persistent = !mddev->sb->not_persistent;
+	size = calc_dev_size(dev, mddev, persistent);
+
+	if (size < mddev->sb->size) {
+		printk("md%d: disk size %d blocks < array size %d\n",
+				mdidx(mddev), size, mddev->sb->size);
+		return -ENOSPC;
+	}
+
+	rdev = find_rdev(mddev, dev);
+	if (rdev)
+		return -EBUSY;
+
+	err = md_import_device (dev, 0);
+	if (err) {
+		printk("md: error, md_import_device() returned %d\n", err);
+		return -EINVAL;
+	}
+	rdev = find_rdev_all(dev);
+	if (!rdev) {
+		MD_BUG();
+		return -EINVAL;
+	}
+	if (rdev->faulty) {
+		printk("md: can not hot-add faulty %s disk to md%d!\n",
+				partition_name(dev), mdidx(mddev));
+		err = -EINVAL;
+		goto abort_export;
+	}
+	bind_rdev_to_array(rdev, mddev);
+
+	/*
+	 * The rest should better be atomic, we can have disk failures
+	 * noticed in interrupt contexts ...
+	 */
+	cli();
+	rdev->old_dev = dev;
+	rdev->size = size;
+	rdev->sb_offset = calc_dev_sboffset(dev, mddev, persistent);
+
+	disk = mddev->sb->disks + mddev->sb->raid_disks;
+	for (i = mddev->sb->raid_disks; i < MD_SB_DISKS; i++) {
+		disk = mddev->sb->disks + i;
+
+		if (!disk->major && !disk->minor)
+			break;
+		if (disk_removed(disk))
+			break;
+	}
+	if (i == MD_SB_DISKS) {
+		printk("md%d: can not hot-add to full array!\n", mdidx(mddev));
+		sti();
+		err = -EBUSY;
+		goto abort_unbind_export;
+	}
+
+	if (disk_removed(disk)) {
+		/*
+		 * reuse slot
+		 */
+		if (disk->number != i) {
+			MD_BUG();
+			err = -EINVAL;
+			goto abort_unbind_export;
+		}
+	} else {
+		disk->number = i;
+	}
+
+	disk->raid_disk = disk->number;
+	disk->major = MAJOR(dev);
+	disk->minor = MINOR(dev);
+
+	if (mddev->pers->diskop(mddev, &disk, DISKOP_HOT_ADD_DISK)) {
+		sti();
+		MD_BUG();
+		err = -EINVAL;
+		goto abort_unbind_export;
+	}
+
+	mark_disk_spare(disk);
+	mddev->sb->nr_disks++;
+	mddev->sb->spare_disks++;
+	mddev->sb->working_disks++;
+
+	mddev->sb_dirty = 1;
+
+	sti();
+	md_update_sb(mddev);
+
+	/*
+	 * Kick recovery, maybe this spare has to be added to the
+	 * array immediately.
+	 */
+	md_recover_arrays();
+
+	return 0;
+
+abort_unbind_export:
+	unbind_rdev_from_array(rdev);
+
+abort_export:
+	export_rdev(rdev);
+	return err;
+}
+
+#define SET_SB(x) mddev->sb->x = info.x
+static int set_array_info (mddev_t * mddev, void * arg)
+{
+	mdu_array_info_t info;
+
+	if (mddev->sb) {
+		printk("array md%d already has a superblock!\n", 
+				mdidx(mddev));
+		return -EBUSY;
+	}
+
+	if (md_copy_from_user(&info, arg, sizeof(info)))
+		return -EFAULT;
+
+	if (alloc_array_sb(mddev))
+		return -ENOMEM;
+
+	mddev->sb->major_version = MD_MAJOR_VERSION;
+	mddev->sb->minor_version = MD_MINOR_VERSION;
+	mddev->sb->patch_version = MD_PATCHLEVEL_VERSION;
+	mddev->sb->ctime = CURRENT_TIME;
+
+	SET_SB(level);
+	SET_SB(size);
+	SET_SB(nr_disks);
+	SET_SB(raid_disks);
+	SET_SB(md_minor);
+	SET_SB(not_persistent);
+
+	SET_SB(state);
+	SET_SB(active_disks);
+	SET_SB(working_disks);
+	SET_SB(failed_disks);
+	SET_SB(spare_disks);
+
+	SET_SB(layout);
+	SET_SB(chunk_size);
+
+	mddev->sb->md_magic = MD_SB_MAGIC;
+
+	/*
+	 * Generate a 128 bit UUID
+	 */
+	get_random_bytes(&mddev->sb->set_uuid0, 4);
+	get_random_bytes(&mddev->sb->set_uuid1, 4);
+	get_random_bytes(&mddev->sb->set_uuid2, 4);
+	get_random_bytes(&mddev->sb->set_uuid3, 4);
+
+	return 0;
+}
+#undef SET_SB
+
+static int set_disk_info (mddev_t * mddev, void * arg)
+{
+	printk("not yet");
+	return -EINVAL;
+}
+
+static int clear_array (mddev_t * mddev)
+{
+	printk("not yet");
+	return -EINVAL;
+}
+
+static int write_raid_info (mddev_t * mddev)
+{
+	printk("not yet");
+	return -EINVAL;
+}
+
+static int protect_array (mddev_t * mddev)
+{
+	printk("not yet");
+	return -EINVAL;
+}
+
+static int unprotect_array (mddev_t * mddev)
+{
+	printk("not yet");
+	return -EINVAL;
+}
+
+static int md_ioctl (struct inode *inode, struct file *file,
+                     unsigned int cmd, unsigned long arg)
+{
+	unsigned int minor;
+	int err = 0;
+	struct hd_geometry *loc = (struct hd_geometry *) arg;
+	mddev_t *mddev;
+
+	if (!md_capable_admin())
+		return -EACCES;
+
+	minor = MINOR(inode->i_rdev);
+	if (minor >= MAX_MD_DEV)
+		return -EINVAL;
+	mddev = kdev_to_mddev(inode->i_rdev);
+
+	if (mddev->busy) {
+		printk("array md%d already executing ioctl!\n", mdidx(mddev));
+		return -EBUSY;
+	} else
+		mddev->busy = 1;
+
+	switch (cmd)
+	{
+		case RAID_VERSION:
+			err = get_version((void *)arg);
+			break;
+      
+		case GET_ARRAY_INFO:
+			err = get_array_info(mddev, (void *)arg);
+			break;
+      
+		case GET_DISK_INFO:
+			err = get_disk_info(mddev, (void *)arg);
+			break;
+      
+		case CLEAR_ARRAY:
+			err = clear_array(mddev);
+			break;
+      
+		case ADD_NEW_DISK:
+			err = add_new_disk(mddev, (void *)arg);
+			break;
+      
+		case HOT_REMOVE_DISK:
+			err = hot_remove_disk(mddev, (kdev_t)arg);
+			break;
+      
+		case HOT_ADD_DISK:
+			err = hot_add_disk(mddev, (kdev_t)arg);
+			break;
+      
+		case SET_ARRAY_INFO:
+			err = set_array_info(mddev, (void *)arg);
+			break;
+      
+		case SET_DISK_INFO:
+			err = set_disk_info(mddev, (void *)arg);
+			break;
+      
+		case WRITE_RAID_INFO:
+			err = write_raid_info(mddev);
+			break;
+      
+		case UNPROTECT_ARRAY:
+			err = unprotect_array(mddev);
+			break;
+      
+		case PROTECT_ARRAY:
+			err = protect_array(mddev);
+			break;
+      
+		case RUN_ARRAY:
+		{
+			mdu_param_t param;
+
+			err = md_copy_from_user(&param, (mdu_param_t *)arg,
+							 sizeof(param));
+			if (err)
+				break;
+
+			err = do_md_run (mddev);
+			/*
+			 * we have to clean up the mess if
+			 * the array cannot be run for some
+			 * reason ...
+			 */
+			if (err) {
+				mddev->sb_dirty = 0;
+				do_md_stop (mddev, 0);
+			}
+			break;
+		}
+      
+		case START_ARRAY:
+			err = autostart_array((kdev_t)arg);
+			if (err) {
+				printk("autostart %s failed!\n",
+					partition_name((kdev_t)arg));
+			}
+			break;
+      
+		case RESTART_ARRAY_RW:
+			err = restart_array(mddev);
+			break;
+
+		case STOP_ARRAY:
+			err = do_md_stop (mddev, 0);
+			break;
+      
+		case STOP_ARRAY_RO:
+			err = do_md_stop (mddev, 1);
+			break;
+      
+		case BLKGETSIZE:   /* Return device size */
+			if (!arg) {
+				err = -EINVAL;
+				break;
+			}
+			err = md_put_user(md_hd_struct[
+				MINOR(inode->i_rdev)].nr_sects, (long *) arg);
+			break;
+
+		case BLKFLSBUF:
+			fsync_dev (inode->i_rdev);
+			invalidate_buffers (inode->i_rdev);
+			break;
+
+		case BLKRASET:
+			if (arg > 0xff)
+				err = -EINVAL;
+			read_ahead[MAJOR(inode->i_rdev)] = arg;
+			break;
+    
+		case BLKRAGET:
+			if (!arg)
+				err = -EINVAL;
+			err = md_put_user (read_ahead[
+				MAJOR(inode->i_rdev)], (long *) arg);
+			break;
+	/*
+	 * We have a problem here : there is no easy way to give a CHS
+	 * virtual geometry. We currently pretend that we have a 2 heads
+	 * 4 sectors (with a BIG number of cylinders...). This drives
+	 * dosfs just mad... ;-)
+	 */
+		case HDIO_GETGEO:
+			if (!loc) {
+				err = -EINVAL;
+				break;
+			}
+			err = md_put_user (2, (char *) &loc->heads);
+			if (err)
+				break;
+			err = md_put_user (4, (char *) &loc->sectors);
+			if (err)
+				break;
+			err = md_put_user (md_hd_struct[mdidx(mddev)].nr_sects/8,
+						(short *) &loc->cylinders);
+			if (err)
+				break;
+			err = md_put_user (md_hd_struct[MINOR(inode->i_rdev)
+				].start_sect, (long *) &loc->start);
+			break;
+    
+		default:
+			printk(KERN_WARNING "%s(pid %d) used obsolete MD ioctl, upgrade your software to use new ictls.\n", current->comm, current->pid);
+			err = -EINVAL;
+	}
+	if (!mddev->busy)
+		printk("huh9???\n");
+	mddev->busy = 0;
+	return err;
+}
+
+
+#if LINUX_VERSION_CODE < LinuxVersionCode(2,1,0)
+
+static int md_open (struct inode *inode, struct file *file)
+{
+	/*
+	 * Always succeed
+	 */
+	return (0);
+}
+
+static void md_release (struct inode *inode, struct file *file)
+{
+	sync_dev(inode->i_rdev);
+}
+
+
+static int md_read (struct inode *inode, struct file *file,
+						char *buf, int count)
+{
+	if (!kdev_to_mddev(MD_FILE_TO_INODE(file)->i_rdev)->pers)
+		return -ENXIO;
+
+	return block_read (inode, file, buf, count);
+}
+
+static int md_write (struct inode *inode, struct file *file,
+						const char *buf, int count)
+{
+	if (!kdev_to_mddev(MD_FILE_TO_INODE(file)->i_rdev)->pers)
+		return -ENXIO;
+
+	return block_write (inode, file, buf, count);
+}
+
+static struct file_operations md_fops=
+{
+	NULL,
+	md_read,
+	md_write,
+	NULL,
+	NULL,
+	md_ioctl,
+	NULL,
+	md_open,
+	md_release,
+	block_fsync
+};
+
+#else
+
+static int md_open (struct inode *inode, struct file *file)
+{
+	/*
+	 * Always succeed
+	 */
+	return (0);
+}
+
+static int md_release (struct inode *inode, struct file *file)
+{
+	sync_dev(inode->i_rdev);
+	return 0;
+}
+
+static ssize_t md_read (struct file *file, char *buf, size_t count,
+			loff_t *ppos)
+{
+	if (!kdev_to_mddev(MD_FILE_TO_INODE(file)->i_rdev)->pers)
+		return -ENXIO;
+
+	return block_read(file, buf, count, ppos);
+}
+
+static ssize_t md_write (struct file *file, const char *buf,
+			 size_t count, loff_t *ppos)
+{
+	if (!kdev_to_mddev(MD_FILE_TO_INODE(file)->i_rdev)->pers)
+		return -ENXIO;
+
+	return block_write(file, buf, count, ppos);
+}
+
+static struct file_operations md_fops=
+{
+	NULL,
+	md_read,
+	md_write,
+	NULL,
+	NULL,
+	md_ioctl,
+	NULL,
+	md_open,
+	NULL,
+	md_release,
+	block_fsync
+};
+
+#endif
+
+int md_map (int minor, kdev_t *rdev, unsigned long *rsector, unsigned long size)
+{
+	int err;
+	mddev_t * mddev = kdev_to_mddev(*rdev);
+
+	if (!mddev->pers) {
+		err = -ENXIO;
+		goto out;
+	}
+
+	err = mddev->pers->map(mddev, rdev, rsector, size);
+out:
+	return err;
+}
+  
+int md_make_request (int minor, int rw, struct buffer_head * bh)
+{
+	int err;
+	mddev_t *mddev = md_arrays + minor;
+
+	if (!mddev->pers) {
+		err = -ENXIO;
+		goto out;
+	}
+
+	if (mddev->pers->make_request) {
+		if (buffer_locked(bh)) {
+			err = 0;
+			goto out;
+		}
+		set_bit(BH_Lock, &bh->b_state);
+		if (rw == WRITE || rw == WRITEA) {
+			if (!buffer_dirty(bh)) {
+				bh->b_end_io(bh, buffer_uptodate(bh));
+				err = 0;
+				goto out;
+			}
+		}
+		if (rw == READ || rw == READA) {
+			if (buffer_uptodate(bh)) {
+				bh->b_end_io(bh, buffer_uptodate(bh));
+				err = 0;
+				goto out;
+			}
+		}
+		err = mddev->pers->make_request(mddev, rw, bh);
+	} else {
+		make_request (MAJOR(bh->b_rdev), rw, bh);
+		err = 0;
+	}
+out:
+	return err;
+}
+
+static void do_md_request (void)
+{
+	printk(KERN_ALERT "Got md request, not good...");
+	return;
+}
 
-  printk ("%s personality unregistered\n", pers[i]->name);
-  pers[i]=NULL;
-  return 0;
-} 
+void md_wakeup_thread(mdk_thread_t *thread)
+{
+	set_bit(THREAD_WAKEUP, &thread->flags);
+	wake_up(&thread->wqueue);
+}
+
+mdk_thread_t *md_register_thread (void (*run) (void *),
+						void *data, const char *name)
+{
+	mdk_thread_t *thread;
+	int ret;
+	struct semaphore sem = MUTEX_LOCKED;
+	
+	thread = (mdk_thread_t *) kmalloc
+				(sizeof(mdk_thread_t), GFP_KERNEL);
+	if (!thread)
+		return NULL;
+	
+	memset(thread, 0, sizeof(mdk_thread_t));
+	init_waitqueue(&thread->wqueue);
+	
+	thread->sem = &sem;
+	thread->run = run;
+	thread->data = data;
+	thread->name = name;
+	ret = kernel_thread(md_thread, thread, 0);
+	if (ret < 0) {
+		kfree(thread);
+		return NULL;
+	}
+	down(&sem);
+	return thread;
+}
+
+void md_unregister_thread (mdk_thread_t *thread)
+{
+	struct semaphore sem = MUTEX_LOCKED;
+	
+	thread->sem = &sem;
+	thread->run = NULL;
+	thread->name = NULL;
+	if (!thread->tsk) {
+		MD_BUG();
+		return;
+	}
+	send_sig(SIGKILL, thread->tsk, 1);
+	down(&sem);
+}
+
+void md_interrupt_thread (mdk_thread_t *thread)
+{
+	if (!thread->tsk) {
+		MD_BUG();
+		return;
+	}
+	send_sig(SIGINT, thread->tsk, 1);
+}
+
+extern int sys_setsid(void);
 
 int md_thread(void * arg)
 {
-	struct md_thread *thread = arg;
+	mdk_thread_t *thread = arg;
+
+	md_lock_kernel();
+	exit_mm(current);
+	exit_files(current);
+	exit_fs(current);
+
+	/*
+	 * Detach thread
+	 */
+	sys_setsid();
+	sprintf(current->comm, thread->name);
+	md_init_signals();
+	thread->tsk = current;
+
+	/*
+	 * md_thread is a 'system-thread', it's priority should be very
+	 * high. We avoid resource deadlocks individually in each
+	 * raid personality. (RAID5 does preallocation) We also use RR and
+	 * the very same RT priority as kswapd, thus we will never get
+	 * into a priority inversion deadlock.
+	 *
+	 * we definitely have to have equal or higher priority than
+	 * bdflush, otherwise bdflush will deadlock if there are too
+	 * many dirty RAID5 blocks.
+	 */
+	current->policy = SCHED_FIFO;
+	current->rt_priority = 32;
+
+	up(thread->sem);
 
-	current->session = 1;
-	current->pgrp = 1;
-	sprintf(current->comm, "md_thread");
-
-#ifdef __SMP__
-	lock_kernel();
-	syscall_count++;
-#endif
 	for (;;) {
+		cli();
+		if (!test_bit(THREAD_WAKEUP, &thread->flags)) {
+			do {
+				md_flush_signals();
+				if (!thread->run) {
+					sti();
+					up(thread->sem);
+					return 0;
+				}
+				interruptible_sleep_on(&thread->wqueue);
+				cli();
+				if (test_bit(THREAD_WAKEUP, &thread->flags))
+					break;
+			} while (md_signal_pending(current));
+		}
 		sti();
 		clear_bit(THREAD_WAKEUP, &thread->flags);
 		if (thread->run) {
 			thread->run(thread->data);
+			if (md_signal_pending(current)) {
+
+			}
 			run_task_queue(&tq_disk);
 		}
-		current->signal = 0;
+	}
+}
+
+void md_recover_arrays (void)
+{
+	if (!md_recovery_thread) {
+		MD_BUG();
+		return;
+	}
+	md_wakeup_thread(md_recovery_thread);
+}
+
+
+int md_error (kdev_t dev, kdev_t rdev)
+{
+	mddev_t *mddev = kdev_to_mddev(dev);
+	mdk_rdev_t * rrdev = find_rdev(mddev, rdev);
+	int rc;
+
+	mark_rdev_faulty(rrdev);
+	if (mddev->pers->error_handler) {
+		rc = mddev->pers->error_handler(mddev, rdev);
+		md_recover_arrays();
+		return rc;
+	}
+	/*
+	 * Drop all buffers in the failed array.
+	 */
+	invalidate_buffers(rdev);
+	return 0;
+}
+
+static int status_unused (char * page)
+{
+	int sz = 0;
+	mdk_rdev_t *rdev;
+	struct md_list_head *tmp;
+
+	sz += sprintf(page + sz, "unused : ");
+
+	ITERATE_RDEV_MANAGED(rdev,tmp) {
+		if (!rdev->same_set.next && !rdev->same_set.prev)
+			/*
+			 * The device is not yet used by any array.
+			 */
+			sz += sprintf(page + sz, "%s ",
+				partition_name(rdev->dev));
+	}
+	sz += sprintf(page + sz, "\n");
+	return sz;
+}
+
+
+static int status_resync (char * page, mddev_t * mddev)
+{
+	int sz = 0;
+	unsigned int blocksize, max_blocks, resync, res, dt, tt, et;
+
+	resync = mddev->curr_resync;
+	blocksize = blksize_size[MD_MAJOR][mdidx(mddev)];
+	max_blocks = blk_size[MD_MAJOR][mdidx(mddev)] / (blocksize >> 10);
+
+	/*
+	 * Should not happen.
+	 */		
+	if (!max_blocks) {
+		MD_BUG();
+		return 0;
+	}
+	res = resync*100/max_blocks;
+	sz += sprintf(page + sz, " resync=%u%%", res);
+
+	/*
+	 * We do not want to overflow, so the order of operands and
+	 * the * 100 / 100 trick are important. We do a +1 to be
+	 * safe against division by zero. We only estimate anyway.
+	 *
+	 * dt: time until now
+	 * tt: total time
+	 * et: estimated finish time
+	 */
+	dt = ((jiffies - mddev->resync_start) / HZ);
+	tt = (dt * (max_blocks / (resync/100+1)))/100;
+	et = tt - dt;
+	
+	sz += sprintf(page + sz, " finish=%u.%umin", et / 60, (et % 60)/6);
+
+	return sz;
+}
+
+int get_md_status (char *page)
+{
+	int sz = 0, i, size;
+	struct md_list_head *tmp;
+	mdk_rdev_t *rdev;
+
+	sz += sprintf(page + sz, "Personalities : ");
+	for (i = 0; i < MAX_PERSONALITY; i++)
+	if (pers[i])
+		sz += sprintf(page+sz, "[%s] ", pers[i]->name);
+
+	sz += sprintf(page+sz, "\n");
+
+
+	sz += sprintf(page+sz, "read_ahead ");
+	if (read_ahead[MD_MAJOR] == INT_MAX)
+		sz += sprintf(page+sz, "not set\n");
+	else
+		sz += sprintf(page+sz, "%d sectors\n", read_ahead[MD_MAJOR]);
+  
+	for (i = 0; i < MAX_MD_DEV; i++) {
+		mddev_t * mddev = md_arrays + i;
+
+		sz += sprintf(page + sz, "md%d : %sactive", i,
+						mddev->pers ? "" : "in");
+		if (mddev->pers) {
+			if (mddev->ro)	
+				sz += sprintf(page + sz, " (read-only)");
+			sz += sprintf(page + sz, " %s", mddev->pers->name);
+		}
+
+		size = 0;
+		ITERATE_RDEV(mddev,rdev,tmp) {
+			sz += sprintf(page + sz, " %s[%d]",
+				partition_name(rdev->dev), rdev->desc_nr);
+			if (rdev->faulty) {
+				sz += sprintf(page + sz, "(F)");
+				continue;
+			}
+			size += rdev->size;
+		}
+
+		if (mddev->nb_dev) {
+			if (mddev->pers)
+				sz += sprintf(page + sz, " %d blocks",
+								 md_size[i]);
+			else
+				sz += sprintf(page + sz, " %d blocks", size);
+		}
+
+		if (!mddev->pers) {
+			sz += sprintf(page+sz, "\n");
+			continue;
+		}
+
+		sz += mddev->pers->status (page+sz, mddev);
+
+		if (mddev->curr_resync)
+			sz += status_resync (page+sz, mddev);
+
+		sz += sprintf(page + sz, "\n");
+	}
+	sz += status_unused (page + sz);
+
+	return (sz);
+}
+
+int register_md_personality (int pnum, mdk_personality_t *p)
+{
+	if (pnum >= MAX_PERSONALITY)
+		return -EINVAL;
+
+	if (pers[pnum])
+		return -EBUSY;
+  
+	pers[pnum] = p;
+	printk(KERN_INFO "%s personality registered\n", p->name);
+	return 0;
+}
+
+int unregister_md_personality (int pnum)
+{
+	if (pnum >= MAX_PERSONALITY)
+		return -EINVAL;
+
+	printk(KERN_INFO "%s personality unregistered\n", pers[pnum]->name);
+	pers[pnum] = NULL;
+	return 0;
+} 
+
+static mdp_disk_t *get_spare(mddev_t *mddev)
+{
+	mdp_super_t *sb = mddev->sb;
+	mdp_disk_t *disk;
+	mdk_rdev_t *rdev;
+	struct md_list_head *tmp;
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty)
+			continue;
+		if (!rdev->sb) {
+			MD_BUG();
+			continue;
+		}
+		disk = &sb->disks[rdev->desc_nr];
+		if (disk_faulty(disk)) {
+			MD_BUG();
+			continue;
+		}
+		if (disk_active(disk))
+			continue;
+		return disk;
+	}
+	return NULL;
+}
+
+/*
+ * This function knows that we do a linear pass over the whole array,
+ * so we can drop all unused buffers. Careful, bforget alone is
+ * unsafe, we must be 100% sure that at the end of bforget() we will
+ * really have no (new) users of this buffer.
+ *
+ * this logic improves overall system performance greatly during array
+ * resync or reconstruction. Actually, the reconstruction is basically
+ * seemless.
+ */
+static void cache_drop_behind(struct buffer_head *bh)
+{
+	unsigned long flags;
+	save_flags(flags);
+	cli();
+	
+	if ((bh->b_count == 1) && !buffer_locked(bh) &&
+			buffer_uptodate(bh) && !buffer_dirty(bh))
+		bforget(bh);
+	else
+		brelse(bh);
+
+	restore_flags(flags);
+}
+
+static int is_mddev_idle (mddev_t *mddev)
+{
+	mdk_rdev_t * rdev;
+	struct md_list_head *tmp;
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (!is_device_idle(rdev->dev))
+			return 0;
+	}
+	return 1;
+}
+
+/*
+ * parallel resyncing thread. 
+ */
+
+int md_do_sync(mddev_t *mddev, mdp_disk_t *spare)
+{
+        struct buffer_head *bh;
+	unsigned int max_blocks, blocksize, curr_bsize, j;
+	kdev_t read_disk = mddev_to_kdev(mddev);
+	int major = MAJOR(read_disk), minor = MINOR(read_disk);
+	unsigned long starttime;
+	int max_read_errors = 10, max_write_errors = 10;
+	int is_idle = 0;
+
+	blocksize = blksize_size[major][minor];
+	max_blocks = blk_size[major][minor] / (blocksize >> 10);
+
+	printk(KERN_INFO "md: syncing RAID array md%d\n", mdidx(mddev));
+	printk(KERN_INFO "md: using idle IO bandwith for reconstruction.\n");
+	printk(KERN_INFO "md: minimum reconstruction speed: %d KB/sec.\n",
+						SPEED_LIMIT);
+
+	/*
+	 * resync is lower priority than any of the other system
+	 * threads
+	 */
+	current->rt_priority = 0;
+
+	starttime = jiffies;
+	mddev->resync_start = starttime;
+	for (j = 0; j < max_blocks; j++) {
+
+		/*
+		 * B careful. When some1 mounts a non-'blocksize' filesystem
+		 * then we get the blocksize changed right under us. Go deal
+		 * with it transparently, recalculate 'blocksize', 'j' and
+		 * 'max_blocks':
+		 */
+		curr_bsize = blksize_size[major][minor];
+		if (curr_bsize != blocksize) {
+retry_read:
+			if (curr_bsize > blocksize)
+				/*
+				 * this is safe, rounds downwards.
+				 */
+				j /= curr_bsize/blocksize;
+			else
+				j *= blocksize/curr_bsize;
+
+			blocksize = curr_bsize;
+			max_blocks = blk_size[major][minor] / (blocksize >> 10);
+		}
+        	bh = breada_blocks(read_disk, j, blocksize, max_blocks);
+        	if (bh) {
+			if (!buffer_uptodate(bh))
+				goto read_error;
+			/*
+			 * mark it dirty and let the buffer cache generate
+			 * a writeback, this is where we reconstruct the
+			 * missing data
+			 */
+retry_write:
+			mark_buffer_dirty(bh, 1);
+			wait_on_buffer(bh);
+			if (spare && disk_faulty(spare)) {
+				printk(" <SPARE FAILED!>\n ");
+				mddev->curr_resync = 0;
+				return -EIO;
+			}
+			if (!buffer_uptodate(bh)) {
+				printk(" BAD WRITE %8d>\n", j);
+				/*
+				 * Ouch, write error, retry or bail out.
+				 */
+				if (max_write_errors) {
+					max_write_errors--;
+					printk ( KERN_WARNING "md%d: write error while reconstructing, at block %u(%d).\n", mdidx(mddev), j, blocksize);
+					goto retry_write;
+				}
+				printk ( KERN_ALERT
+				  "too many write errors, stopping reconstruction.\n");
+				brelse(bh);
+				mddev->curr_resync = 0;
+				return -EIO;
+			}
+			/*
+			 * This is the normal 'everything went OK' case
+			 * do a 'free-behind' logic, we sure dont need
+			 * this buffer if it was the only user.
+			 */
+			cache_drop_behind(bh);
+		} else {
+			/*
+			 * set_blocksize() might change the blocksize. This
+			 * should not happen often, but it happens when eg.
+			 * someone mounts a filesystem that has non-1k
+			 * blocksize. set_blocksize() doesnt touch our
+			 * buffer, but to avoid aliasing problems we change
+			 * our internal blocksize too and retry the read.
+			 */
+			curr_bsize = blksize_size[major][minor];
+			if (curr_bsize != blocksize) {
+				printk(KERN_INFO "md%d: blocksize changed\n",
+					mdidx(mddev));
+				brelse(bh);
+				goto retry_read;
+			}
+
+read_error:
+			/*
+			 * It's a real read problem. We retry and bail out
+			 * only if it's excessive.
+			 */
+			if (max_read_errors) {
+				max_read_errors--;
+				printk ( KERN_WARNING "md%d: read error while reconstructing, at block %u(%d).\n", mdidx(mddev), j, blocksize);
+				goto retry_read;
+			}
+			printk ( KERN_ALERT
+			  "too many read errors, stopping reconstruction.\n");
+			brelse(bh);
+			mddev->curr_resync = 0;
+			return -EIO;
+		}
+		if (md_signal_pending(current)) {
+			/*
+			 * got a signal, exit.
+			 */
+			mddev->curr_resync = 0;
+			printk("md_do_sync() got signal ... exiting\n");
+			return -EINTR;
+		}
+
+		mddev->curr_resync = j;
+		/*
+		 * this loop exits only if either when we are slower than
+		 * the 'hard' speed limit, or the system was IO-idle for
+		 * a jiffy.
+		 * the system might be non-idle CPU-wise, but we only care
+		 * about not overloading the IO subsystem. (things like an
+		 * e2fsck being done on the RAID array should execute fast)
+		 */
+		while (blocksize*j/(jiffies-starttime+1)*HZ/1024 > SPEED_LIMIT)
+		{
+			if (is_mddev_idle(mddev)) {
+				if (is_idle)
+					break;
+				is_idle = 1;
+			} else
+				is_idle = 0;
+
+			current->state = TASK_INTERRUPTIBLE;
+			current->timeout = jiffies+HZ/10;
+			schedule();
+		}
+	}
+	fsync_dev(read_disk);
+	printk(KERN_INFO "md: md%d: sync done.\n",mdidx(mddev));
+	/*
+	 * this also signals 'finished resyncing' to md_stop
+	 */
+	mddev->curr_resync = 0;
+	return 0;
+}
+
+/*
+ * This is a kernel thread which syncs a spare disk with the active array
+ *
+ * the amount of foolproofing might seem to be a tad excessive, but an
+ * early (not so error-safe) version of raid1syncd synced the first 0.5 gigs
+ * of my root partition with the first 0.5 gigs of my /home partition ... so
+ * i'm a bit nervous ;)
+ */
+void md_do_recovery (void *data)
+{
+	int i, err;
+	mddev_t *mddev;
+	mdp_super_t *sb;
+	mdp_disk_t *spare;
+	unsigned long flags;
+
+	printk(KERN_INFO "md: recovery thread got woken up ...\n");
+	for (i = 0, mddev = md_arrays; i < MAX_MD_DEV; i++, mddev++) {
+		if ((sb = mddev->sb) == NULL)
+			continue;
+		if (mddev->recovery_running)
+			continue;
+		if (sb->active_disks == sb->raid_disks)
+			continue;
+		if (!sb->spare_disks) {
+			printk(KERN_ERR "md%d: no spare disk to reconstruct array! -- continuing in degraded mode\n", mdidx(mddev));
+			continue;
+		}
+		/*
+		 * now here we get the spare and resync it.
+		 */
+		if ((spare = get_spare(mddev)) == NULL)
+			continue;
+		printk(KERN_INFO "md%d: resyncing spare disk %s to replace failed disk\n", mdidx(mddev), partition_name(MKDEV(spare->major,spare->minor)));
+		if (!mddev->pers->diskop)
+			continue;
+		if (mddev->pers->diskop(mddev, &spare, DISKOP_SPARE_WRITE))
+			continue;
+		down(&mddev->recovery_sem);
+		mddev->recovery_running = 1;
+		err = md_do_sync(mddev, spare);
+		if (err == -EIO) {
+			printk(KERN_INFO "md%d: spare disk %s failed, skipping to next spare.\n", mdidx(mddev), partition_name(MKDEV(spare->major,spare->minor)));
+			if (!disk_faulty(spare)) {
+				mddev->pers->diskop(mddev,&spare,DISKOP_SPARE_INACTIVE);
+				mark_disk_faulty(spare);
+				mark_disk_nonsync(spare);
+				mark_disk_inactive(spare);
+				sb->spare_disks--;
+				sb->working_disks--;
+				sb->failed_disks++;
+			}
+		} else
+			if (disk_faulty(spare))
+				mddev->pers->diskop(mddev, &spare,
+						DISKOP_SPARE_INACTIVE);
+		if (err == -EINTR) {
+			/*
+			 * Recovery got interrupted ...
+			 * signal back that we have finished using the array.
+			 */
+			mddev->pers->diskop(mddev, &spare,
+							 DISKOP_SPARE_INACTIVE);
+			up(&mddev->recovery_sem);
+			/*
+			 * we keep 'recovery_running == 1', so we will not
+			 * start a reconstruction next time around ...
+			 * the stop code will set it to 0 explicitly.
+			 */
+			continue;
+		} else {
+			mddev->recovery_running = 0;
+			up(&mddev->recovery_sem);
+		}
+		save_flags(flags);
 		cli();
-		if (!test_bit(THREAD_WAKEUP, &thread->flags))
-			interruptible_sleep_on(&thread->wqueue);
+		if (!disk_faulty(spare)) {
+			/*
+			 * the SPARE_ACTIVE diskop possibly changes the
+			 * pointer too
+			 */
+			mddev->pers->diskop(mddev, &spare, DISKOP_SPARE_ACTIVE);
+			mark_disk_sync(spare);
+			mark_disk_active(spare);
+			sb->active_disks++;
+			sb->spare_disks--;
+		}
+		mddev->sb_dirty = 1;
+		md_update_sb(mddev);
+		restore_flags(flags);
+	}
+	printk(KERN_INFO "md: recovery thread finished ...\n");
+	
+}
+
+int md_notify_reboot(struct notifier_block *this,
+					unsigned long code, void *x)
+{
+	int i, err;
+
+	if ((code == MD_SYS_DOWN) || (code == MD_SYS_HALT)) {
+		printk(KERN_INFO "stopping all md devices.\n");
+		for (i = 0; i < MAX_MD_DEV; i++)
+			err = do_md_stop (md_arrays + i, 1);
+		/*
+		 * certain more exotic SCSI devices are known to be
+		 * volatile wrt too early system reboots. While the
+		 * right place to handle this issue is the given
+		 * driver, we do want to have a safe RAID driver ...
+		 */
+		md_mdelay(1000*1);
+	}
+	return NOTIFY_DONE;
+}
+
+struct notifier_block md_notifier = {
+	md_notify_reboot,
+	NULL,
+	0
+};
+
+md__initfunc(void raid_setup(char *str,int *ints))
+{
+	printk("nothing yet ...\n");
+}
+
+#ifdef CONFIG_MD_BOOT
+struct {
+	int set;
+	int ints[100];
+	char str[100];
+} md_setup_args md__initdata = {
+	0,{0},{0}
+};
+
+/* called from init/main.c */
+md__initfunc(void md_setup(char *str,int *ints))
+{
+	int i;
+	for(i=0;i<=ints[0];i++) {
+		md_setup_args.ints[i] = ints[i];
+		strcpy(md_setup_args.str, str);
+/*      printk ("md: ints[%d]=%d.\n", i, ints[i]);*/
+	}
+	md_setup_args.set=1;
+	return;
+}
+
+md__initfunc(void do_md_setup(char *str,int *ints))
+{
+#if 0
+	int minor, pers, chunk_size, fault;
+	kdev_t dev;
+	int i=1;
+
+	printk("i plan to phase this out --mingo\n");
+
+	if(ints[0] < 4) {
+		printk (KERN_WARNING "md: Too few Arguments (%d).\n", ints[0]);
+		return;
+	}
+   
+	minor=ints[i++];
+   
+	if ((unsigned int)minor >= MAX_MD_DEV) {
+		printk (KERN_WARNING "md: Minor device number too high.\n");
+		return;
+	}
+
+	pers = 0;
+	
+	switch(ints[i++]) {  /* Raidlevel  */
+	case -1:
+#ifdef CONFIG_MD_LINEAR
+		pers = LINEAR;
+		printk (KERN_INFO "md: Setting up md%d as linear device.\n",
+									minor);
+#else 
+	        printk (KERN_WARNING "md: Linear mode not configured." 
+			"Recompile the kernel with linear mode enabled!\n");
+#endif
+		break;
+	case 0:
+		pers = STRIPED;
+#ifdef CONFIG_MD_STRIPED
+		printk (KERN_INFO "md: Setting up md%d as a striped device.\n",
+								minor);
+#else 
+	        printk (KERN_WARNING "md: Striped mode not configured." 
+			"Recompile the kernel with striped mode enabled!\n");
+#endif
+		break;
+/*      not supported yet
+	case 1:
+		pers = RAID1;
+		printk ("md: Setting up md%d as a raid1 device.\n",minor);
+		break;
+	case 5:
+		pers = RAID5;
+		printk ("md: Setting up md%d as a raid5 device.\n",minor);
+		break;
+*/
+	default:	   
+		printk (KERN_WARNING "md: Unknown or not supported raid level %d.\n", ints[--i]);
+		return;
+	}
+
+	if (pers) {
+
+		chunk_size = ints[i++]; /* Chunksize  */
+		fault = ints[i++]; /* Faultlevel */
+   
+		pers = pers | chunk_size | (fault << FAULT_SHIFT);   
+   
+		while( str && (dev = name_to_kdev_t(str))) {
+			do_md_add (minor, dev);
+			if((str = strchr (str, ',')) != NULL)
+				str++;
+		}
+
+		do_md_run (minor, pers);
+		printk (KERN_INFO "md: Loading md%d.\n",minor);
 	}
+#endif
 }
+#endif
 
 void linear_init (void);
 void raid0_init (void);
 void raid1_init (void);
 void raid5_init (void);
 
-int md_init (void)
+md__initfunc(int md_init (void))
 {
-  int i;
+	static char * name = "mdrecoveryd";
+
+	printk (KERN_INFO "md driver %d.%d.%d MAX_MD_DEV=%d, MAX_REAL=%d\n",
+			MD_MAJOR_VERSION, MD_MINOR_VERSION,
+			MD_PATCHLEVEL_VERSION, MAX_MD_DEV, MAX_REAL);
+
+	if (register_blkdev (MD_MAJOR, "md", &md_fops))
+	{
+		printk (KERN_ALERT "Unable to get major %d for md\n", MD_MAJOR);
+		return (-1);
+	}
 
-  printk ("md driver %d.%d.%d MAX_MD_DEV=%d, MAX_REAL=%d\n",
-    MD_MAJOR_VERSION, MD_MINOR_VERSION, MD_PATCHLEVEL_VERSION,
-    MAX_MD_DEV, MAX_REAL);
-
-  if (register_blkdev (MD_MAJOR, "md", &md_fops))
-  {
-    printk ("Unable to get major %d for md\n", MD_MAJOR);
-    return (-1);
-  }
-
-  for (i = 0; i < MAX_MD_THREADS; i++) {
-    md_threads[i].run = NULL;
-    init_waitqueue(&md_threads[i].wqueue);
-    md_threads[i].flags = 0;
-    kernel_thread (md_thread, md_threads + i, 0);
-  }
-
-  blk_dev[MD_MAJOR].request_fn=DEVICE_REQUEST;
-  blk_dev[MD_MAJOR].current_request=NULL;
-  read_ahead[MD_MAJOR]=INT_MAX;
-  memset(md_dev, 0, MAX_MD_DEV * sizeof (struct md_dev));
-  md_gendisk.next=gendisk_head;
+	blk_dev[MD_MAJOR].request_fn = DEVICE_REQUEST;
+	blk_dev[MD_MAJOR].current_request = NULL;
+	read_ahead[MD_MAJOR] = INT_MAX;
+	memset(md_arrays, 0, MAX_MD_DEV * sizeof (mddev_t));
+	md_gendisk.next = gendisk_head;
+
+	gendisk_head = &md_gendisk;
+
+	md_recovery_thread = md_register_thread(md_do_recovery, NULL, name);
+	if (!md_recovery_thread)
+		printk(KERN_ALERT "bug: couldn't allocate md_recovery_thread\n");
 
-  gendisk_head=&md_gendisk;
+	md_register_reboot_notifier(&md_notifier);
 
 #ifdef CONFIG_MD_LINEAR
-  linear_init ();
+	linear_init ();
 #endif
 #ifdef CONFIG_MD_STRIPED
-  raid0_init ();
+	raid0_init ();
 #endif
 #ifdef CONFIG_MD_MIRRORING
-  raid1_init ();
+	raid1_init ();
 #endif
 #ifdef CONFIG_MD_RAID5
-  raid5_init ();
+	raid5_init ();
+#endif
+#if defined(CONFIG_MD_RAID5) || defined(CONFIG_MD_RAID5_MODULE)
+        /*
+         * pick a XOR routine, runtime.
+         */
+	calibrate_xor_block();
+#endif
+
+	return (0);
+}
+
+#ifdef CONFIG_MD_BOOT
+md__initfunc(void md_setup_drive(void))
+{
+	if(md_setup_args.set)
+		do_md_setup(md_setup_args.str, md_setup_args.ints);
+}
 #endif
+
+MD_EXPORT_SYMBOL(md_size);
+MD_EXPORT_SYMBOL(register_md_personality);
+MD_EXPORT_SYMBOL(unregister_md_personality);
+MD_EXPORT_SYMBOL(partition_name);
+MD_EXPORT_SYMBOL(md_arrays);
+MD_EXPORT_SYMBOL(md_error);
+MD_EXPORT_SYMBOL(md_recover_arrays);
+MD_EXPORT_SYMBOL(md_register_thread);
+MD_EXPORT_SYMBOL(md_unregister_thread);
+MD_EXPORT_SYMBOL(md_update_sb);
+MD_EXPORT_SYMBOL(md_map);
+MD_EXPORT_SYMBOL(md_wakeup_thread);
+MD_EXPORT_SYMBOL(md_do_sync);
+MD_EXPORT_SYMBOL(md_print_devices);
+MD_EXPORT_SYMBOL(find_rdev_nr);
+MD_EXPORT_SYMBOL(md_check_ordering);
+
+#ifdef CONFIG_PROC_FS
+static struct proc_dir_entry proc_md = {
+	PROC_MD, 6, "mdstat",
+	S_IFREG | S_IRUGO, 1, 0, 0,
+	0, &proc_array_inode_operations,
+};
+#endif
+
+static void md_geninit (struct gendisk *gdisk)
+{
+	int i;
   
-  return (0);
+	for(i = 0; i < MAX_MD_DEV; i++) {
+		md_blocksizes[i] = 1024;
+		md_maxreadahead[i] = MD_READAHEAD;
+		md_gendisk.part[i].start_sect = -1; /* avoid partition check */
+		md_gendisk.part[i].nr_sects = 0;
+		memset(md_arrays+i, 0, sizeof(mddev_t));
+		md_arrays[i].__minor = i;
+		md_arrays[i].recovery_sem = MUTEX;
+		MD_INIT_LIST_HEAD(&md_arrays[i].disks);
+	}
+
+	blksize_size[MD_MAJOR] = md_blocksizes;
+	md_set_global_readahead(md_maxreadahead);
+
+#ifdef CONFIG_PROC_FS
+	proc_register(&proc_root, &proc_md);
+#endif
 }
+
--- linux/drivers/block/raid1.c.orig	Mon Aug  3 20:40:05 1998
+++ linux/drivers/block/raid1.c	Fri Feb  2 01:14:53 1996
@@ -1,6 +1,6 @@
-/************************************************************************
+/*
  * raid1.c : Multiple Devices driver for Linux
- *           Copyright (C) 1996 Ingo Molnar, Miguel de Icaza, Gadi Oxman
+ * Copyright (C) 1996, 1997, 1998 Ingo Molnar, Miguel de Icaza, Gadi Oxman
  *
  * RAID-1 management functions.
  *
@@ -15,48 +15,52 @@
  */
 
 #include <linux/module.h>
-#include <linux/locks.h>
 #include <linux/malloc.h>
-#include <linux/md.h>
-#include <linux/raid1.h>
-#include <asm/bitops.h>
+#include <linux/raid/raid1.h>
 #include <asm/atomic.h>
 
 #define MAJOR_NR MD_MAJOR
 #define MD_DRIVER
 #define MD_PERSONALITY
 
-/*
- * The following can be used to debug the driver
- */
-/*#define RAID1_DEBUG*/
-#ifdef RAID1_DEBUG
-#define PRINTK(x)   do { printk x; } while (0);
-#else
-#define PRINTK(x)   do { ; } while (0);
-#endif
+#define MAX_LINEAR_SECTORS 2048
 
+#define MAX(a,b)	((a) > (b) ? (a) : (b))
+#define MIN(a,b)	((a) < (b) ? (a) : (b))
 
-static struct md_personality raid1_personality;
-static struct md_thread *raid1_thread = NULL;
+static mdk_personality_t raid1_personality;
 struct buffer_head *raid1_retry_list = NULL;
 
-static int __raid1_map (struct md_dev *mddev, kdev_t *rdev,
+static void * raid1_kmalloc (int size)
+{
+	void * ptr;
+	/*
+	 * FIXME: now we are rather fault tolerant than nice, but
+	 * there are a couple of places in the RAID code where we
+	 * simply can not afford to fail an allocation because
+	 * there is no failure return path (eg. make_request())
+	 */
+	while (!(ptr = kmalloc (sizeof (raid1_conf_t), GFP_KERNEL)))
+		printk ("raid1: out of memory, retrying...\n");
+
+	memset(ptr, 0, size);
+	return ptr;
+}
+
+static int __raid1_map (mddev_t *mddev, kdev_t *rdev,
 		        unsigned long *rsector, unsigned long size)
 {
-	struct raid1_data *raid_conf = (struct raid1_data *) mddev->private;
-	int i, n = raid_conf->raid_disks;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+	int i, disks = MD_SB_DISKS /*conf->nr_disks FIXME */;
 
 	/*
 	 * Later we do read balancing on the read side 
 	 * now we use the first available disk.
 	 */
 
-	PRINTK(("raid1_map().\n"));
-
-	for (i=0; i<n; i++) {
-		if (raid_conf->mirrors[i].operational) {
-			*rdev = raid_conf->mirrors[i].dev;
+	for (i = 0; i < disks; i++) {
+		if (conf->mirrors[i].operational) {
+			*rdev = conf->mirrors[i].dev;
 			return (0);
 		}
 	}
@@ -65,51 +69,43 @@
 	return (-1);
 }
 
-static int raid1_map (struct md_dev *mddev, kdev_t *rdev,
+static int raid1_map (mddev_t *mddev, kdev_t *rdev,
 		      unsigned long *rsector, unsigned long size)
 {
 	return 0;
 }
 
-void raid1_reschedule_retry (struct buffer_head *bh)
+static void raid1_reschedule_retry (struct buffer_head *bh)
 {
-	struct raid1_bh * r1_bh = (struct raid1_bh *)(bh->private_bh);
-
-	PRINTK(("raid1_reschedule_retry().\n"));
+	struct raid1_bh * r1_bh = (struct raid1_bh *)(bh->b_dev_id);
+	mddev_t *mddev = r1_bh->mddev;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
 
 	r1_bh->next_retry = raid1_retry_list;
 	raid1_retry_list = bh;
-	md_wakeup_thread(raid1_thread);
+	md_wakeup_thread(conf->thread);
 }
 
 /*
- * raid1_end_buffer_io() is called when we have finished servicing a mirrored
- * operation and are ready to return a success/failture code to the buffer
+ * raid1_end_bh_io() is called when we have finished servicing a mirrored
+ * operation and are ready to return a success/failure code to the buffer
  * cache layer.
  */
-static inline void raid1_end_buffer_io (struct buffer_head *bh, int uptodate)
+static void raid1_end_bh_io (struct raid1_bh *r1_bh, int uptodate)
 {
-	/*
-	 * kfree() can sleep and we try to keep this bh operation atomic.
-	 */
-	struct raid1_bh * tmp = (struct raid1_bh *) bh->private_bh;
+	struct buffer_head *bh = r1_bh->master_bh;
 
-	clear_bit (BH_MD, &bh->b_state);
-	bh->private_bh = NULL;
-	bh->personality = NULL;
-	mark_buffer_uptodate(bh, uptodate);
-	unlock_buffer(bh);
-	kfree(tmp);
+	bh->b_end_io(bh, uptodate);
+	kfree(r1_bh);
 }
 
 void raid1_end_request (struct buffer_head *bh, int uptodate)
 {
-	struct raid1_bh * r1_bh = (struct raid1_bh *)(bh->private_bh);
+	struct raid1_bh * r1_bh = (struct raid1_bh *)(bh->b_dev_id);
 	unsigned long flags;
 
 	save_flags(flags);
 	cli();
-	PRINTK(("raid1_end_request().\n"));
 
 	/*
 	 * this branch is our 'one mirror IO has finished' event handler:
@@ -135,15 +131,11 @@
 	 */
 
 	if ( (r1_bh->cmd == READ) || (r1_bh->cmd == READA) ) {
-
-		PRINTK(("raid1_end_request(), read branch.\n"));
-
 		/*
 		 * we have only one buffer_head on the read side
 		 */
 		if (uptodate) {
-			PRINTK(("raid1_end_request(), read branch, uptodate.\n"));
-			raid1_end_buffer_io (bh, uptodate);
+			raid1_end_bh_io(r1_bh, uptodate);
 			restore_flags(flags);
 			return;
 		}
@@ -151,151 +143,58 @@
 		 * oops, read error:
 		 */
 		printk(KERN_ERR "raid1: %s: rescheduling block %lu\n", 
-				 kdevname(bh->b_dev), bh->b_blocknr);
-		raid1_reschedule_retry (bh);
+			 partition_name(bh->b_dev), bh->b_blocknr);
+		raid1_reschedule_retry(bh);
 		restore_flags(flags);
 		return;
 	}
 
 	/*
-	 * WRITE or WRITEA.
-	 */
-	PRINTK(("raid1_end_request(), write branch.\n"));
-
-	/*
-	 * lets see if all mirrored write operations have finished 
+	 * WRITE:
+	 *
+	 * Let's see if all mirrored write operations have finished 
 	 * already [we have irqs off, so we can decrease]:
 	 */
 
 	if (!--r1_bh->remaining) {
-		struct md_dev *mddev = r1_bh->mddev;
-		struct raid1_data *raid_conf = (struct raid1_data *) mddev->private;
-		int i, n = raid_conf->raid_disks;
+		int i, disks = MD_SB_DISKS /*conf->nr_disks FIXME */;
 
-		PRINTK(("raid1_end_request(), remaining == 0.\n"));
+		for ( i = 0; i < disks; i++)
+			if (r1_bh->mirror_bh[i])
+				kfree(r1_bh->mirror_bh[i]);
 
-		/*
-		 * kfree() can sleep? really? if yes then we are
-		 * doomed here ...
-		 */
-		for ( i=0; i<n; i++) {
-			if (r1_bh->mirror_bh[i]) kfree(r1_bh->mirror_bh[i]);
-		}
-
-		/*
-		 * the 'master' bh is the one that is used in page IO,
-		 * perhaps someone is waiting on it. Lets erase all
-		 * signs of mirroring, and lets finish the bh operation:
-		 *
-		 * In particular, the "uptodate" value which we return
-		 * to the higher level represents the entire mirror set.
-		 *
-		 * yes, and this is why i want to use the 'master' bh as
-		 * a 'representative'. Thats why i think it's not clean to
-		 * use the master bh for real IO. We mix concepts, which
-		 * isnt too good.
-		 *
-		 * a buffer_head is basically a user-side file buffer.
-		 * Normally it has direct relationship with the physical
-		 * device, but as in this case, we have an abstract mapping
-		 * between the file buffer and the physical layout. So i've
-		 * reverted all changes that do this mixing.
-		 *
-		 * we 'waste' about 76 bytes for the one more buffer_head,
-		 * but note that we will do the mirror bh allocation at once
-		 * in the future, so this isnt really a valid point, i think.
-		 *
-		 * Also i dont like the current way of mixing the user-side buffer
-		 * concept with the 'real' physical layout like raid0.c does
-		 * now: it increases the size of buffer_head even for nonstriped
-		 * devices, etc.
-		 *
-		 * IMHO, in the future, we should have a lightweight buffer_head
-		 * structure, which holds almost no physical device information.
-		 
-		 * Abstract relationship between buffers:
-		 * ===================================== 
-		 * 
-		 *           [user] 
-		 *              |
-		 *              |
-		 *    ['master' buffer_head] + [private_buffer_head]
-		 *                                      |
-		 *                                      |
-		 *                                      |
-		 *                        [additional 'sub'-buffer_heads]
-		 *                           |          |           | 
-		 *                         [dev1]     [dev2]      [dev3]
-		 * 
- 
-		 * In this scheme it's not clean to use the 'master' as one of
-		 * the 'sub' buffer_heads. If you think about it, currently we can 
-		 * do this only because raid0 introduced it's own private_buffer_head
-		 * structure in buffer_head: rdev,rsector. And raid0 has a 1:1
-		 * relationship to the physical device. But this is really just a
-		 * special case. Once we have our megafast bh pools running, we could
-		 * clean up raid0.c too :))
-		 *
-		 * Not that it isnt clean, it is lethal if in the future we insert our 
-		 * sub buffer_heads into the global block cache. The master request
-		 * should be an IO operation label for the complex operation, nothing
-		 * more.
-		 *
-		 * So we have almost no performance arguments, and alot of cleanness
-		 * arguments.
-		 *
-		 * Comments? Gonna change it back to your way again if you can convince
-		 * me :)) --mingo
-		 *
-		 */
-		raid1_end_buffer_io ( r1_bh->master_bh, 
-				test_bit (BH_Uptodate, &r1_bh->state));
+		raid1_end_bh_io(r1_bh, test_bit(BH_Uptodate, &r1_bh->state));
 	}
-	else PRINTK(("raid1_end_request(), remaining == %u.\n", r1_bh->remaining));
 	restore_flags(flags);
 }
 
-/* This routine checks if the undelying device is an md device and in that
- * case it maps the blocks before putting the request on the queue
+/*
+ * This routine checks if the undelying device is an md device
+ * and in that case it maps the blocks before putting the
+ * request on the queue
  */
-static inline void
-map_and_make_request (int rw, struct buffer_head *bh)
+static void map_and_make_request (int rw, struct buffer_head *bh)
 {
-	if (MAJOR (bh->b_rdev) == MD_MAJOR){
-		md_map (MINOR (bh->b_rdev), &bh->b_rdev, &bh->b_rsector, bh->b_size >> 9);
-	}
+	if (MAJOR (bh->b_rdev) == MD_MAJOR)
+		md_map (MINOR (bh->b_rdev), &bh->b_rdev,
+				&bh->b_rsector, bh->b_size >> 9);
+	clear_bit(BH_Lock, &bh->b_state);
 	make_request (MAJOR (bh->b_rdev), rw, bh);
 }
 	
-static int
-raid1_make_request (struct md_dev *mddev, int rw, struct buffer_head * bh)
+static int raid1_make_request (mddev_t *mddev, int rw,
+						 struct buffer_head * bh)
 {
-
-	struct raid1_data *raid_conf = (struct raid1_data *) mddev->private;
-	struct buffer_head *mirror_bh[MD_SB_DISKS];
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+	struct buffer_head *mirror_bh[MD_SB_DISKS], *bh_req;
 	struct raid1_bh * r1_bh;
-	int n = raid_conf->raid_disks, i, sum_bhs = 0, switch_disks = 0, sectors;
+	int disks = MD_SB_DISKS /*conf->nr_disks FIXME */;
+	int i, sum_bhs = 0, switch_disks = 0, sectors;
 	struct mirror_info *mirror;
 
-	PRINTK(("raid1_make_request().\n"));
+	r1_bh = raid1_kmalloc (sizeof (struct raid1_bh));
 
 /*
- * We put allocations at the beginning, to avoid sleeping while doing
- * atomic operations of buffer heads. This might or might not make much
- * difference, but lets rather be careful.
- *
- * but this has two side effects (probably non harmless):
- *
- *	1.	The buffer will not be locked while we sleep.
- *	2.	The rest of the kernel will see BH_Req without
- *		BH_Lock.
- */
-	while (!( /* FIXME: now we are rather fault tolerant than nice */
-	r1_bh = kmalloc (sizeof (struct raid1_bh), GFP_KERNEL)
-	) )
-		printk ("raid1_make_request(#1): out of memory\n");
-	memset (r1_bh, 0, sizeof (struct raid1_bh));
-/*
  * make_request() can abort the operation when READA or WRITEA are being
  * used and no empty request is available.
  *
@@ -304,76 +203,70 @@
 	if (rw == READA) rw = READ;
 	if (rw == WRITEA) rw = WRITE;
 
-	if (rw == WRITE || rw == WRITEA)
-		mark_buffer_clean(bh);		/* Too early ? */
+	if (rw == WRITE)
+		/*
+		 * Too early ?
+		 */
+		mark_buffer_clean(bh);
+		/*
+		 * not too early. we _first_ clean the bh, then we start
+		 * the IO, then when the IO has finished, we unlock the
+		 * bh and mark it uptodate. This way we do not miss the
+		 * case when the bh got dirty again during the IO.
+		 */
 
 /*
- * i think the read and write branch should be separated completely, since we want
- * to do read balancing on the read side for example. Comments? :) --mingo
+ * i think the read and write branch should be separated completely,
+ * since we want to do read balancing on the read side for example.
+ * Comments? :) --mingo
  */
 
 	r1_bh->master_bh=bh;
 	r1_bh->mddev=mddev;
 	r1_bh->cmd = rw;
 
-	set_bit (BH_MD,	&bh->b_state);
-	bh->personality  = &raid1_personality;
-	bh->private_bh   = (void*)(r1_bh);
-
-	if (rw==READ || rw==READA) {
-		int last_used = raid_conf->last_used;
-		PRINTK(("raid1_make_request(), read branch.\n"));
-		mirror = raid_conf->mirrors + last_used;
+	if (rw==READ) {
+		int last_used = conf->last_used;
+
+		/*
+		 * read balancing logic:
+		 */
+		mirror = conf->mirrors + last_used;
 		bh->b_rdev = mirror->dev;
 		sectors = bh->b_size >> 9;
-		if (bh->b_blocknr * sectors == raid_conf->next_sect) {
-			raid_conf->sect_count += sectors;
-			if (raid_conf->sect_count >= mirror->sect_limit)
+
+		if (bh->b_blocknr * sectors == conf->next_sect) {
+			conf->sect_count += sectors;
+			if (conf->sect_count >= mirror->sect_limit)
 				switch_disks = 1;
 		} else
 			switch_disks = 1;
-		raid_conf->next_sect = (bh->b_blocknr + 1) * sectors;
+		conf->next_sect = (bh->b_blocknr + 1) * sectors;
 		if (switch_disks) {
-			PRINTK(("read-balancing: switching %d -> %d (%d sectors)\n", last_used, mirror->next, raid_conf->sect_count));
-			raid_conf->sect_count = 0;
-			raid_conf->last_used = mirror->next;
+			conf->sect_count = 0;
+			last_used = conf->last_used = mirror->next;
+			/*
+			 * Do not switch to write-only disks ... resyncing
+			 * is in progress
+			 */
+			while (conf->mirrors[last_used].write_only)
+				conf->last_used = conf->mirrors[last_used].next;
 		}
-		PRINTK (("raid1 read queue: %d %d\n", MAJOR (bh->b_rdev), MINOR (bh->b_rdev)));
-
-		clear_bit (BH_Lock, &bh->b_state);
-		map_and_make_request (rw, bh);
+		bh_req = &r1_bh->bh_req;
+		memcpy(bh_req, bh, sizeof(*bh));
+		bh_req->b_end_io = raid1_end_request;
+		bh_req->b_dev_id = r1_bh;
+		map_and_make_request (rw, bh_req);
 		return 0;
 	}
 
 	/*
-	 * WRITE or WRITEA.
+	 * WRITE:
 	 */
-/*
- * btw, we have no more master disk. 'slave' is gone too :) [i hate that word :))]
- *
- * We are now using the master bh for a real IO. It seems important that:
- *
- * 1.	lock_buffer() will be called when we start to handle the request,
- *	before we do anything (done by ll_rw_blk.c).
- *
- * 2.	It seems that Linus took great care to set mark_buffer_clean()
- *	atomically with cli() in effect just when the buffer was placed
- *	into the queue. To be compatible with this behavior, it would be
- *	best to lock the buffer *first*, but mark it clean *last*, and to
- *	do this by passing through the exact logic in ll_rw_blk.c.
- *
- * Note: i've reverted this #3 thing, see the big comment in this file.
- *
- * 3.	We are now called from within make_request(), so the real bh
- *	will be automatically handled last when we return, so we only need
- *	to add the rest of the buffers (but remember to include the
- *	master bh in the remaining count).
- */
-	PRINTK(("raid1_make_request(n=%d), write branch.\n",n));
 
-	for (i = 0; i < n; i++) {
+	for (i = 0; i < disks; i++) {
 
-		if (!raid_conf->mirrors [i].operational) {
+		if (!conf->mirrors [i].operational) {
 			/*
 			 * the r1_bh->mirror_bh[i] pointer remains NULL
 			 */
@@ -385,36 +278,30 @@
 	 * We should use a private pool (size depending on NR_REQUEST),
 	 * to avoid writes filling up the memory with bhs
 	 *
-	 * Such pools are much faster than kmalloc anyways (so we waste almost 
-	 * nothing by not using the master bh when writing and win alot of cleanness)
-	 *
-	 * but for now we are cool enough. --mingo
+	 * Such pools are much faster than kmalloc anyways (so we waste
+	 * almost nothing by not using the master bh when writing and
+	 * win alot of cleanness) but for now we are cool enough. --mingo
 	 *
 	 * It's safe to sleep here, buffer heads cannot be used in a shared
-	 * manner in the write branch. Look how we lock the buffer at the beginning
-	 * of this function to grok the difference ;)
+	 * manner in the write branch. Look how we lock the buffer at the
+	 * beginning of this function to grok the difference ;)
 	 */
-		while (!( /* FIXME: now we are rather fault tolerant than nice */
-		mirror_bh[i] = kmalloc (sizeof (struct buffer_head), GFP_KERNEL)
-		) )
-			printk ("raid1_make_request(#2): out of memory\n");
-		memset (mirror_bh[i], 0, sizeof (struct buffer_head));
-
+		mirror_bh[i] = raid1_kmalloc(sizeof(struct buffer_head));
 	/*
 	 * prepare mirrored bh (fields ordered for max mem throughput):
 	 */
 		mirror_bh [i]->b_blocknr    = bh->b_blocknr;
 		mirror_bh [i]->b_dev        = bh->b_dev;
-		mirror_bh [i]->b_rdev 	    = raid_conf->mirrors [i].dev;
+		mirror_bh [i]->b_rdev 	    = conf->mirrors [i].dev;
 		mirror_bh [i]->b_rsector    = bh->b_rsector;
-		mirror_bh [i]->b_state      =   (1<<BH_MD)      | (1<<BH_Req) | 
+		mirror_bh [i]->b_state      =   (1<<BH_Req) | 
 						(1<<BH_Touched) | (1<<BH_Dirty);
 		mirror_bh [i]->b_count      = 1;
 		mirror_bh [i]->b_size       = bh->b_size;
 		mirror_bh [i]->b_data       = bh->b_data;
 		mirror_bh [i]->b_list       = BUF_LOCKED;
-		mirror_bh [i]->personality  = &raid1_personality;
-		mirror_bh [i]->private_bh   = (void*)(r1_bh);
+		mirror_bh [i]->b_end_io     = raid1_end_request;
+		mirror_bh [i]->b_dev_id     = r1_bh;
 
 		r1_bh->mirror_bh[i] = mirror_bh[i];
 		sum_bhs++;
@@ -422,159 +309,593 @@
 
 	r1_bh->remaining = sum_bhs;
 
-	PRINTK(("raid1_make_request(), write branch, sum_bhs=%d.\n",sum_bhs));
-
 	/*
-	 * We have to be a bit careful about the semaphore above, thats why we
-	 * start the requests separately. Since kmalloc() could fail, sleep and
-	 * make_request() can sleep too, this is the safer solution. Imagine,
-	 * end_request decreasing the semaphore before we could have set it up ...
-	 * We could play tricks with the semaphore (presetting it and correcting
-	 * at the end if sum_bhs is not 'n' but we have to do end_request by hand
-	 * if all requests finish until we had a chance to set up the semaphore
-	 * correctly ... lots of races).
+	 * We have to be a bit careful about the semaphore above, thats
+	 * why we start the requests separately. Since kmalloc() could
+	 * fail, sleep and make_request() can sleep too, this is the
+	 * safer solution. Imagine, end_request decreasing the semaphore
+	 * before we could have set it up ... We could play tricks with
+	 * the semaphore (presetting it and correcting at the end if
+	 * sum_bhs is not 'n' but we have to do end_request by hand if
+	 * all requests finish until we had a chance to set up the
+	 * semaphore correctly ... lots of races).
 	 */
-	for (i = 0; i < n; i++)
+	for (i = 0; i < disks; i++)
 		if (mirror_bh [i] != NULL)
 			map_and_make_request (rw, mirror_bh [i]);
 
 	return (0);
 }
 			   
-static int raid1_status (char *page, int minor, struct md_dev *mddev)
+static int raid1_status (char *page, mddev_t *mddev)
 {
-	struct raid1_data *raid_conf = (struct raid1_data *) mddev->private;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
 	int sz = 0, i;
 	
-	sz += sprintf (page+sz, " [%d/%d] [", raid_conf->raid_disks, raid_conf->working_disks);
-	for (i = 0; i < raid_conf->raid_disks; i++)
-		sz += sprintf (page+sz, "%s", raid_conf->mirrors [i].operational ? "U" : "_");
+	sz += sprintf (page+sz, " [%d/%d] [", conf->raid_disks,
+						 conf->working_disks);
+	for (i = 0; i < conf->raid_disks; i++)
+		sz += sprintf (page+sz, "%s",
+			conf->mirrors[i].operational ? "U" : "_");
 	sz += sprintf (page+sz, "]");
 	return sz;
 }
 
-static void raid1_fix_links (struct raid1_data *raid_conf, int failed_index)
+static void unlink_disk (raid1_conf_t *conf, int target)
 {
-	int disks = raid_conf->raid_disks;
-	int j;
+	int disks = MD_SB_DISKS /* FIXME conf->nr_disks*/;
+	int i;
 
-	for (j = 0; j < disks; j++)
-		if (raid_conf->mirrors [j].next == failed_index)
-			raid_conf->mirrors [j].next = raid_conf->mirrors [failed_index].next;
+	for (i = 0; i < disks; i++)
+		if (conf->mirrors[i].next == target)
+			conf->mirrors[i].next = conf->mirrors[target].next;
 }
 
-static int raid1_error (struct md_dev *mddev, kdev_t dev)
+#define LAST_DISK KERN_ALERT \
+"raid1: only one disk left and IO error.\n"
+
+#define NO_SPARE_DISK KERN_ALERT \
+"raid1: no spare disk left, degrading mirror level by one.\n"
+
+#define DISK_FAILED KERN_ALERT \
+"raid1: Disk failure on %s, disabling device. \n" \
+"       Operation continuing on %d devices\n"
+
+#define START_SYNCING KERN_ALERT \
+"raid1: start syncing spare disk.\n"
+
+#define ALREADY_SYNCING KERN_INFO \
+"raid1: syncing already in progress.\n"
+
+static void mark_disk_bad (mddev_t *mddev, int failed)
 {
-	struct raid1_data *raid_conf = (struct raid1_data *) mddev->private;
-	struct mirror_info *mirror;
-	md_superblock_t *sb = mddev->sb;
-	int disks = raid_conf->raid_disks;
-	int i;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+	struct mirror_info *mirror = conf->mirrors+failed;
+	mdp_super_t *sb = mddev->sb;
+
+	mirror->operational = 0;
+	unlink_disk(conf, failed);
+	mark_disk_faulty(sb->disks+mirror->number);
+	mark_disk_nonsync(sb->disks+mirror->number);
+	mark_disk_inactive(sb->disks+mirror->number);
+	sb->active_disks--;
+	sb->working_disks--;
+	sb->failed_disks++;
+	mddev->sb_dirty = 1;
+	md_wakeup_thread(conf->thread);
+	conf->working_disks--;
+	printk (DISK_FAILED, partition_name (mirror->dev),
+				 conf->working_disks);
+}
 
-	PRINTK(("raid1_error called\n"));
+static int raid1_error (mddev_t *mddev, kdev_t dev)
+{
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+	struct mirror_info * mirrors = conf->mirrors;
+	int disks = MD_SB_DISKS /*conf->nr_disks FIXME */;
+	int i;
 
-	if (raid_conf->working_disks == 1) {
+	if (conf->working_disks == 1) {
 		/*
 		 * Uh oh, we can do nothing if this is our last disk, but
 		 * first check if this is a queued request for a device
 		 * which has just failed.
 		 */
-		for (i = 0, mirror = raid_conf->mirrors; i < disks; i++, mirror++)
-			if (mirror->dev == dev && !mirror->operational)
+		for (i = 0; i < disks; i++) {
+			if (mirrors[i].dev==dev && !mirrors[i].operational)
 				return 0;
-		printk (KERN_ALERT "RAID1: only one disk left and IO error.\n");
-		return 0;
+		}
+		printk (LAST_DISK);
+	} else {
+		/*
+		 * Mark disk as unusable
+		 */
+		for (i = 0; i < disks; i++) {
+			if (mirrors[i].dev==dev && mirrors[i].operational) {
+				mark_disk_bad (mddev, i);
+				break;
+			}
+		}
 	}
+	return 0;
+}
 
-	/* Mark disk as unusable */
-	for (i = 0, mirror = raid_conf->mirrors; i < disks; i++, mirror++) {
-		if (mirror->dev == dev && mirror->operational){
-			mirror->operational = 0;
-			raid1_fix_links (raid_conf, i);
-			sb->disks[mirror->number].state |= (1 << MD_FAULTY_DEVICE);
-			sb->disks[mirror->number].state &= ~(1 << MD_SYNC_DEVICE);
-			sb->disks[mirror->number].state &= ~(1 << MD_ACTIVE_DEVICE);
-			sb->active_disks--;
-			sb->working_disks--;
-			sb->failed_disks++;
-			mddev->sb_dirty = 1;
-			md_wakeup_thread(raid1_thread);
-			raid_conf->working_disks--;
-			printk (KERN_ALERT
-				"RAID1: Disk failure on %s, disabling device."
-				"Operation continuing on %d devices\n",
-				kdevname (dev), raid_conf->working_disks);
-		}
+#undef LAST_DISK
+#undef NO_SPARE_DISK
+#undef DISK_FAILED
+#undef START_SYNCING
+
+/*
+ * This is the personality-specific hot-addition routine
+ */
+
+#if 0
+#define NO_SUPERBLOCK KERN_ERR \
+"raid1: cannot hot-add disk to the array with no RAID superblock\n"
+
+#define WRONG_LEVEL KERN_ERR \
+"raid1: hot-add: level of disk is not RAID-1\n"
+
+#define HOT_ADD_SUCCEEDED KERN_INFO \
+"raid1: device %s hot-added\n"
+
+static int raid1_hot_add_disk (mddev_t *mddev, kdev_t dev)
+{
+	unsigned long flags;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+	struct mirror_info *mirror;
+	mdp_super_t *sb = mddev->sb;
+	mdk_rdev_t * rdev;
+	int n;
+
+	/*
+	 * The device has its superblock already read and it was found
+	 * to be consistent for generic RAID usage.  Now we check whether
+	 * it's usable for RAID-1 hot addition.
+	 */
+
+	n = mddev->nb_dev++;
+	rdev = &mddev->devices[n];
+	if (!rdev->sb) {
+		printk (NO_SUPERBLOCK);
+		return -EINVAL;
+	}
+	if (rdev->sb->level != 1) {
+		printk (WRONG_LEVEL);
+		return -EINVAL;
 	}
+	/* FIXME: are there other things left we could sanity-check? */
+
+	/*
+	 * We have to disable interrupts, as our RAID-1 state is used
+	 * from irq handlers as well.
+	 */
+	save_flags(flags);
+	cli();
+
+	conf->nr_disks++;
+	mirror = conf->mirrors+n;
+
+	mirror->number = n;
+	mirror->raid_disk = n;
+	mirror->dev = dev;
+	mirror->next = 0; /* FIXME */
+	mirror->sect_limit = MAX_LINEAR_SECTORS;
+
+	mirror->operational = 0;
+	mirror->spare = 1;
+	mirror->write_only = 0;
+
+	mark_disk_faulty(sb->disks+n);
+	mark_disk_nonsync(sb->disks+n);
+	mark_disk_inactive(sb->disks+n);
+	sb->nr_disks++;
+	sb->spare_disks++;
+
+	restore_flags(flags);
+
+	md_update_sb(mddev);
+
+	printk (HOT_ADD_SUCCEEDED, kdevname(rdev->dev));
 
 	return 0;
 }
 
+#undef NO_SUPERBLOCK
+#undef WRONG_LEVEL
+#undef HOT_ADD_SUCCEEDED
+
+#endif
+
+/*
+ * Insert the spare disk into the drive-ring
+ */
+static void link_disk(raid1_conf_t *conf, struct mirror_info *mirror)
+{
+	int j, next;
+	int disks = MD_SB_DISKS /*conf->nr_disks FIXME */;
+	struct mirror_info *p = conf->mirrors;
+
+	for (j = 0; j < disks; j++, p++)
+		if (p->operational && !p->write_only) {
+			next = p->next;
+			p->next = mirror->raid_disk;
+			mirror->next = next;
+			return;
+		}
+
+	printk("raid1: bug: no read-operational devices\n");
+}
+
+static void print_raid1_conf (raid1_conf_t *conf)
+{
+	int i;
+	struct mirror_info *tmp;
+
+	printk("RAID1 conf printout:\n");
+	if (!conf) {
+		printk("(conf==NULL)\n");
+		return;
+	}
+	printk(" --- wd:%d rd:%d nd:%d\n", conf->working_disks,
+			 conf->raid_disks, conf->nr_disks);
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		tmp = conf->mirrors + i;
+		printk(" disk %d, s:%d, o:%d, n:%d rd:%d us:%d dev:%s\n",
+			i, tmp->spare,tmp->operational,
+			tmp->number,tmp->raid_disk,tmp->used_slot,
+			partition_name(tmp->dev));
+	}
+}
+
+static int raid1_diskop(mddev_t *mddev, mdp_disk_t **d, int state)
+{
+	int err = 0;
+	int i, failed_disk=-1, spare_disk=-1, removed_disk=-1, added_disk=-1;
+	raid1_conf_t *conf = mddev->private;
+	struct mirror_info *tmp, *sdisk, *fdisk, *rdisk, *adisk;
+	unsigned long flags;
+	mdp_super_t *sb = mddev->sb;
+	mdp_disk_t *failed_desc, *spare_desc, *added_desc;
+
+	save_flags(flags);
+	cli();
+
+	print_raid1_conf(conf);
+	/*
+	 * find the disk ...
+	 */
+	switch (state) {
+
+	case DISKOP_SPARE_ACTIVE:
+
+		/*
+		 * Find the failed disk within the RAID1 configuration ...
+		 * (this can only be in the first conf->working_disks part)
+		 */
+		for (i = 0; i < conf->raid_disks; i++) {
+			tmp = conf->mirrors + i;
+			if ((!tmp->operational && !tmp->spare) ||
+					!tmp->used_slot) {
+				failed_disk = i;
+				break;
+			}
+		}
+		/*
+		 * When we activate a spare disk we _must_ have a disk in
+		 * the lower (active) part of the array to replace. 
+		 */
+		if ((failed_disk == -1) || (failed_disk >= conf->raid_disks)) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		/* fall through */
+
+	case DISKOP_SPARE_WRITE:
+	case DISKOP_SPARE_INACTIVE:
+
+		/*
+		 * Find the spare disk ... (can only be in the 'high'
+		 * area of the array)
+		 */
+		for (i = conf->raid_disks; i < MD_SB_DISKS; i++) {
+			tmp = conf->mirrors + i;
+			if (tmp->spare && tmp->number == (*d)->number) {
+				spare_disk = i;
+				break;
+			}
+		}
+		if (spare_disk == -1) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		break;
+
+	case DISKOP_HOT_REMOVE_DISK:
+
+		for (i = 0; i < MD_SB_DISKS; i++) {
+			tmp = conf->mirrors + i;
+			if (tmp->used_slot && (tmp->number == (*d)->number)) {
+				if (tmp->operational) {
+					err = -EBUSY;
+					goto abort;
+				}
+				removed_disk = i;
+				break;
+			}
+		}
+		if (removed_disk == -1) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		break;
+
+	case DISKOP_HOT_ADD_DISK:
+
+		for (i = conf->raid_disks; i < MD_SB_DISKS; i++) {
+			tmp = conf->mirrors + i;
+			if (!tmp->used_slot) {
+				added_disk = i;
+				break;
+			}
+		}
+		if (added_disk == -1) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		break;
+	}
+
+	switch (state) {
+	/*
+	 * Switch the spare disk to write-only mode:
+	 */
+	case DISKOP_SPARE_WRITE:
+		sdisk = conf->mirrors + spare_disk;
+		sdisk->operational = 1;
+		sdisk->write_only = 1;
+		break;
+	/*
+	 * Deactivate a spare disk:
+	 */
+	case DISKOP_SPARE_INACTIVE:
+		sdisk = conf->mirrors + spare_disk;
+		sdisk->operational = 0;
+		sdisk->write_only = 0;
+		break;
+	/*
+	 * Activate (mark read-write) the (now sync) spare disk,
+	 * which means we switch it's 'raid position' (->raid_disk)
+	 * with the failed disk. (only the first 'conf->nr_disks'
+	 * slots are used for 'real' disks and we must preserve this
+	 * property)
+	 */
+	case DISKOP_SPARE_ACTIVE:
+
+		sdisk = conf->mirrors + spare_disk;
+		fdisk = conf->mirrors + failed_disk;
+
+		spare_desc = &sb->disks[sdisk->number];
+		failed_desc = &sb->disks[fdisk->number];
+
+		if (spare_desc != *d) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		if (spare_desc->raid_disk != sdisk->raid_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+			
+		if (sdisk->raid_disk != spare_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		if (failed_desc->raid_disk != fdisk->raid_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		if (fdisk->raid_disk != failed_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		/*
+		 * do the switch finally
+		 */
+		xchg_values(*spare_desc, *failed_desc);
+		xchg_values(*fdisk, *sdisk);
+
+		/*
+		 * (careful, 'failed' and 'spare' are switched from now on)
+		 *
+		 * we want to preserve linear numbering and we want to
+		 * give the proper raid_disk number to the now activated
+		 * disk. (this means we switch back these values)
+		 */
+	
+		xchg_values(spare_desc->raid_disk, failed_desc->raid_disk);
+		xchg_values(sdisk->raid_disk, fdisk->raid_disk);
+		xchg_values(spare_desc->number, failed_desc->number);
+		xchg_values(sdisk->number, fdisk->number);
+
+		*d = failed_desc;
+
+		if (sdisk->dev == MKDEV(0,0))
+			sdisk->used_slot = 0;
+		/*
+		 * this really activates the spare.
+		 */
+		fdisk->spare = 0;
+		fdisk->write_only = 0;
+		link_disk(conf, fdisk);
+
+		/*
+		 * if we activate a spare, we definitely replace a
+		 * non-operational disk slot in the 'low' area of
+		 * the disk array.
+		 */
+
+		conf->working_disks++;
+
+		break;
+
+	case DISKOP_HOT_REMOVE_DISK:
+		rdisk = conf->mirrors + removed_disk;
+
+		if (rdisk->spare && (removed_disk < conf->raid_disks)) {
+			MD_BUG();	
+			err = 1;
+			goto abort;
+		}
+		rdisk->dev = MKDEV(0,0);
+		rdisk->used_slot = 0;
+		conf->nr_disks--;
+		break;
+
+	case DISKOP_HOT_ADD_DISK:
+		adisk = conf->mirrors + added_disk;
+		added_desc = *d;
+
+		if (added_disk != added_desc->number) {
+			MD_BUG();	
+			err = 1;
+			goto abort;
+		}
+
+		adisk->number = added_desc->number;
+		adisk->raid_disk = added_desc->raid_disk;
+		adisk->dev = MKDEV(added_desc->major,added_desc->minor);
+
+		adisk->operational = 0;
+		adisk->write_only = 0;
+		adisk->spare = 1;
+		adisk->used_slot = 1;
+		conf->nr_disks++;
+
+		break;
+
+	default:
+		MD_BUG();	
+		err = 1;
+		goto abort;
+	}
+abort:
+	restore_flags(flags);
+	print_raid1_conf(conf);
+	return err;
+}
+
+
+#define IO_ERROR KERN_ALERT \
+"raid1: %s: unrecoverable I/O read error for block %lu\n"
+
+#define REDIRECT_SECTOR KERN_ERR \
+"raid1: %s: redirecting sector %lu to another mirror\n"
+
 /*
  * This is a kernel thread which:
  *
  *	1.	Retries failed read operations on working mirrors.
- *	2.	Updates the raid superblock when problems are encountered.
+ *	2.	Updates the raid superblock when problems encounter.
  */
-void raid1d (void *data)
+static void raid1d (void *data)
 {
 	struct buffer_head *bh;
 	kdev_t dev;
 	unsigned long flags;
-	struct raid1_bh * r1_bh;
-	struct md_dev *mddev;
+	struct raid1_bh *r1_bh;
+	mddev_t *mddev;
 
-	PRINTK(("raid1d() active\n"));
-	save_flags(flags);
-	cli();
 	while (raid1_retry_list) {
+		save_flags(flags);
+		cli();
 		bh = raid1_retry_list;
-		r1_bh = (struct raid1_bh *)(bh->private_bh);
+		r1_bh = (struct raid1_bh *)(bh->b_dev_id);
 		raid1_retry_list = r1_bh->next_retry;
 		restore_flags(flags);
 
-		mddev = md_dev + MINOR(bh->b_dev);
+		mddev = md_arrays + MINOR(bh->b_dev);
 		if (mddev->sb_dirty) {
+			printk(KERN_INFO "dirty sb detected, updating.\n");
 			mddev->sb_dirty = 0;
-			md_update_sb(MINOR(bh->b_dev));
+			md_update_sb(mddev);
 		}
 		dev = bh->b_rdev;
-		__raid1_map (md_dev + MINOR(bh->b_dev), &bh->b_rdev, &bh->b_rsector, bh->b_size >> 9);
+		__raid1_map (mddev, &bh->b_rdev, &bh->b_rsector,
+							 bh->b_size >> 9);
 		if (bh->b_rdev == dev) {
-			printk (KERN_ALERT 
-					"raid1: %s: unrecoverable I/O read error for block %lu\n",
-						kdevname(bh->b_dev), bh->b_blocknr);
-			raid1_end_buffer_io (bh, 0);
+			printk (IO_ERROR, partition_name(bh->b_dev), bh->b_blocknr);
+			raid1_end_bh_io(r1_bh, 0);
 		} else {
-			printk (KERN_ERR "raid1: %s: redirecting sector %lu to another mirror\n", 
-					  kdevname(bh->b_dev), bh->b_blocknr);
-			clear_bit (BH_Lock, &bh->b_state);
+			printk (REDIRECT_SECTOR,
+				partition_name(bh->b_dev), bh->b_blocknr);
 			map_and_make_request (r1_bh->cmd, bh);
 		}
-		cli();
 	}
-	restore_flags(flags);
-	
 }
+#undef IO_ERROR
+#undef REDIRECT_SECTOR
+
+/*
+ * Private kernel thread to reconstruct mirrors after an unclean
+ * shutdown.
+ */
+static void raid1syncd (void *data)
+{
+        raid1_conf_t *conf = data;
+        mddev_t *mddev = conf->mddev;
+
+        if (!conf->resync_mirrors)
+                return;
+        if (conf->resync_mirrors == 2)
+                return;
+        if (md_do_sync(mddev,NULL))
+		return;
+	/*
+	 * Only if everything went Ok.
+	 */
+        conf->resync_mirrors = 0;
+}
+
 
 /*
  * This will catch the scenario in which one of the mirrors was
  * mounted as a normal device rather than as a part of a raid set.
+ *
+ * check_consistency is very personality-dependent, eg. RAID5 cannot
+ * do this check, it uses another method.
  */
-static int check_consistenty (struct md_dev *mddev)
+static int __check_consistency (mddev_t *mddev, int row)
 {
-	struct raid1_data *raid_conf = mddev->private;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+	int disks = MD_SB_DISKS /*conf->nr_disks FIXME */;
 	kdev_t dev;
 	struct buffer_head *bh = NULL;
 	int i, rc = 0;
 	char *buffer = NULL;
 
-	for (i = 0; i < raid_conf->raid_disks; i++) {
-		if (!raid_conf->mirrors[i].operational)
+	for (i = 0; i < disks; i++) {
+		printk("(checking disk %d)\n",i);
+		if (!conf->mirrors[i].operational)
 			continue;
-		dev = raid_conf->mirrors[i].dev;
+		printk("(really checking disk %d)\n",i);
+		dev = conf->mirrors[i].dev;
 		set_blocksize(dev, 4096);
-		if ((bh = bread(dev, 0, 4096)) == NULL)
+		if ((bh = bread(dev, row / 4, 4096)) == NULL)
 			break;
 		if (!buffer) {
 			buffer = (char *) __get_free_page(GFP_KERNEL);
@@ -601,137 +922,336 @@
 	return rc;
 }
 
-static int raid1_run (int minor, struct md_dev *mddev)
+static int check_consistency (mddev_t *mddev)
 {
-	struct raid1_data *raid_conf;
-	int i, j, raid_disk;
-	md_superblock_t *sb = mddev->sb;
-	md_descriptor_t *descriptor;
-	struct real_dev *realdev;
+	if (__check_consistency(mddev, 0))
+/*
+ * we do not do this currently, as it's perfectly possible to
+ * have an inconsistent array when it's freshly created. Only
+ * newly written data has to be consistent.
+ */
+		return 0;
+
+	return 0;
+}
+
+#define INVALID_LEVEL KERN_WARNING \
+"raid1: md%d: raid level not set to mirroring (%d)\n"
+
+#define NO_SB KERN_ERR \
+"raid1: disabled mirror %s (couldn't access raid superblock)\n"
+
+#define ERRORS KERN_ERR \
+"raid1: disabled mirror %s (errors detected)\n"
+
+#define NOT_IN_SYNC KERN_ERR \
+"raid1: disabled mirror %s (not in sync)\n"
+
+#define INCONSISTENT KERN_ERR \
+"raid1: disabled mirror %s (inconsistent descriptor)\n"
+
+#define ALREADY_RUNNING KERN_ERR \
+"raid1: disabled mirror %s (mirror %d already operational)\n"
+
+#define OPERATIONAL KERN_INFO \
+"raid1: device %s operational as mirror %d\n"
+
+#define MEM_ERROR KERN_ERR \
+"raid1: couldn't allocate memory for md%d\n"
+
+#define SPARE KERN_INFO \
+"raid1: spare disk %s\n"
+
+#define NONE_OPERATIONAL KERN_ERR \
+"raid1: no operational mirrors for md%d\n"
+
+#define RUNNING_CKRAID KERN_ERR \
+"raid1: detected mirror differences -- running resync\n"
+
+#define ARRAY_IS_ACTIVE KERN_INFO \
+"raid1: raid set md%d active with %d out of %d mirrors\n"
+
+#define THREAD_ERROR KERN_ERR \
+"raid1: couldn't allocate thread for md%d\n"
+
+#define START_RESYNC KERN_WARNING \
+"raid1: raid set md%d not clean; reconstructing mirrors\n"
+
+static int raid1_run (mddev_t *mddev)
+{
+	raid1_conf_t *conf;
+	int i, j, disk_idx;
+	struct mirror_info *disk;
+	mdp_super_t *sb = mddev->sb;
+	mdp_disk_t *descriptor;
+	mdk_rdev_t *rdev;
+	struct md_list_head *tmp;
+	int start_recovery = 0;
 
 	MOD_INC_USE_COUNT;
 
 	if (sb->level != 1) {
-		printk("raid1: %s: raid level not set to mirroring (%d)\n", kdevname(MKDEV(MD_MAJOR, minor)), sb->level);
-		MOD_DEC_USE_COUNT;
-		return -EIO;
+		printk(INVALID_LEVEL, mdidx(mddev), sb->level);
+		goto out;
 	}
-	/****
-	 * copy the now verified devices into our private RAID1 bookkeeping area:
-	 *
-	 * [whatever we allocate in raid1_run(), should be freed in raid1_stop()]
+	/*
+	 * copy the already verified devices into our private RAID1
+	 * bookkeeping area. [whatever we allocate in raid1_run(),
+	 * should be freed in raid1_stop()]
 	 */
 
-	while (!( /* FIXME: now we are rather fault tolerant than nice */
-	mddev->private = kmalloc (sizeof (struct raid1_data), GFP_KERNEL)
-	) )
-		printk ("raid1_run(): out of memory\n");
-	raid_conf = mddev->private;
-	memset(raid_conf, 0, sizeof(*raid_conf));
-
-	PRINTK(("raid1_run(%d) called.\n", minor));
-
-  	for (i = 0; i < mddev->nb_dev; i++) {
-  		realdev = &mddev->devices[i];
-		if (!realdev->sb) {
-			printk(KERN_ERR "raid1: disabled mirror %s (couldn't access raid superblock)\n", kdevname(realdev->dev));
+	conf = raid1_kmalloc(sizeof(raid1_conf_t));
+	mddev->private = conf;
+	if (!conf) {
+		printk(MEM_ERROR, mdidx(mddev));
+		goto out;
+	}
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
+		if (rdev->faulty) {
+			printk(ERRORS, partition_name(rdev->dev));
+		} else {
+			if (!rdev->sb) {
+				MD_BUG();
+				continue;
+			}
+		}
+		if (rdev->desc_nr == -1) {
+			MD_BUG();
 			continue;
 		}
-
-		/*
-		 * This is important -- we are using the descriptor on
-		 * the disk only to get a pointer to the descriptor on
-		 * the main superblock, which might be more recent.
-		 */
-		descriptor = &sb->disks[realdev->sb->descriptor.number];
-		if (descriptor->state & (1 << MD_FAULTY_DEVICE)) {
-			printk(KERN_ERR "raid1: disabled mirror %s (errors detected)\n", kdevname(realdev->dev));
+		descriptor = &sb->disks[rdev->desc_nr];
+		disk_idx = descriptor->raid_disk;
+		disk = conf->mirrors + disk_idx;
+
+		if (disk_faulty(descriptor)) {
+			disk->number = descriptor->number;
+			disk->raid_disk = disk_idx;
+			disk->dev = rdev->dev;
+			disk->sect_limit = MAX_LINEAR_SECTORS;
+			disk->operational = 0;
+			disk->write_only = 0;
+			disk->spare = 0;
+			disk->used_slot = 1;
 			continue;
 		}
-		if (descriptor->state & (1 << MD_ACTIVE_DEVICE)) {
-			if (!(descriptor->state & (1 << MD_SYNC_DEVICE))) {
-				printk(KERN_ERR "raid1: disabled mirror %s (not in sync)\n", kdevname(realdev->dev));
+		if (disk_active(descriptor)) {
+			if (!disk_sync(descriptor)) {
+				printk(NOT_IN_SYNC,
+					partition_name(rdev->dev));
 				continue;
 			}
-			raid_disk = descriptor->raid_disk;
-			if (descriptor->number > sb->nr_disks || raid_disk > sb->raid_disks) {
-				printk(KERN_ERR "raid1: disabled mirror %s (inconsistent descriptor)\n", kdevname(realdev->dev));
+			if ((descriptor->number > MD_SB_DISKS) ||
+					 (disk_idx > sb->raid_disks)) {
+
+				printk(INCONSISTENT,
+					partition_name(rdev->dev));
 				continue;
 			}
-			if (raid_conf->mirrors[raid_disk].operational) {
-				printk(KERN_ERR "raid1: disabled mirror %s (mirror %d already operational)\n", kdevname(realdev->dev), raid_disk);
+			if (disk->operational) {
+				printk(ALREADY_RUNNING,
+					partition_name(rdev->dev),
+					disk_idx);
 				continue;
 			}
-			printk(KERN_INFO "raid1: device %s operational as mirror %d\n", kdevname(realdev->dev), raid_disk);
-			raid_conf->mirrors[raid_disk].number = descriptor->number;
-			raid_conf->mirrors[raid_disk].raid_disk = raid_disk;
-			raid_conf->mirrors[raid_disk].dev = mddev->devices [i].dev;
-			raid_conf->mirrors[raid_disk].operational = 1;
-			raid_conf->mirrors[raid_disk].sect_limit = 128;
-			raid_conf->working_disks++;
-		}
-	}
-	if (!raid_conf->working_disks) {
-		printk(KERN_ERR "raid1: no operational mirrors for %s\n", kdevname(MKDEV(MD_MAJOR, minor)));
-		kfree(raid_conf);
-		mddev->private = NULL;
-		MOD_DEC_USE_COUNT;
-		return -EIO;
-	}
-
-	raid_conf->raid_disks = sb->raid_disks;
-	raid_conf->mddev = mddev;
-
-	for (j = 0; !raid_conf->mirrors[j].operational; j++);
-	raid_conf->last_used = j;
-	for (i = raid_conf->raid_disks - 1; i >= 0; i--) {
-		if (raid_conf->mirrors[i].operational) {
-			PRINTK(("raid_conf->mirrors[%d].next == %d\n", i, j));
-			raid_conf->mirrors[i].next = j;
+			printk(OPERATIONAL, partition_name(rdev->dev),
+ 					disk_idx);
+			disk->number = descriptor->number;
+			disk->raid_disk = disk_idx;
+			disk->dev = rdev->dev;
+			disk->sect_limit = MAX_LINEAR_SECTORS;
+			disk->operational = 1;
+			disk->write_only = 0;
+			disk->spare = 0;
+			disk->used_slot = 1;
+			conf->working_disks++;
+		} else {
+		/*
+		 * Must be a spare disk ..
+		 */
+			printk(SPARE, partition_name(rdev->dev));
+			disk->number = descriptor->number;
+			disk->raid_disk = disk_idx;
+			disk->dev = rdev->dev;
+			disk->sect_limit = MAX_LINEAR_SECTORS;
+			disk->operational = 0;
+			disk->write_only = 0;
+			disk->spare = 1;
+			disk->used_slot = 1;
+		}
+	}
+	if (!conf->working_disks) {
+		printk(NONE_OPERATIONAL, mdidx(mddev));
+		goto out_free_conf;
+	}
+
+	conf->raid_disks = sb->raid_disks;
+	conf->nr_disks = sb->nr_disks;
+	conf->mddev = mddev;
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		
+		descriptor = sb->disks+i;
+		disk_idx = descriptor->raid_disk;
+		disk = conf->mirrors + disk_idx;
+
+		if (disk_faulty(descriptor) && (disk_idx < conf->raid_disks) &&
+				!disk->used_slot) {
+
+			disk->number = descriptor->number;
+			disk->raid_disk = disk_idx;
+			disk->dev = MKDEV(0,0);
+
+			disk->operational = 0;
+			disk->write_only = 0;
+			disk->spare = 0;
+			disk->used_slot = 1;
+		}
+	}
+
+	for (j = 0; !conf->mirrors[j].operational; j++);
+	conf->last_used = j;
+	for (i = conf->raid_disks - 1; i >= 0; i--) {
+		if (conf->mirrors[i].operational) {
+			conf->mirrors[i].next = j;
 			j = i;
 		}
 	}
 
-	if (check_consistenty(mddev)) {
-		printk(KERN_ERR "raid1: detected mirror differences -- run ckraid\n");
-		sb->state |= 1 << MD_SB_ERRORS;
-		kfree(raid_conf);
-		mddev->private = NULL;
-		MOD_DEC_USE_COUNT;
-		return -EIO;
+	if (conf->working_disks != sb->raid_disks) {
+		printk(KERN_ALERT "raid1: md%d, not all disks are operational -- trying to recover array\n", mdidx(mddev));
+		start_recovery = 1;
+	}
+
+	if (!start_recovery && (sb->state & (1 << MD_SB_CLEAN))) {
+		/*
+		 * we do sanity checks even if the device says
+		 * it's clean ...
+		 */
+		if (check_consistency(mddev)) {
+			printk(RUNNING_CKRAID);
+			sb->state &= ~(1 << MD_SB_CLEAN);
+		}
+	}
+
+	{
+		const char * name = "raid1d";
+
+		conf->thread = md_register_thread(raid1d, conf, name);
+		if (!conf->thread) {
+			printk(THREAD_ERROR, mdidx(mddev));
+			goto out_free_conf;
+        	}
 	}
 
+	{
+		const char * name = "raid1syncd";
+
+		conf->resync_thread = md_register_thread(raid1syncd, conf,name);
+		if (!conf->resync_thread) {
+			printk(THREAD_ERROR, mdidx(mddev));
+			goto out_free_conf;
+		}
+        }
+
+	if (!start_recovery && !(sb->state & (1 << MD_SB_CLEAN))) {
+		printk(START_RESYNC, mdidx(mddev));
+                conf->resync_mirrors = 1;
+		mddev->curr_resync = 1;
+                md_wakeup_thread(conf->resync_thread);
+        }
+
 	/*
 	 * Regenerate the "device is in sync with the raid set" bit for
 	 * each device.
 	 */
-	for (i = 0; i < sb->nr_disks ; i++) {
-		sb->disks[i].state &= ~(1 << MD_SYNC_DEVICE);
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		mark_disk_nonsync(sb->disks+i);
 		for (j = 0; j < sb->raid_disks; j++) {
-			if (!raid_conf->mirrors[j].operational)
+			if (!conf->mirrors[j].operational)
 				continue;
-			if (sb->disks[i].number == raid_conf->mirrors[j].number)
-				sb->disks[i].state |= 1 << MD_SYNC_DEVICE;
+			if (sb->disks[i].number == conf->mirrors[j].number)
+				mark_disk_sync(sb->disks+i);
 		}
 	}
-	sb->active_disks = raid_conf->working_disks;
+	sb->active_disks = conf->working_disks;
 
-	printk("raid1: raid set %s active with %d out of %d mirrors\n", kdevname(MKDEV(MD_MAJOR, minor)), sb->active_disks, sb->raid_disks);
-	/* Ok, everything is just fine now */
-	return (0);
+	if (start_recovery)
+		md_recover_arrays();
+
+
+	printk(ARRAY_IS_ACTIVE, mdidx(mddev), sb->active_disks, sb->raid_disks);
+	/*
+	 * Ok, everything is just fine now
+	 */
+	return 0;
+
+out_free_conf:
+	kfree(conf);
+	mddev->private = NULL;
+out:
+	MOD_DEC_USE_COUNT;
+	return -EIO;
+}
+
+#undef INVALID_LEVEL
+#undef NO_SB
+#undef ERRORS
+#undef NOT_IN_SYNC
+#undef INCONSISTENT
+#undef ALREADY_RUNNING
+#undef OPERATIONAL
+#undef SPARE
+#undef NONE_OPERATIONAL
+#undef RUNNING_CKRAID
+#undef ARRAY_IS_ACTIVE
+
+static int raid1_stop_resync (mddev_t *mddev)
+{
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+
+	if (conf->resync_thread) {
+		if (conf->resync_mirrors) {
+			conf->resync_mirrors = 2;
+			md_interrupt_thread(conf->resync_thread);
+			printk(KERN_INFO "raid1: mirror resync was not fully finished, restarting next time.\n");
+			return 1;
+		}
+		return 0;
+	}
+	return 0;
+}
+
+static int raid1_restart_resync (mddev_t *mddev)
+{
+	raid1_conf_t *conf = mddev_to_conf(mddev);
+
+	if (conf->resync_mirrors) {
+		if (!conf->resync_thread) {
+			MD_BUG();
+			return 0;
+		}
+		conf->resync_mirrors = 1;
+		md_wakeup_thread(conf->resync_thread);
+		return 1;
+	}
+	return 0;
 }
 
-static int raid1_stop (int minor, struct md_dev *mddev)
+static int raid1_stop (mddev_t *mddev)
 {
-	struct raid1_data *raid_conf = (struct raid1_data *) mddev->private;
+	raid1_conf_t *conf = mddev_to_conf(mddev);
 
-	kfree (raid_conf);
+	md_unregister_thread(conf->thread);
+	if (conf->resync_thread)
+		md_unregister_thread(conf->resync_thread);
+	kfree(conf);
 	mddev->private = NULL;
 	MOD_DEC_USE_COUNT;
 	return 0;
 }
 
-static struct md_personality raid1_personality=
+static mdk_personality_t raid1_personality=
 {
 	"raid1",
 	raid1_map,
@@ -742,13 +1262,14 @@
 	raid1_status,
 	NULL,			/* no ioctls */
 	0,
-	raid1_error
+	raid1_error,
+	raid1_diskop,
+	raid1_stop_resync,
+	raid1_restart_resync
 };
 
 int raid1_init (void)
 {
-	if ((raid1_thread = md_register_thread(raid1d, NULL)) == NULL)
-		return -EBUSY;
 	return register_md_personality (RAID1, &raid1_personality);
 }
 
@@ -760,7 +1281,6 @@
 
 void cleanup_module (void)
 {
-	md_unregister_thread (raid1_thread);
 	unregister_md_personality (RAID1);
 }
 #endif
--- linux/drivers/block/raid5.c.orig	Mon Aug  3 20:40:05 1998
+++ linux/drivers/block/raid5.c	Fri Feb  2 01:14:54 1996
@@ -1,4 +1,4 @@
-/*****************************************************************************
+/*
  * raid5.c : Multiple Devices driver for Linux
  *           Copyright (C) 1996, 1997 Ingo Molnar, Miguel de Icaza, Gadi Oxman
  *
@@ -17,91 +17,21 @@
 #include <linux/module.h>
 #include <linux/locks.h>
 #include <linux/malloc.h>
-#include <linux/md.h>
-#include <linux/raid5.h>
+#include <linux/raid/raid5.h>
 #include <asm/bitops.h>
 #include <asm/atomic.h>
 
-struct buffer_head *efind_buffer(kdev_t dev, int block, int size);
-
-#define MAJOR_NR MD_MAJOR
-#define MD_DRIVER
-#define MD_PERSONALITY
-
-static struct md_personality raid5_personality;
-
-struct stripe_head {
-	struct stripe_head	*hash_next, **hash_pprev; /* hash pointers */
-	struct stripe_head	*handle_next;		/* completed during hash scan pointers */
-	struct raid5_data	*raid_conf;
-	struct buffer_head	*bh_old[MD_SB_DISKS];	/* disk image */
-	struct buffer_head	*bh_new[MD_SB_DISKS];	/* buffers of the MD device (present in buffer cache) */
-	struct buffer_head	*bh_copy[MD_SB_DISKS];	/* copy on write of bh_new (bh_new can change from under us) */
-	int			cmd_new[MD_SB_DISKS];	/* READ/WRITE for new */
-	int			new[MD_SB_DISKS];	/* buffer added since the last handle_stripe() */
-	unsigned long		sector;			/* sector of this row */
-	int			size;			/* buffers size */
-	int			pd_idx;			/* parity disk index */
-	int			nr_pending;		/* nr of pending cmds */
-	__u32			state;			/* state flags */
-	int			cmd;			/* stripe cmd */
-	int			count;			/* nr of waiters */
-	int			write_method;		/* reconstruct-write / read-modify-write */
-	int			phase;			/* PHASE_BEGIN, ..., PHASE_COMPLETE */
-	struct wait_queue	*wait;			/* processes waiting for this stripe */
-};
-
-/*
- * Phase
- */
-#define PHASE_BEGIN		0
-#define PHASE_READ_OLD		1
-#define PHASE_WRITE		2
-#define PHASE_READ		3
-#define PHASE_COMPLETE		4
-
-/*
- * Write method
- */
-#define METHOD_NONE		0
-#define RECONSTRUCT_WRITE	1
-#define READ_MODIFY_WRITE	2
-
-/*
- * Stripe state
- */
-#define STRIPE_LOCKED		0
-#define STRIPE_ERROR		1
-
-/*
- * Stripe commands
- */
-#define STRIPE_NONE		0
-#define	STRIPE_WRITE		1
-#define STRIPE_READ		2
+static mdk_personality_t raid5_personality;
 
 /*
  * Stripe cache
  */
-#define RAID5_STRIPE_POOL_SIZE	128
+#define NR_STRIPES		128
 #define HASH_PAGES		1
 #define HASH_PAGES_ORDER	0
 #define NR_HASH			(HASH_PAGES * PAGE_SIZE / sizeof(struct stripe_head *))
 #define HASH_MASK		(NR_HASH - 1)
-#define stripe_hash(sect, size)	(stripe_hashtbl[((sect) / (size >> 9)) & HASH_MASK])
-
-int nr_stripes = 0, nr_locked_stripes = 0, nr_pending_stripes = 0;
-struct stripe_head **stripe_hashtbl;
-static struct wait_queue *raid5_wait_for_stripe = NULL;
-struct stripe_head *stripe_handle_list = NULL, *stripe_handle_tail = NULL;
-
-/*
- * Free buffers pool
- */  
-#define RAID5_POOL_SIZE	3000
-static int nr_free_buffers = 0, nr_used_buffers = 0, max_nr_used_buffers = 0;
-static struct buffer_head *raid5_buffer_list = NULL;
-static struct wait_queue *raid5_wait_for_bh = NULL;
+#define stripe_hash(conf, sect, size)	((conf)->stripe_hashtbl[((sect) / (size >> 9)) & HASH_MASK])
 
 /*
  * The following can be used to debug the driver
@@ -110,11 +40,12 @@
 
 #if RAID5_DEBUG
 #define PRINTK(x)   do { printk x; } while (0);
-static int nr_pending = 0, free_1024 = 0, free_4096 = 0, used_1024 = 0, used_4096 = 0;
 #else
 #define PRINTK(x)   do { ; } while (0)
 #endif
 
+static void print_raid5_conf (raid5_conf_t *conf);
+
 static inline int stripe_locked(struct stripe_head *sh)
 {
 	return test_bit(STRIPE_LOCKED, &sh->state);
@@ -130,41 +61,34 @@
  */
 static inline void lock_stripe(struct stripe_head *sh)
 {
-	if (!set_bit(STRIPE_LOCKED, &sh->state)) {
+	raid5_conf_t *conf = sh->raid_conf;
+	if (!md_test_and_set_bit(STRIPE_LOCKED, &sh->state)) {
 		PRINTK(("locking stripe %lu\n", sh->sector));
-		nr_locked_stripes++;
+		conf->nr_locked_stripes++;
 	}
 }
 
 static inline void unlock_stripe(struct stripe_head *sh)
 {
-	if (clear_bit(STRIPE_LOCKED, &sh->state)) {
+	raid5_conf_t *conf = sh->raid_conf;
+	if (md_test_and_clear_bit(STRIPE_LOCKED, &sh->state)) {
 		PRINTK(("unlocking stripe %lu\n", sh->sector));
-		nr_locked_stripes--;
+		conf->nr_locked_stripes--;
 		wake_up(&sh->wait);
 	}
 }
 
 static inline void finish_stripe(struct stripe_head *sh)
 {
+	raid5_conf_t *conf = sh->raid_conf;
 	unlock_stripe(sh);
 	sh->cmd = STRIPE_NONE;
 	sh->phase = PHASE_COMPLETE;
-	nr_pending_stripes--;
-	wake_up(&raid5_wait_for_stripe);
+	conf->nr_pending_stripes--;
+	conf->nr_cached_stripes++;
+	wake_up(&conf->wait_for_stripe);
 }
 
-static void unplug_devices(struct stripe_head *sh)
-{
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int i;
-
-	for (i = 0; i < raid_conf->raid_disks; i++)
-		unplug_device(blk_dev + MAJOR(raid_conf->disks[i].dev));
-}
-
-static void raid5d (void *data);
-
 void __wait_on_stripe(struct stripe_head *sh)
 {
 	struct wait_queue wait = { current, NULL };
@@ -190,7 +114,7 @@
 		__wait_on_stripe(sh);
 }
 
-static inline void remove_hash(struct stripe_head *sh)
+static inline void remove_hash(raid5_conf_t *conf, struct stripe_head *sh)
 {
 	PRINTK(("remove_hash(), stripe %lu\n", sh->sector));
 
@@ -199,77 +123,184 @@
 			sh->hash_next->hash_pprev = sh->hash_pprev;
 		*sh->hash_pprev = sh->hash_next;
 		sh->hash_pprev = NULL;
-		nr_stripes--;
+		conf->nr_hashed_stripes--;
 	}
 }
 
-static inline void insert_hash(struct stripe_head *sh)
+static inline void insert_hash(raid5_conf_t *conf, struct stripe_head *sh)
 {
-	struct stripe_head **shp = &stripe_hash(sh->sector, sh->size);
+	struct stripe_head **shp = &stripe_hash(conf, sh->sector, sh->size);
 
-	PRINTK(("insert_hash(), stripe %lu, nr_stripes %d\n", sh->sector, nr_stripes));
+	PRINTK(("insert_hash(), stripe %lu, nr_hashed_stripes %d\n",
+			sh->sector, conf->nr_hashed_stripes));
 
 	if ((sh->hash_next = *shp) != NULL)
 		(*shp)->hash_pprev = &sh->hash_next;
 	*shp = sh;
 	sh->hash_pprev = shp;
-	nr_stripes++;
+	conf->nr_hashed_stripes++;
 }
 
-static void add_bh (struct buffer_head *bh)
+static struct buffer_head *get_free_buffer(struct stripe_head *sh, int b_size)
 {
+	struct buffer_head *bh;
 	unsigned long flags;
 
 	save_flags(flags);
 	cli();
-	bh->b_next = raid5_buffer_list;
-	raid5_buffer_list = bh;
-	nr_free_buffers++;
-#if RAID5_DEBUG
-	if (bh->b_size == 1024)
-		free_1024++;
-	if (bh->b_size == 4096)
-		free_4096++;
-#endif
+	if ((bh = sh->buffer_pool) == NULL) {
+		restore_flags(flags);
+		return NULL;
+	}
+	sh->buffer_pool = bh->b_next;
+	bh->b_size = b_size;
 	restore_flags(flags);
+	return bh;
 }
 
-static void raid5_kfree_bh (struct buffer_head *bh)
+static struct buffer_head *get_free_bh(struct stripe_head *sh)
 {
+	struct buffer_head *bh;
 	unsigned long flags;
 
 	save_flags(flags);
 	cli();
-	nr_used_buffers--;
-#if RAID5_DEBUG
-	if (bh->b_size == 1024)
-		used_1024--;
-	if (bh->b_size == 4096)
-		used_4096--;
-#endif
-	if (nr_free_buffers < RAID5_POOL_SIZE) {
-#if 0 /* This can magically catch races :-) */
-		char *b_data = ((volatile struct buffer_head *) bh)->b_data;
-		int b_size = ((volatile struct buffer_head *) bh)->b_size;
-		memset (bh, 0, sizeof (struct buffer_head));
-		((volatile struct buffer_head *) bh)->b_data = b_data;
-		((volatile struct buffer_head *) bh)->b_size = b_size;
-#endif
-		add_bh (bh);
-		wake_up (&raid5_wait_for_bh);
-	} else {
-		if (bh->b_size == PAGE_SIZE)
-			free_page ((unsigned long) bh->b_data);
-		else
-			kfree (bh->b_data);
-#if 0
-		memset (bh, 0, sizeof (struct buffer_head));
-#endif
-		kfree (bh);
+	if ((bh = sh->bh_pool) == NULL) {
+		restore_flags(flags);
+		return NULL;
 	}
-#if RAID5_DEBUG
-	printk ("kfree_bh: nr_free == %d, nr_used == %d, max_nr_used == %d\n", nr_free_buffers, nr_used_buffers, max_nr_used_buffers);
-#endif
+	sh->bh_pool = bh->b_next;
+	restore_flags(flags);
+	return bh;
+}
+
+static void put_free_buffer(struct stripe_head *sh, struct buffer_head *bh)
+{
+	unsigned long flags;
+
+	save_flags(flags);
+	cli();
+	bh->b_next = sh->buffer_pool;
+	sh->buffer_pool = bh;
+	restore_flags(flags);
+}
+
+static void put_free_bh(struct stripe_head *sh, struct buffer_head *bh)
+{
+	unsigned long flags;
+
+	save_flags(flags);
+	cli();
+	bh->b_next = sh->bh_pool;
+	sh->bh_pool = bh;
+	restore_flags(flags);
+}
+
+static struct stripe_head *get_free_stripe(raid5_conf_t *conf)
+{
+	struct stripe_head *sh;
+	unsigned long flags;
+
+	save_flags(flags);
+	cli();
+	if ((sh = conf->free_sh_list) == NULL) {
+		restore_flags(flags);
+		return NULL;
+	}
+	conf->free_sh_list = sh->free_next;
+	conf->nr_free_sh--;
+	if (!conf->nr_free_sh && conf->free_sh_list)
+		printk ("raid5: bug: free_sh_list != NULL, nr_free_sh == 0\n");
+	restore_flags(flags);
+	if (sh->hash_pprev || sh->nr_pending || sh->count)
+		printk("get_free_stripe(): bug\n");
+	return sh;
+}
+
+static void put_free_stripe(raid5_conf_t *conf, struct stripe_head *sh)
+{
+	unsigned long flags;
+
+	save_flags(flags);
+	cli();
+	sh->free_next = conf->free_sh_list;
+	conf->free_sh_list = sh;
+	conf->nr_free_sh++;
+	restore_flags(flags);
+}
+
+static void shrink_buffers(struct stripe_head *sh, int num)
+{
+	struct buffer_head *bh;
+
+	while (num--) {
+		if ((bh = get_free_buffer(sh, -1)) == NULL)
+			return;
+		free_page((unsigned long) bh->b_data);
+		kfree(bh);
+	}
+}
+
+static void shrink_bh(struct stripe_head *sh, int num)
+{
+	struct buffer_head *bh;
+
+	while (num--) {
+		if ((bh = get_free_bh(sh)) == NULL)
+			return;
+		kfree(bh);
+	}
+}
+
+static int grow_buffers(struct stripe_head *sh, int num, int b_size, int priority)
+{
+	struct buffer_head *bh;
+
+	while (num--) {
+		if ((bh = kmalloc(sizeof(struct buffer_head), priority)) == NULL)
+			return 1;
+		memset(bh, 0, sizeof (struct buffer_head));
+		bh->b_data = (char *) __get_free_page(priority);
+		if (!bh->b_data) {
+			kfree(bh);
+			return 1;
+		}
+		bh->b_size = b_size;
+		put_free_buffer(sh, bh);
+	}
+	return 0;
+}
+
+static int grow_bh(struct stripe_head *sh, int num, int priority)
+{
+	struct buffer_head *bh;
+
+	while (num--) {
+		if ((bh = kmalloc(sizeof(struct buffer_head), priority)) == NULL)
+			return 1;
+		memset(bh, 0, sizeof (struct buffer_head));
+		put_free_bh(sh, bh);
+	}
+	return 0;
+}
+
+static void raid5_kfree_buffer(struct stripe_head *sh, struct buffer_head *bh)
+{
+	unsigned long flags;
+
+	save_flags(flags);
+	cli();
+	put_free_buffer(sh, bh);
+	restore_flags(flags);
+}
+
+static void raid5_kfree_bh(struct stripe_head *sh, struct buffer_head *bh)
+{
+	unsigned long flags;
+
+	save_flags(flags);
+	cli();
+	put_free_bh(sh, bh);
 	restore_flags(flags);
 }
 
@@ -279,7 +310,7 @@
 		printk("raid5_kfree_old_bh: bug: sector %lu, index %d not present\n", sh->sector, i);
 		return;
 	}
-	raid5_kfree_bh(sh->bh_old[i]);
+	raid5_kfree_buffer(sh, sh->bh_old[i]);
 	sh->bh_old[i] = NULL;
 }
 
@@ -298,8 +329,8 @@
 
 static void kfree_stripe(struct stripe_head *sh)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int disks = raid_conf->raid_disks, j;
+	raid5_conf_t *conf = sh->raid_conf;
+	int disks = conf->raid_disks, j;
 
 	PRINTK(("kfree_stripe called, stripe %lu\n", sh->sector));
 	if (sh->phase != PHASE_COMPLETE || stripe_locked(sh) || sh->count) {
@@ -312,20 +343,19 @@
 		if (sh->bh_new[j] || sh->bh_copy[j])
 			printk("raid5: bug: sector %lu, new %p, copy %p\n", sh->sector, sh->bh_new[j], sh->bh_copy[j]);
 	}
-	remove_hash(sh);
-	kfree(sh);
+	remove_hash(conf, sh);
+	put_free_stripe(conf, sh);
 }
 
-static int shrink_stripe_cache(int nr)
+static int shrink_stripe_cache(raid5_conf_t *conf, int nr)
 {
 	struct stripe_head *sh;
 	int i, count = 0;
-	static int clock = 0;
 
-	PRINTK(("shrink_stripe_cache called, %d/%d, clock %d\n", nr, nr_stripes, clock));
+	PRINTK(("shrink_stripe_cache called, %d/%d, clock %d\n", nr, conf->nr_hashed_stripes, conf->clock));
 	for (i = 0; i < NR_HASH; i++) {
 repeat:
-		sh = stripe_hashtbl[(i + clock) & HASH_MASK];
+		sh = conf->stripe_hashtbl[(i + conf->clock) & HASH_MASK];
 		for (; sh; sh = sh->hash_next) {
 			if (sh->phase != PHASE_COMPLETE)
 				continue;
@@ -335,30 +365,30 @@
 				continue;
 			kfree_stripe(sh);
 			if (++count == nr) {
-				PRINTK(("shrink completed, nr_stripes %d\n", nr_stripes));
-				clock = (i + clock) & HASH_MASK;
+				PRINTK(("shrink completed, nr_hashed_stripes %d\n", conf->nr_hashed_stripes));
+				conf->clock = (i + conf->clock) & HASH_MASK;
 				return nr;
 			}
 			goto repeat;
 		}
 	}
-	PRINTK(("shrink completed, nr_stripes %d\n", nr_stripes));
+	PRINTK(("shrink completed, nr_hashed_stripes %d\n", conf->nr_hashed_stripes));
 	return count;
 }
 
-static struct stripe_head *find_stripe(struct raid5_data *raid_conf, unsigned long sector, int size)
+static struct stripe_head *find_stripe(raid5_conf_t *conf, unsigned long sector, int size)
 {
 	struct stripe_head *sh;
 
-	if (raid_conf->buffer_size != size) {
-		PRINTK(("switching size, %d --> %d\n", raid_conf->buffer_size, size));
-		shrink_stripe_cache(RAID5_STRIPE_POOL_SIZE);
-		raid_conf->buffer_size = size;
+	if (conf->buffer_size != size) {
+		PRINTK(("switching size, %d --> %d\n", conf->buffer_size, size));
+		shrink_stripe_cache(conf, conf->max_nr_stripes);
+		conf->buffer_size = size;
 	}
 
 	PRINTK(("find_stripe, sector %lu\n", sector));
-	for (sh = stripe_hash(sector, size); sh; sh = sh->hash_next)
-		if (sh->sector == sector && sh->raid_conf == raid_conf) {
+	for (sh = stripe_hash(conf, sector, size); sh; sh = sh->hash_next)
+		if (sh->sector == sector && sh->raid_conf == conf) {
 			if (sh->size == size) {
 				PRINTK(("found stripe %lu\n", sector));
 				return sh;
@@ -372,179 +402,119 @@
 	return NULL;
 }
 
-static struct stripe_head *kmalloc_stripe(struct raid5_data *raid_conf, unsigned long sector, int size)
+static int grow_stripes(raid5_conf_t *conf, int num, int priority)
+{
+	struct stripe_head *sh;
+
+	while (num--) {
+		if ((sh = kmalloc(sizeof(struct stripe_head), priority)) == NULL)
+			return 1;
+		memset(sh, 0, sizeof(*sh));
+		if (grow_buffers(sh, 2 * conf->raid_disks, PAGE_SIZE, priority)) {
+			shrink_buffers(sh, 2 * conf->raid_disks);
+			kfree(sh);
+			return 1;
+		}
+		if (grow_bh(sh, conf->raid_disks, priority)) {
+			shrink_buffers(sh, 2 * conf->raid_disks);
+			shrink_bh(sh, conf->raid_disks);
+			kfree(sh);
+			return 1;
+		}
+		put_free_stripe(conf, sh);
+		conf->nr_stripes++;
+	}
+	return 0;
+}
+
+static void shrink_stripes(raid5_conf_t *conf, int num)
+{
+	struct stripe_head *sh;
+
+	while (num--) {
+		sh = get_free_stripe(conf);
+		if (!sh)
+			break;
+		shrink_buffers(sh, conf->raid_disks * 2);
+		shrink_bh(sh, conf->raid_disks);
+		kfree(sh);
+		conf->nr_stripes--;
+	}
+}
+
+static struct stripe_head *kmalloc_stripe(raid5_conf_t *conf, unsigned long sector, int size)
 {
 	struct stripe_head *sh = NULL, *tmp;
+	struct buffer_head *buffer_pool, *bh_pool;
 
 	PRINTK(("kmalloc_stripe called\n"));
 
-	while (nr_stripes > RAID5_STRIPE_POOL_SIZE) {
-		shrink_stripe_cache(RAID5_STRIPE_POOL_SIZE / 8);
-		if (nr_stripes <= RAID5_STRIPE_POOL_SIZE)
+	while ((sh = get_free_stripe(conf)) == NULL) {
+		shrink_stripe_cache(conf, conf->max_nr_stripes / 8);
+		if ((sh = get_free_stripe(conf)) != NULL)
 			break;
-		md_wakeup_thread(raid_conf->thread);
+		if (!conf->nr_pending_stripes)
+			printk("raid5: bug: nr_free_sh == 0, nr_pending_stripes == 0\n");
+		md_wakeup_thread(conf->thread);
 		PRINTK(("waiting for some stripes to complete\n"));
-		sleep_on(&raid5_wait_for_stripe);
+		sleep_on(&conf->wait_for_stripe);
 	}
-	md_wakeup_thread(raid_conf->thread);
-	sh = kmalloc(sizeof(*sh), GFP_KERNEL);
 
 	/*
 	 * The above might have slept, so perhaps another process
 	 * already created the stripe for us..
 	 */
-	if ((tmp = find_stripe(raid_conf, sector, size)) != NULL) { 
-		kfree(sh);
+	if ((tmp = find_stripe(conf, sector, size)) != NULL) { 
+		put_free_stripe(conf, sh);
 		wait_on_stripe(tmp);
 		return tmp;
 	}
 	if (sh) {
+		buffer_pool = sh->buffer_pool;
+		bh_pool = sh->bh_pool;
 		memset(sh, 0, sizeof(*sh));
+		sh->buffer_pool = buffer_pool;
+		sh->bh_pool = bh_pool;
 		sh->phase = PHASE_COMPLETE;
 		sh->cmd = STRIPE_NONE;
-		sh->raid_conf = raid_conf;
+		sh->raid_conf = conf;
 		sh->sector = sector;
 		sh->size = size;
-		insert_hash(sh);
-	}
+		conf->nr_cached_stripes++;
+		insert_hash(conf, sh);
+	} else printk("raid5: bug: kmalloc_stripe() == NULL\n");
 	return sh;
 }
 
-static struct stripe_head *get_stripe(struct raid5_data *raid_conf, unsigned long sector, int size)
+static struct stripe_head *get_stripe(raid5_conf_t *conf, unsigned long sector, int size)
 {
 	struct stripe_head *sh;
 
 	PRINTK(("get_stripe, sector %lu\n", sector));
-	sh = find_stripe(raid_conf, sector, size);
+	sh = find_stripe(conf, sector, size);
 	if (sh)
 		wait_on_stripe(sh);
 	else
-		sh = kmalloc_stripe(raid_conf, sector, size);
+		sh = kmalloc_stripe(conf, sector, size);
 	return sh;
 }
 
-static struct buffer_head *remove_bh (int b_size)
-{
-	struct buffer_head *bh, *bhp = NULL;
-	unsigned long flags;
 
-	save_flags(flags);
-	cli();
-	if ((bh = raid5_buffer_list) == NULL)
-		return NULL;
-	do {
-		if (bh->b_size == b_size || b_size == -1)
-			break;
-		bhp = bh;
-		bh = bh->b_next;
-	} while (bh);
-	if (!bh)
-		return NULL;
-	if (bhp)
-		bhp->b_next = bh->b_next;
-	else
-		raid5_buffer_list = bh->b_next;
-#if RAID5_DEBUG
-	if (bh->b_size == 1024)
-		free_1024--;
-	if (bh->b_size == 4096)
-		free_4096--;
-#endif
-	nr_free_buffers--;
-	if (!nr_free_buffers && raid5_buffer_list)
-		printk ("raid5: bug: buffer_list != NULL, nr_free_buffers == 0\n");
-	restore_flags(flags);
-	return bh;
-}
-
-
-static void shrink_buffers (int num)
+static struct buffer_head *raid5_kmalloc_buffer(struct stripe_head *sh, int b_size)
 {
 	struct buffer_head *bh;
 
-	while (num--) {
-		if ((bh = remove_bh(-1)) == NULL)
-			return;
-		if (bh->b_size == PAGE_SIZE)
-			free_page ((unsigned long) bh->b_data);
-		else
-			kfree (bh->b_data);
-		kfree (bh);
-	}
-}
-
-static void grow_buffers (int num, int b_size, int priority)
-{
-	struct buffer_head *bh;
-
-	while (num--) {
-		bh = kmalloc (sizeof (struct buffer_head), priority);
-		if (!bh)
-			break;
-		memset (bh, 0, sizeof (struct buffer_head));
-		if (b_size == PAGE_SIZE)
-			bh->b_data = (char *) __get_free_page (priority);
-		else
-			bh->b_data = kmalloc (b_size, priority);
-		if (!bh->b_data) {
-			kfree (bh);
-			break;
-		}
-		bh->b_size = b_size;
-		add_bh (bh);
-	}
+	if ((bh = get_free_buffer(sh, b_size)) == NULL)
+		printk("raid5: bug: raid5_kmalloc_buffer() == NULL\n");
+	return bh;
 }
 
-static struct buffer_head *raid5_kmalloc_bh (struct stripe_head *sh, int b_size)
+static struct buffer_head *raid5_kmalloc_bh(struct stripe_head *sh)
 {
 	struct buffer_head *bh;
-	struct raid5_data *raid_conf = sh->raid_conf;
-	unsigned long flags;
 
-	bh = remove_bh(b_size);
-	if (!bh && nr_free_buffers > RAID5_POOL_SIZE / 10)
-		shrink_buffers (RAID5_POOL_SIZE / 10);
-	if (!bh && nr_used_buffers < RAID5_POOL_SIZE) {
-#if 0
-		grow_buffers (200, b_size, GFP_BUFFER);
-#else
-		grow_buffers (200, b_size, GFP_KERNEL);
-#endif
-		bh = remove_bh(b_size);
-	}
-	if (bh == NULL && nr_used_buffers > RAID5_POOL_SIZE / 2) {
-		shrink_stripe_cache(RAID5_STRIPE_POOL_SIZE / 2);
-		bh = remove_bh(b_size);
-	}
-
-	while (bh == NULL && nr_used_buffers > 3 * RAID5_POOL_SIZE / 4) {
-		md_wakeup_thread(raid_conf->thread);
-		run_task_queue (&tq_disk);
-		unplug_devices(sh);
-		PRINTK(("waiting for bh\n"));
-		sleep_on (&raid5_wait_for_bh);
-		bh = remove_bh(b_size);
-	}
-	if (bh == NULL) {
-		grow_buffers (200, b_size, GFP_KERNEL);
-		bh = remove_bh(b_size);
-	}
-	if (bh) {
-		save_flags(flags);
-		cli();
-		nr_used_buffers++;
-		if (nr_used_buffers > max_nr_used_buffers)
-			max_nr_used_buffers = nr_used_buffers;
-#if RAID5_DEBUG
-		if (bh->b_size == 1024)
-			used_1024++;
-		if (bh->b_size == 4096)
-			used_4096++;
-		printk ("kmalloc_bh: free, used, pending, max = %d, %d, %d, %d\n", nr_free_buffers, nr_used_buffers, nr_pending, max_nr_used_buffers);
-		printk ("kmalloc_bh: free1, used1, free4, used4 = %d, %d, %d, %d\n", free_1024, used_1024, free_4096, used_4096);
-#endif
-		restore_flags(flags);
-	}
+	if ((bh = get_free_bh(sh)) == NULL)
+		printk("raid5: bug: raid5_kmalloc_bh() == NULL\n");
 	return bh;
 }
 
@@ -553,14 +523,12 @@
 	struct buffer_head *bh = sh->bh_new[i];
 
 	sh->bh_new[i] = NULL;
-	clear_bit (BH_MD, &bh->b_state);
-	bh->private_bh = NULL;
-	bh->personality = NULL;
-	mark_buffer_uptodate(bh, uptodate);
-	unlock_buffer(bh);
+	raid5_kfree_bh(sh, sh->bh_req[i]);
+	sh->bh_req[i] = NULL;
+	bh->b_end_io(bh, uptodate);
 	if (!uptodate)
 		printk(KERN_ALERT "raid5: %s: unrecoverable I/O error for "
-		       "block %lu\n", kdevname(bh->b_dev), bh->b_blocknr);
+		       "block %lu\n", partition_name(bh->b_dev), bh->b_blocknr);
 }
 
 static inline void raid5_mark_buffer_uptodate (struct buffer_head *bh, int uptodate)
@@ -573,9 +541,9 @@
 
 static void raid5_end_request (struct buffer_head * bh, int uptodate)
 {
-	struct stripe_head *sh = bh->private_bh;
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int disks = raid_conf->raid_disks, i;
+	struct stripe_head *sh = bh->b_dev_id;
+	raid5_conf_t *conf = sh->raid_conf;
+	int disks = conf->raid_disks, i;
 	unsigned long flags;
 
 	PRINTK(("end_request %lu, nr_pending %d\n", sh->sector, sh->nr_pending));
@@ -584,22 +552,19 @@
 	raid5_mark_buffer_uptodate(bh, uptodate);
 	--sh->nr_pending;
 	if (!sh->nr_pending) {
-		md_wakeup_thread(raid_conf->thread);
-		atomic_inc(&raid_conf->nr_handle);
-		if (!stripe_handle_tail)
-			stripe_handle_list = sh;
-		else
-			stripe_handle_tail->handle_next = sh;
-		sh->handle_next = NULL;
-		stripe_handle_tail = sh;
+		md_wakeup_thread(conf->thread);
+		atomic_inc(&conf->nr_handle);
 	}
-	if (!uptodate)
+	if (!uptodate) {
 		md_error(bh->b_dev, bh->b_rdev);
-	if (raid_conf->failed_disks) {
+	}
+	if (conf->failed_disks) {
 		for (i = 0; i < disks; i++) {
-			if (raid_conf->disks[i].operational)
+			if (conf->disks[i].operational)
+				continue;
+			if (bh != sh->bh_old[i] && bh != sh->bh_req[i] && bh != sh->bh_copy[i])
 				continue;
-			if (bh != sh->bh_old[i] && bh != sh->bh_new[i] && bh != sh->bh_copy[i])
+			if (bh->b_rdev != conf->disks[i].dev)
 				continue;
 			set_bit(STRIPE_ERROR, &sh->state);
 		}
@@ -607,7 +572,7 @@
 	restore_flags(flags);
 }
 
-static int raid5_map (struct md_dev *mddev, kdev_t *rdev,
+static int raid5_map (mddev_t *mddev, kdev_t *rdev,
 		      unsigned long *rsector, unsigned long size)
 {
 	/* No complex mapping used: the core of the work is done in the
@@ -618,55 +583,81 @@
 
 static void raid5_build_block (struct stripe_head *sh, struct buffer_head *bh, int i)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	struct md_dev *mddev = raid_conf->mddev;
-	int minor = (int) (mddev - md_dev);
+	raid5_conf_t *conf = sh->raid_conf;
+	mddev_t *mddev = conf->mddev;
 	char *b_data;
+	kdev_t dev = mddev_to_kdev(mddev);
+	int block = sh->sector / (sh->size >> 9);
 
 	b_data = ((volatile struct buffer_head *) bh)->b_data;
 	memset (bh, 0, sizeof (struct buffer_head));
+	init_buffer(bh, dev, block, raid5_end_request, sh);
 	((volatile struct buffer_head *) bh)->b_data = b_data;
 
-	bh->personality	= &raid5_personality;
-	bh->private_bh  = (void *) sh;
-
-	bh->b_rdev	= raid_conf->disks[i].dev;
-	bh->b_dev	= MKDEV(MD_MAJOR, minor);
+	bh->b_rdev	= conf->disks[i].dev;
 	bh->b_rsector   = sh->sector;
-	bh->b_blocknr   = sh->sector / (sh->size >> 9);
 
-	bh->b_state	= (1 << BH_MD) | (1 << BH_Req);
-	bh->b_count	= 1;
+	bh->b_state	= (1 << BH_Req);
 	bh->b_size	= sh->size;
 	bh->b_list	= BUF_LOCKED;
 }
 
-static int raid5_error (struct md_dev *mddev, kdev_t dev)
+static int raid5_error (mddev_t *mddev, kdev_t dev)
 {
-	struct raid5_data *raid_conf = (struct raid5_data *) mddev->private;
-	md_superblock_t *sb = mddev->sb;
+	raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
+	mdp_super_t *sb = mddev->sb;
 	struct disk_info *disk;
 	int i;
 
 	PRINTK(("raid5_error called\n"));
-	for (i = 0, disk = raid_conf->disks; i < raid_conf->raid_disks; i++, disk++)
+	conf->resync_parity = 0;
+	for (i = 0, disk = conf->disks; i < conf->raid_disks; i++, disk++) {
 		if (disk->dev == dev && disk->operational) {
 			disk->operational = 0;
-			sb->disks[disk->number].state |= (1 << MD_FAULTY_DEVICE);
-			sb->disks[disk->number].state &= ~(1 << MD_SYNC_DEVICE);
-			sb->disks[disk->number].state &= ~(1 << MD_ACTIVE_DEVICE);
+			mark_disk_faulty(sb->disks+disk->number);
+			mark_disk_nonsync(sb->disks+disk->number);
+			mark_disk_inactive(sb->disks+disk->number);
 			sb->active_disks--;
 			sb->working_disks--;
 			sb->failed_disks++;
 			mddev->sb_dirty = 1;
-			raid_conf->working_disks--;
-			raid_conf->failed_disks++;
-			md_wakeup_thread(raid_conf->thread);
+			conf->working_disks--;
+			conf->failed_disks++;
+			md_wakeup_thread(conf->thread);
 			printk (KERN_ALERT
-				"RAID5: Disk failure on %s, disabling device."
-				"Operation continuing on %d devices\n",
-				kdevname (dev), raid_conf->working_disks);
+				"raid5: Disk failure on %s, disabling device."
+				" Operation continuing on %d devices\n",
+				partition_name (dev), conf->working_disks);
+			return -EIO;
 		}
+	}
+	/*
+	 * handle errors in spares (during reconstruction)
+	 */
+	if (conf->spare) {
+		disk = conf->spare;
+		if (disk->dev == dev) {
+			printk (KERN_ALERT
+				"raid5: Disk failure on spare %s\n",
+				partition_name (dev));
+			if (!conf->spare->operational) {
+				MD_BUG();
+				return -EIO;
+			}
+			disk->operational = 0;
+			disk->write_only = 0;
+			conf->spare = NULL;
+			mark_disk_faulty(sb->disks+disk->number);
+			mark_disk_nonsync(sb->disks+disk->number);
+			mark_disk_inactive(sb->disks+disk->number);
+			sb->spare_disks--;
+			sb->working_disks--;
+			sb->failed_disks++;
+
+			return -EIO;
+		}
+	}
+	MD_BUG();
 	return 0;
 }	
 
@@ -677,12 +668,12 @@
 static inline unsigned long 
 raid5_compute_sector (int r_sector, unsigned int raid_disks, unsigned int data_disks,
 			unsigned int * dd_idx, unsigned int * pd_idx, 
-			struct raid5_data *raid_conf)
+			raid5_conf_t *conf)
 {
 	unsigned int  stripe;
 	int chunk_number, chunk_offset;
 	unsigned long new_sector;
-	int sectors_per_chunk = raid_conf->chunk_size >> 9;
+	int sectors_per_chunk = conf->chunk_size >> 9;
 
 	/* First compute the information on this sector */
 
@@ -705,9 +696,9 @@
 	/*
 	 * Select the parity disk based on the user selected algorithm.
 	 */
-	if (raid_conf->level == 4)
+	if (conf->level == 4)
 		*pd_idx = data_disks;
-	else switch (raid_conf->algorithm) {
+	else switch (conf->algorithm) {
 		case ALGORITHM_LEFT_ASYMMETRIC:
 			*pd_idx = data_disks - stripe % raid_disks;
 			if (*dd_idx >= *pd_idx)
@@ -727,7 +718,7 @@
 			*dd_idx = (*pd_idx + 1 + *dd_idx) % raid_disks;
 			break;
 		default:
-			printk ("raid5: unsupported algorithm %d\n", raid_conf->algorithm);
+			printk ("raid5: unsupported algorithm %d\n", conf->algorithm);
 	}
 
 	/*
@@ -748,16 +739,16 @@
 
 static unsigned long compute_blocknr(struct stripe_head *sh, int i)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int raid_disks = raid_conf->raid_disks, data_disks = raid_disks - 1;
+	raid5_conf_t *conf = sh->raid_conf;
+	int raid_disks = conf->raid_disks, data_disks = raid_disks - 1;
 	unsigned long new_sector = sh->sector, check;
-	int sectors_per_chunk = raid_conf->chunk_size >> 9;
+	int sectors_per_chunk = conf->chunk_size >> 9;
 	unsigned long stripe = new_sector / sectors_per_chunk;
 	int chunk_offset = new_sector % sectors_per_chunk;
 	int chunk_number, dummy1, dummy2, dd_idx = i;
 	unsigned long r_sector, blocknr;
 
-	switch (raid_conf->algorithm) {
+	switch (conf->algorithm) {
 		case ALGORITHM_LEFT_ASYMMETRIC:
 		case ALGORITHM_RIGHT_ASYMMETRIC:
 			if (i > sh->pd_idx)
@@ -770,14 +761,14 @@
 			i -= (sh->pd_idx + 1);
 			break;
 		default:
-			printk ("raid5: unsupported algorithm %d\n", raid_conf->algorithm);
+			printk ("raid5: unsupported algorithm %d\n", conf->algorithm);
 	}
 
 	chunk_number = stripe * data_disks + i;
 	r_sector = chunk_number * sectors_per_chunk + chunk_offset;
 	blocknr = r_sector / (sh->size >> 9);
 
-	check = raid5_compute_sector (r_sector, raid_disks, data_disks, &dummy1, &dummy2, raid_conf);
+	check = raid5_compute_sector (r_sector, raid_disks, data_disks, &dummy1, &dummy2, conf);
 	if (check != sh->sector || dummy1 != dd_idx || dummy2 != sh->pd_idx) {
 		printk("compute_blocknr: map not correct\n");
 		return 0;
@@ -785,34 +776,15 @@
 	return blocknr;
 }
 
-static void xor_block(struct buffer_head *dest, struct buffer_head *source)
-{
-	int lines = dest->b_size / (sizeof (int)) / 8, i;
-	int *destp = (int *) dest->b_data, *sourcep = (int *) source->b_data;
-
-	for (i = lines; i > 0; i--) {
-		*(destp + 0) ^= *(sourcep + 0);
-		*(destp + 1) ^= *(sourcep + 1);
-		*(destp + 2) ^= *(sourcep + 2);
-		*(destp + 3) ^= *(sourcep + 3);
-		*(destp + 4) ^= *(sourcep + 4);
-		*(destp + 5) ^= *(sourcep + 5);
-		*(destp + 6) ^= *(sourcep + 6);
-		*(destp + 7) ^= *(sourcep + 7);
-		destp += 8;
-		sourcep += 8;
-	}
-}
-
 static void compute_block(struct stripe_head *sh, int dd_idx)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int i, disks = raid_conf->raid_disks;
+	raid5_conf_t *conf = sh->raid_conf;
+	int i, disks = conf->raid_disks;
 
 	PRINTK(("compute_block, stripe %lu, idx %d\n", sh->sector, dd_idx));
 
 	if (sh->bh_old[dd_idx] == NULL)
-		sh->bh_old[dd_idx] = raid5_kmalloc_bh(sh, sh->size);
+		sh->bh_old[dd_idx] = raid5_kmalloc_buffer(sh, sh->size);
 	raid5_build_block(sh, sh->bh_old[dd_idx], dd_idx);
 
 	memset(sh->bh_old[dd_idx]->b_data, 0, sh->size);
@@ -830,21 +802,21 @@
 
 static void compute_parity(struct stripe_head *sh, int method)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int i, pd_idx = sh->pd_idx, disks = raid_conf->raid_disks;
+	raid5_conf_t *conf = sh->raid_conf;
+	int i, pd_idx = sh->pd_idx, disks = conf->raid_disks;
 
 	PRINTK(("compute_parity, stripe %lu, method %d\n", sh->sector, method));
 	for (i = 0; i < disks; i++) {
 		if (i == pd_idx || !sh->bh_new[i])
 			continue;
 		if (!sh->bh_copy[i])
-			sh->bh_copy[i] = raid5_kmalloc_bh(sh, sh->size);
+			sh->bh_copy[i] = raid5_kmalloc_buffer(sh, sh->size);
 		raid5_build_block(sh, sh->bh_copy[i], i);
 		mark_buffer_clean(sh->bh_new[i]);
 		memcpy(sh->bh_copy[i]->b_data, sh->bh_new[i]->b_data, sh->size);
 	}
 	if (sh->bh_copy[pd_idx] == NULL)
-		sh->bh_copy[pd_idx] = raid5_kmalloc_bh(sh, sh->size);
+		sh->bh_copy[pd_idx] = raid5_kmalloc_buffer(sh, sh->size);
 	raid5_build_block(sh, sh->bh_copy[pd_idx], sh->pd_idx);
 
 	if (method == RECONSTRUCT_WRITE) {
@@ -878,33 +850,37 @@
 
 static void add_stripe_bh (struct stripe_head *sh, struct buffer_head *bh, int dd_idx, int rw)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
+	raid5_conf_t *conf = sh->raid_conf;
+	struct buffer_head *bh_req;
 
-	if (sh->bh_new[dd_idx])
+	if (sh->bh_new[dd_idx]) {
 		printk("raid5: bug: stripe->bh_new[%d], sector %lu exists\n", dd_idx, sh->sector);
+		printk("forcing oops.\n");
+		*(int*)0=0;
+	}
 
-	set_bit(BH_MD, &bh->b_state);
 	set_bit(BH_Lock, &bh->b_state);
-	bh->personality  = &raid5_personality;
-	bh->private_bh   = (void *) sh;
-	bh->b_rdev    = raid_conf->disks[dd_idx].dev;
-	bh->b_rsector = sh->sector;
+
+	bh_req = raid5_kmalloc_bh(sh);
+	raid5_build_block(sh, bh_req, dd_idx);
+	bh_req->b_data = bh->b_data;
 
 	if (sh->phase == PHASE_COMPLETE && sh->cmd == STRIPE_NONE) {
 		sh->phase = PHASE_BEGIN;
 		sh->cmd = (rw == READ) ? STRIPE_READ : STRIPE_WRITE;
-		nr_pending_stripes++;
-		atomic_inc(&raid_conf->nr_handle);
+		conf->nr_pending_stripes++;
+		atomic_inc(&conf->nr_handle);
 	}
 	sh->bh_new[dd_idx] = bh;
+	sh->bh_req[dd_idx] = bh_req;
 	sh->cmd_new[dd_idx] = rw;
 	sh->new[dd_idx] = 1;
 }
 
 static void complete_stripe(struct stripe_head *sh)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	int disks = raid_conf->raid_disks;
+	raid5_conf_t *conf = sh->raid_conf;
+	int disks = conf->raid_disks;
 	int i, new = 0;
 	
 	PRINTK(("complete_stripe %lu\n", sh->sector));
@@ -951,17 +927,16 @@
  * 2.	We should be careful to set sh->nr_pending whenever we sleep,
  *	to prevent re-entry of handle_stripe() for the same sh.
  *
- * 3.	raid_conf->failed_disks and disk->operational can be changed
+ * 3.	conf->failed_disks and disk->operational can be changed
  *	from an interrupt. This complicates things a bit, but it allows
  *	us to stop issuing requests for a failed drive as soon as possible.
  */
 static void handle_stripe(struct stripe_head *sh)
 {
-	struct raid5_data *raid_conf = sh->raid_conf;
-	struct md_dev *mddev = raid_conf->mddev;
-	int minor = (int) (mddev - md_dev);
+	raid5_conf_t *conf = sh->raid_conf;
+	mddev_t *mddev = conf->mddev;
 	struct buffer_head *bh;
-	int disks = raid_conf->raid_disks;
+	int disks = conf->raid_disks;
 	int i, nr = 0, nr_read = 0, nr_write = 0;
 	int nr_cache = 0, nr_cache_other = 0, nr_cache_overwrite = 0, parity = 0;
 	int nr_failed_other = 0, nr_failed_overwrite = 0, parity_failed = 0;
@@ -969,7 +944,7 @@
 	int method1 = INT_MAX, method2 = INT_MAX;
 	int block;
 	unsigned long flags;
-	int operational[MD_SB_DISKS], failed_disks = raid_conf->failed_disks;
+	int operational[MD_SB_DISKS], failed_disks = conf->failed_disks;
 
 	PRINTK(("handle_stripe(), stripe %lu\n", sh->sector));
 	if (sh->nr_pending) {
@@ -981,9 +956,9 @@
 		return;
 	}
 
-	atomic_dec(&raid_conf->nr_handle);
+	atomic_dec(&conf->nr_handle);
 
-	if (clear_bit(STRIPE_ERROR, &sh->state)) {
+	if (md_test_and_clear_bit(STRIPE_ERROR, &sh->state)) {
 		printk("raid5: restarting stripe %lu\n", sh->sector);
 		sh->phase = PHASE_BEGIN;
 	}
@@ -1000,9 +975,12 @@
 
 	save_flags(flags);
 	cli();
-	for (i = 0; i < disks; i++)
-		operational[i] = raid_conf->disks[i].operational;
-	failed_disks = raid_conf->failed_disks;
+	for (i = 0; i < disks; i++) {
+		operational[i] = conf->disks[i].operational;
+		if (i == sh->pd_idx && conf->resync_parity)
+			operational[i] = 0;
+	}
+	failed_disks = conf->failed_disks;
 	restore_flags(flags);
 
 	if (failed_disks > 1) {
@@ -1046,7 +1024,7 @@
 	}
 
 	if (nr_write && nr_read)
-		printk("raid5: bug, nr_write == %d, nr_read == %d, sh->cmd == %d\n", nr_write, nr_read, sh->cmd);
+		printk("raid5: bug, nr_write ==`%d, nr_read == %d, sh->cmd == %d\n", nr_write, nr_read, sh->cmd);
 
 	if (nr_write) {
 		/*
@@ -1059,7 +1037,7 @@
 				if (sh->bh_new[i])
 					continue;
 				block = (int) compute_blocknr(sh, i);
-				bh = efind_buffer(MKDEV(MD_MAJOR, minor), block, sh->size);
+				bh = find_buffer(mddev_to_kdev(mddev), block, sh->size);
 				if (bh && bh->b_count == 0 && buffer_dirty(bh) && !buffer_locked(bh)) {
 					PRINTK(("Whee.. sector %lu, index %d (%d) found in the buffer cache!\n", sh->sector, i, block));
 					add_stripe_bh(sh, bh, i, WRITE);
@@ -1097,7 +1075,7 @@
 			sh->phase = PHASE_WRITE;
 			compute_parity(sh, method1 <= method2 ? RECONSTRUCT_WRITE : READ_MODIFY_WRITE);
 			for (i = 0; i < disks; i++) {
-				if (!operational[i])
+				if (!operational[i] && !conf->spare && !conf->resync_parity)
 					continue;
 				if (i == sh->pd_idx || sh->bh_new[i])
 					nr_writing++;
@@ -1107,7 +1085,7 @@
 			PRINTK(("handle_stripe() %lu, writing back %d\n", sh->sector, sh->nr_pending));
 
 			for (i = 0; i < disks; i++) {
-				if (!operational[i])
+				if (!operational[i] && !conf->spare && !conf->resync_parity)
 					continue;
 				bh = sh->bh_copy[i];
 				if (i != sh->pd_idx && ((bh == NULL) ^ (sh->bh_new[i] == NULL)))
@@ -1118,7 +1096,11 @@
 					bh->b_state |= (1<<BH_Dirty);
 					PRINTK(("making request for buffer %d\n", i));
 					clear_bit(BH_Lock, &bh->b_state);
-					make_request(MAJOR(raid_conf->disks[i].dev), WRITE, bh);
+					if (!operational[i] && !conf->resync_parity) {
+						bh->b_rdev = conf->spare->dev;
+						make_request(MAJOR(conf->spare->dev), WRITE, bh);
+					} else
+						make_request(MAJOR(conf->disks[i].dev), WRITE, bh);
 				}
 			}
 			return;
@@ -1133,7 +1115,7 @@
 					continue;
 				if (sh->bh_new[i] || sh->bh_old[i])
 					continue;
-				sh->bh_old[i] = raid5_kmalloc_bh(sh, sh->size);
+				sh->bh_old[i] = raid5_kmalloc_buffer(sh, sh->size);
 				raid5_build_block(sh, sh->bh_old[i], i);
 				reading++;
 			}
@@ -1144,7 +1126,7 @@
 					continue;
 				if (!sh->bh_new[i] && i != sh->pd_idx)
 					continue;
-				sh->bh_old[i] = raid5_kmalloc_bh(sh, sh->size);
+				sh->bh_old[i] = raid5_kmalloc_buffer(sh, sh->size);
 				raid5_build_block(sh, sh->bh_old[i], i);
 				reading++;
 			}
@@ -1158,7 +1140,7 @@
 			if (buffer_uptodate(sh->bh_old[i]))
 				continue;
 		 	clear_bit(BH_Lock, &sh->bh_old[i]->b_state);
-			make_request(MAJOR(raid_conf->disks[i].dev), READ, sh->bh_old[i]);
+			make_request(MAJOR(conf->disks[i].dev), READ, sh->bh_old[i]);
 		}
 	} else {
 		/*
@@ -1191,10 +1173,10 @@
 					continue;
 				if (!operational[i])
 					continue;
-				sh->bh_old[i] = raid5_kmalloc_bh(sh, sh->size);
+				sh->bh_old[i] = raid5_kmalloc_buffer(sh, sh->size);
 				raid5_build_block(sh, sh->bh_old[i], i);
 			 	clear_bit(BH_Lock, &sh->bh_old[i]->b_state);
-				make_request(MAJOR(raid_conf->disks[i].dev), READ, sh->bh_old[i]);
+				make_request(MAJOR(conf->disks[i].dev), READ, sh->bh_old[i]);
 			}
 		} else {
 			sh->phase = PHASE_READ;
@@ -1207,17 +1189,16 @@
 					memcpy(sh->bh_new[i]->b_data, sh->bh_old[i]->b_data, sh->size);
 					continue;
 				}
-				clear_bit(BH_Lock, &sh->bh_new[i]->b_state);
-				make_request(MAJOR(raid_conf->disks[i].dev), READ, sh->bh_new[i]);
+				make_request(MAJOR(conf->disks[i].dev), READ, sh->bh_req[i]);
 			}
 		}
 	}
 }
 
-static int raid5_make_request (struct md_dev *mddev, int rw, struct buffer_head * bh)
+static int raid5_make_request (mddev_t *mddev, int rw, struct buffer_head * bh)
 {
-	struct raid5_data *raid_conf = (struct raid5_data *) mddev->private;
-	const unsigned int raid_disks = raid_conf->raid_disks;
+	raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
+	const unsigned int raid_disks = conf->raid_disks;
 	const unsigned int data_disks = raid_disks - 1;
 	unsigned int  dd_idx, pd_idx;
 	unsigned long new_sector;
@@ -1228,26 +1209,46 @@
 	if (rw == WRITEA) rw = WRITE;
 
 	new_sector = raid5_compute_sector(bh->b_rsector, raid_disks, data_disks,
-						&dd_idx, &pd_idx, raid_conf);
+						&dd_idx, &pd_idx, conf);
 
 	PRINTK(("raid5_make_request, sector %lu\n", new_sector));
-	sh = get_stripe(raid_conf, new_sector, bh->b_size);
+repeat:
+	sh = get_stripe(conf, new_sector, bh->b_size);
 	if ((rw == READ && sh->cmd == STRIPE_WRITE) || (rw == WRITE && sh->cmd == STRIPE_READ)) {
-		printk("raid5: lock contention, rw == %d, sh->cmd == %d\n", rw, sh->cmd);
+		PRINTK(("raid5: lock contention, rw == %d, sh->cmd == %d\n", rw, sh->cmd));
 		lock_stripe(sh);
 		if (!sh->nr_pending)
 			handle_stripe(sh);
-		wait_on_stripe(sh);
+		goto repeat;
 	}
 	sh->pd_idx = pd_idx;
 	if (sh->phase != PHASE_COMPLETE && sh->phase != PHASE_BEGIN)
 		PRINTK(("stripe %lu catching the bus!\n", sh->sector));
+	if (sh->bh_new[dd_idx]) {
+		printk("raid5: bug: stripe->bh_new[%d], sector %lu exists\n", dd_idx, sh->sector);
+		printk("raid5: bh %p, bh_new %p\n", bh, sh->bh_new[dd_idx]);
+		lock_stripe(sh);
+		md_wakeup_thread(conf->thread);
+		wait_on_stripe(sh);
+		goto repeat;
+	}
 	add_stripe_bh(sh, bh, dd_idx, rw);
 
-	md_wakeup_thread(raid_conf->thread);
+	md_wakeup_thread(conf->thread);
 	return 0;
 }
 
+static void unplug_devices(struct stripe_head *sh)
+{
+#if 0
+	raid5_conf_t *conf = sh->raid_conf;
+	int i;
+
+	for (i = 0; i < conf->raid_disks; i++)
+		unplug_device(blk_dev + MAJOR(conf->disks[i].dev));
+#endif
+}
+
 /*
  * This is our raid5 kernel thread.
  *
@@ -1258,8 +1259,8 @@
 static void raid5d (void *data)
 {
 	struct stripe_head *sh;
-	struct raid5_data *raid_conf = data;
-	struct md_dev *mddev = raid_conf->mddev;
+	raid5_conf_t *conf = data;
+	mddev_t *mddev = conf->mddev;
 	int i, handled = 0, unplug = 0;
 	unsigned long flags;
 
@@ -1267,206 +1268,713 @@
 
 	if (mddev->sb_dirty) {
 		mddev->sb_dirty = 0;
-		md_update_sb((int) (mddev - md_dev));
+		md_update_sb(mddev);
 	}
-	save_flags(flags);
-	cli();
-	stripe_handle_list = stripe_handle_tail = NULL;
-	restore_flags(flags);
-
 	for (i = 0; i < NR_HASH; i++) {
 repeat:
-		sh = stripe_hashtbl[i];
+		sh = conf->stripe_hashtbl[i];
 		for (; sh; sh = sh->hash_next) {
-			if (sh->raid_conf != raid_conf)
+			if (sh->raid_conf != conf)
 				continue;
 			if (sh->phase == PHASE_COMPLETE)
 				continue;
 			if (sh->nr_pending)
 				continue;
-			if (sh->sector == raid_conf->next_sector) {
-				raid_conf->sector_count += (sh->size >> 9);
-				if (raid_conf->sector_count >= 128)
+			if (sh->sector == conf->next_sector) {
+				conf->sector_count += (sh->size >> 9);
+				if (conf->sector_count >= 128)
 					unplug = 1;
 			} else
 				unplug = 1;
 			if (unplug) {
-				PRINTK(("unplugging devices, sector == %lu, count == %d\n", sh->sector, raid_conf->sector_count));
+				PRINTK(("unplugging devices, sector == %lu, count == %d\n", sh->sector, conf->sector_count));
 				unplug_devices(sh);
 				unplug = 0;
-				raid_conf->sector_count = 0;
+				conf->sector_count = 0;
 			}
-			raid_conf->next_sector = sh->sector + (sh->size >> 9);
+			conf->next_sector = sh->sector + (sh->size >> 9);
 			handled++;
 			handle_stripe(sh);
 			goto repeat;
 		}
 	}
-	if (raid_conf) {
-		PRINTK(("%d stripes handled, nr_handle %d\n", handled, raid_conf->nr_handle));
+	if (conf) {
+		PRINTK(("%d stripes handled, nr_handle %d\n", handled, md_atomic_read(&conf->nr_handle)));
 		save_flags(flags);
 		cli();
-		if (!raid_conf->nr_handle)
-			clear_bit(THREAD_WAKEUP, &raid_conf->thread->flags);
+		if (!md_atomic_read(&conf->nr_handle))
+			clear_bit(THREAD_WAKEUP, &conf->thread->flags);
+		restore_flags(flags);
 	}
 	PRINTK(("--- raid5d inactive\n"));
 }
 
-static int raid5_run (int minor, struct md_dev *mddev)
+/*
+ * Private kernel thread for parity reconstruction after an unclean
+ * shutdown. Reconstruction on spare drives in case of a failed drive
+ * is done by the generic mdsyncd.
+ */
+static void raid5syncd (void *data)
+{
+	raid5_conf_t *conf = data;
+	mddev_t *mddev = conf->mddev;
+
+	if (!conf->resync_parity)
+		return;
+	if (conf->resync_parity == 2)
+		return;
+	if (md_do_sync(mddev,NULL)) {
+		printk("raid5: resync aborted!\n");
+		return;
+	}
+	printk("raid5: resync finished normally.\n");
+	conf->resync_parity = 0;
+}
+
+static int __check_consistency (mddev_t *mddev, int row)
 {
-	struct raid5_data *raid_conf;
-	int i, j, raid_disk;
-	md_superblock_t *sb = mddev->sb;
-	md_descriptor_t *descriptor;
-	struct real_dev *realdev;
+	raid5_conf_t *conf = mddev->private;
+	kdev_t dev;
+	struct buffer_head *bh[MD_SB_DISKS], tmp;
+	int i, rc = 0, nr = 0;
+
+	if (conf->working_disks != conf->raid_disks)
+		return 0;
+	tmp.b_size = 4096;
+	if ((tmp.b_data = (char *) get_free_page(GFP_KERNEL)) == NULL)
+		return 0;
+	md_clear_page((unsigned long)tmp.b_data);
+	memset(bh, 0, MD_SB_DISKS * sizeof(struct buffer_head *));
+	for (i = 0; i < conf->raid_disks; i++) {
+		dev = conf->disks[i].dev;
+		set_blocksize(dev, 4096);
+		if ((bh[i] = bread(dev, row / 4, 4096)) == NULL)
+			break;
+		nr++;
+	}
+	if (nr == conf->raid_disks) {
+		for (i = 1; i < nr; i++)
+			xor_block(&tmp, bh[i]);
+		if (memcmp(tmp.b_data, bh[0]->b_data, 4096))
+			rc = 1;
+	}
+	for (i = 0; i < conf->raid_disks; i++) {
+		dev = conf->disks[i].dev;
+		if (bh[i]) {
+			bforget(bh[i]);
+			bh[i] = NULL;
+		}
+		fsync_dev(dev);
+		invalidate_buffers(dev);
+	}
+	free_page((unsigned long) tmp.b_data);
+	return rc;
+}
+
+static int check_consistency (mddev_t *mddev)
+{
+	if (__check_consistency(mddev, 0))
+/*
+ * We are not checking this currently, as it's legitimate to have
+ * an inconsistent array, at creation time.
+ */
+		return 0;
+
+	return 0;
+}
+
+static int raid5_run (mddev_t *mddev)
+{
+	raid5_conf_t *conf;
+	int i, j, raid_disk, memory;
+	mdp_super_t *sb = mddev->sb;
+	mdp_disk_t *desc;
+	mdk_rdev_t *rdev;
+	struct disk_info *disk;
+	struct md_list_head *tmp;
+	int start_recovery = 0;
 
 	MOD_INC_USE_COUNT;
 
 	if (sb->level != 5 && sb->level != 4) {
-		printk("raid5: %s: raid level not set to 4/5 (%d)\n", kdevname(MKDEV(MD_MAJOR, minor)), sb->level);
+		printk("raid5: md%d: raid level not set to 4/5 (%d)\n", mdidx(mddev), sb->level);
 		MOD_DEC_USE_COUNT;
 		return -EIO;
 	}
 
-	mddev->private = kmalloc (sizeof (struct raid5_data), GFP_KERNEL);
-	raid_conf = mddev->private;
-	memset (raid_conf, 0, sizeof (*raid_conf));
-	raid_conf->mddev = mddev;
-
-	PRINTK(("raid5_run(%d) called.\n", minor));
-
-  	for (i = 0; i < mddev->nb_dev; i++) {
-  		realdev = &mddev->devices[i];
-		if (!realdev->sb) {
-			printk(KERN_ERR "raid5: disabled device %s (couldn't access raid superblock)\n", kdevname(realdev->dev));
-			continue;
-		}
+	mddev->private = kmalloc (sizeof (raid5_conf_t), GFP_KERNEL);
+	if ((conf = mddev->private) == NULL)
+		goto abort;
+	memset (conf, 0, sizeof (*conf));
+	conf->mddev = mddev;
 
+	if ((conf->stripe_hashtbl = (struct stripe_head **) md__get_free_pages(GFP_ATOMIC, HASH_PAGES_ORDER)) == NULL)
+		goto abort;
+	memset(conf->stripe_hashtbl, 0, HASH_PAGES * PAGE_SIZE);
+
+	init_waitqueue(&conf->wait_for_stripe);
+	PRINTK(("raid5_run(md%d) called.\n", mdidx(mddev)));
+
+	ITERATE_RDEV(mddev,rdev,tmp) {
 		/*
 		 * This is important -- we are using the descriptor on
 		 * the disk only to get a pointer to the descriptor on
 		 * the main superblock, which might be more recent.
 		 */
-		descriptor = &sb->disks[realdev->sb->descriptor.number];
-		if (descriptor->state & (1 << MD_FAULTY_DEVICE)) {
-			printk(KERN_ERR "raid5: disabled device %s (errors detected)\n", kdevname(realdev->dev));
+		desc = sb->disks + rdev->desc_nr;
+		raid_disk = desc->raid_disk;
+		disk = conf->disks + raid_disk;
+
+		if (disk_faulty(desc)) {
+			printk(KERN_ERR "raid5: disabled device %s (errors detected)\n", partition_name(rdev->dev));
+			if (!rdev->faulty) {
+				MD_BUG();
+				goto abort;
+			}
+			disk->number = desc->number;
+			disk->raid_disk = raid_disk;
+			disk->dev = rdev->dev;
+
+			disk->operational = 0;
+			disk->write_only = 0;
+			disk->spare = 0;
+			disk->used_slot = 1;
 			continue;
 		}
-		if (descriptor->state & (1 << MD_ACTIVE_DEVICE)) {
-			if (!(descriptor->state & (1 << MD_SYNC_DEVICE))) {
-				printk(KERN_ERR "raid5: disabled device %s (not in sync)\n", kdevname(realdev->dev));
-				continue;
+		if (disk_active(desc)) {
+			if (!disk_sync(desc)) {
+				printk(KERN_ERR "raid5: disabled device %s (not in sync)\n", partition_name(rdev->dev));
+				MD_BUG();
+				goto abort;
 			}
-			raid_disk = descriptor->raid_disk;
-			if (descriptor->number > sb->nr_disks || raid_disk > sb->raid_disks) {
-				printk(KERN_ERR "raid5: disabled device %s (inconsistent descriptor)\n", kdevname(realdev->dev));
+			if (raid_disk > sb->raid_disks) {
+				printk(KERN_ERR "raid5: disabled device %s (inconsistent descriptor)\n", partition_name(rdev->dev));
 				continue;
 			}
-			if (raid_conf->disks[raid_disk].operational) {
-				printk(KERN_ERR "raid5: disabled device %s (device %d already operational)\n", kdevname(realdev->dev), raid_disk);
+			if (disk->operational) {
+				printk(KERN_ERR "raid5: disabled device %s (device %d already operational)\n", partition_name(rdev->dev), raid_disk);
 				continue;
 			}
-			printk(KERN_INFO "raid5: device %s operational as raid disk %d\n", kdevname(realdev->dev), raid_disk);
+			printk(KERN_INFO "raid5: device %s operational as raid disk %d\n", partition_name(rdev->dev), raid_disk);
 	
-			raid_conf->disks[raid_disk].number = descriptor->number;
-			raid_conf->disks[raid_disk].raid_disk = raid_disk;
-			raid_conf->disks[raid_disk].dev = mddev->devices[i].dev;
-			raid_conf->disks[raid_disk].operational = 1;
-
-			raid_conf->working_disks++;
-		}
-	}
-	raid_conf->raid_disks = sb->raid_disks;
-	raid_conf->failed_disks = raid_conf->raid_disks - raid_conf->working_disks;
-	raid_conf->mddev = mddev;
-	raid_conf->chunk_size = sb->chunk_size;
-	raid_conf->level = sb->level;
-	raid_conf->algorithm = sb->parity_algorithm;
+			disk->number = desc->number;
+			disk->raid_disk = raid_disk;
+			disk->dev = rdev->dev;
+			disk->operational = 1;
+			disk->used_slot = 1;
 
-	if (!raid_conf->chunk_size || raid_conf->chunk_size % 4) {
-		printk(KERN_ERR "raid5: invalid chunk size %d for %s\n", raid_conf->chunk_size, kdevname(MKDEV(MD_MAJOR, minor)));
+			conf->working_disks++;
+		} else {
+			/*
+			 * Must be a spare disk ..
+			 */
+			printk(KERN_INFO "raid5: spare disk %s\n", partition_name(rdev->dev));
+			disk->number = desc->number;
+			disk->raid_disk = raid_disk;
+			disk->dev = rdev->dev;
+
+			disk->operational = 0;
+			disk->write_only = 0;
+			disk->spare = 1;
+			disk->used_slot = 1;
+		}
+	}
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		desc = sb->disks + i;
+		raid_disk = desc->raid_disk;
+		disk = conf->disks + raid_disk;
+
+		if (disk_faulty(desc) && (raid_disk < sb->raid_disks) &&
+			!conf->disks[raid_disk].used_slot) {
+
+			disk->number = desc->number;
+			disk->raid_disk = raid_disk;
+			disk->dev = MKDEV(0,0);
+
+			disk->operational = 0;
+			disk->write_only = 0;
+			disk->spare = 0;
+			disk->used_slot = 1;
+		}
+	}
+
+	conf->raid_disks = sb->raid_disks;
+	/*
+	 * 0 for a fully functional array, 1 for a degraded array.
+	 */
+	conf->failed_disks = conf->raid_disks - conf->working_disks;
+	conf->mddev = mddev;
+	conf->chunk_size = sb->chunk_size;
+	conf->level = sb->level;
+	conf->algorithm = sb->layout;
+	conf->max_nr_stripes = NR_STRIPES;
+
+#if 0
+	for (i = 0; i < conf->raid_disks; i++) {
+		if (!conf->disks[i].used_slot) {
+			MD_BUG();
+			goto abort;
+		}
+	}
+#endif
+	if (!conf->chunk_size || conf->chunk_size % 4) {
+		printk(KERN_ERR "raid5: invalid chunk size %d for md%d\n", conf->chunk_size, mdidx(mddev));
 		goto abort;
 	}
-	if (raid_conf->algorithm > ALGORITHM_RIGHT_SYMMETRIC) {
-		printk(KERN_ERR "raid5: unsupported parity algorithm %d for %s\n", raid_conf->algorithm, kdevname(MKDEV(MD_MAJOR, minor)));
+	if (conf->algorithm > ALGORITHM_RIGHT_SYMMETRIC) {
+		printk(KERN_ERR "raid5: unsupported parity algorithm %d for md%d\n", conf->algorithm, mdidx(mddev));
 		goto abort;
 	}
-	if (raid_conf->failed_disks > 1) {
-		printk(KERN_ERR "raid5: not enough operational devices for %s (%d/%d failed)\n", kdevname(MKDEV(MD_MAJOR, minor)), raid_conf->failed_disks, raid_conf->raid_disks);
+	if (conf->failed_disks > 1) {
+		printk(KERN_ERR "raid5: not enough operational devices for md%d (%d/%d failed)\n", mdidx(mddev), conf->failed_disks, conf->raid_disks);
 		goto abort;
 	}
 
-#if 0
-	if (check_consistenty(mddev)) {
-		printk(KERN_ERR "raid5: detected raid-5 xor inconsistenty -- run ckraid\n");
-		sb->state |= 1 << MD_SB_ERRORS;
-		goto abort;
+	if (conf->working_disks != sb->raid_disks) {
+		printk(KERN_ALERT "raid5: md%d, not all disks are operational -- trying to recover array\n", mdidx(mddev));
+		start_recovery = 1;
 	}
-#endif
 
-	if ((raid_conf->thread = md_register_thread(raid5d, raid_conf)) == NULL) {
-		printk(KERN_ERR "raid5: couldn't allocate thread for %s\n", kdevname(MKDEV(MD_MAJOR, minor)));
-		goto abort;
+	if (!start_recovery && (sb->state & (1 << MD_SB_CLEAN)) &&
+			check_consistency(mddev)) {
+		printk(KERN_ERR "raid5: detected raid-5 superblock xor inconsistency -- running resync\n");
+		sb->state &= ~(1 << MD_SB_CLEAN);
 	}
 
+	{
+		const char * name = "raid5d";
+
+		conf->thread = md_register_thread(raid5d, conf, name);
+		if (!conf->thread) {
+			printk(KERN_ERR "raid5: couldn't allocate thread for md%d\n", mdidx(mddev));
+			goto abort;
+		}
+	}
+
+	{
+		const char * name = "raid5syncd";
+
+		conf->resync_thread = md_register_thread(raid5syncd, conf,name);
+		if (!conf->resync_thread) {
+			printk(KERN_ERR "raid5: couldn't allocate thread for md%d\n", mdidx(mddev));
+			goto abort;
+		}
+	}
+
+	memory = conf->max_nr_stripes * (sizeof(struct stripe_head) +
+		 conf->raid_disks * (sizeof(struct buffer_head) +
+		 2 * (sizeof(struct buffer_head) + PAGE_SIZE))) / 1024;
+	if (grow_stripes(conf, conf->max_nr_stripes, GFP_KERNEL)) {
+		printk(KERN_ERR "raid5: couldn't allocate %dkB for buffers\n", memory);
+		shrink_stripes(conf, conf->max_nr_stripes);
+		goto abort;
+	} else
+		printk(KERN_INFO "raid5: allocated %dkB for md%d\n", memory, mdidx(mddev));
+
 	/*
 	 * Regenerate the "device is in sync with the raid set" bit for
 	 * each device.
 	 */
-	for (i = 0; i < sb->nr_disks ; i++) {
-		sb->disks[i].state &= ~(1 << MD_SYNC_DEVICE);
+	for (i = 0; i < MD_SB_DISKS ; i++) {
+		mark_disk_nonsync(sb->disks + i);
 		for (j = 0; j < sb->raid_disks; j++) {
-			if (!raid_conf->disks[j].operational)
+			if (!conf->disks[j].operational)
 				continue;
-			if (sb->disks[i].number == raid_conf->disks[j].number)
-				sb->disks[i].state |= 1 << MD_SYNC_DEVICE;
+			if (sb->disks[i].number == conf->disks[j].number)
+				mark_disk_sync(sb->disks + i);
 		}
 	}
-	sb->active_disks = raid_conf->working_disks;
+	sb->active_disks = conf->working_disks;
 
 	if (sb->active_disks == sb->raid_disks)
-		printk("raid5: raid level %d set %s active with %d out of %d devices, algorithm %d\n", raid_conf->level, kdevname(MKDEV(MD_MAJOR, minor)), sb->active_disks, sb->raid_disks, raid_conf->algorithm);
+		printk("raid5: raid level %d set md%d active with %d out of %d devices, algorithm %d\n", conf->level, mdidx(mddev), sb->active_disks, sb->raid_disks, conf->algorithm);
 	else
-		printk(KERN_ALERT "raid5: raid level %d set %s active with %d out of %d devices, algorithm %d\n", raid_conf->level, kdevname(MKDEV(MD_MAJOR, minor)), sb->active_disks, sb->raid_disks, raid_conf->algorithm);
+		printk(KERN_ALERT "raid5: raid level %d set md%d active with %d out of %d devices, algorithm %d\n", conf->level, mdidx(mddev), sb->active_disks, sb->raid_disks, conf->algorithm);
+
+	if (!start_recovery && (sb->state & (1 << MD_SB_CLEAN)) == 0) {
+		printk("raid5: raid set md%d not clean; reconstructing parity\n", mdidx(mddev));
+		conf->resync_parity = 1;
+		mddev->curr_resync = 1;
+		md_wakeup_thread(conf->resync_thread);
+	}
+
+	print_raid5_conf(conf);
+	if (start_recovery)
+		md_recover_arrays();
+	print_raid5_conf(conf);
 
 	/* Ok, everything is just fine now */
 	return (0);
 abort:
-	if (raid_conf)
-		kfree(raid_conf);
+	if (conf) {
+		print_raid5_conf(conf);
+		if (conf->stripe_hashtbl)
+			free_pages((unsigned long) conf->stripe_hashtbl,
+							HASH_PAGES_ORDER);
+		kfree(conf);
+	}
 	mddev->private = NULL;
-	printk(KERN_ALERT "raid5: failed to run raid set %s\n", kdevname(MKDEV(MD_MAJOR, minor)));
+	printk(KERN_ALERT "raid5: failed to run raid set md%d\n", mdidx(mddev));
 	MOD_DEC_USE_COUNT;
 	return -EIO;
 }
 
-static int raid5_stop (int minor, struct md_dev *mddev)
+static int raid5_stop_resync (mddev_t *mddev)
+{
+	raid5_conf_t *conf = mddev_to_conf(mddev);
+	mdk_thread_t *thread = conf->resync_thread;
+
+	if (thread) {
+		if (conf->resync_parity) {
+			conf->resync_parity = 2;
+			md_interrupt_thread(thread);
+			printk(KERN_INFO "raid5: parity resync was not fully finished, restarting next time.\n");
+			return 1;
+		}
+		return 0;
+	}
+	return 0;
+}
+
+static int raid5_restart_resync (mddev_t *mddev)
 {
-	struct raid5_data *raid_conf = (struct raid5_data *) mddev->private;
+	raid5_conf_t *conf = mddev_to_conf(mddev);
+
+	if (conf->resync_parity) {
+		if (!conf->resync_thread) {
+			MD_BUG();
+			return 0;
+		}
+		printk("raid5: waking up raid5resync.\n");
+		conf->resync_parity = 1;
+		md_wakeup_thread(conf->resync_thread);
+		return 1;
+	} else
+		printk("raid5: no restart-resync needed.\n");
+	return 0;
+}
+
 
-	md_unregister_thread(raid_conf->thread);
-	kfree (raid_conf);
-	shrink_stripe_cache(RAID5_STRIPE_POOL_SIZE);
-	shrink_buffers(RAID5_POOL_SIZE);
+static int raid5_stop (mddev_t *mddev)
+{
+	raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
+
+	shrink_stripe_cache(conf, conf->max_nr_stripes);
+	shrink_stripes(conf, conf->max_nr_stripes);
+	md_unregister_thread(conf->thread);
+	if (conf->resync_thread)
+		md_unregister_thread(conf->resync_thread);
+	free_pages((unsigned long) conf->stripe_hashtbl, HASH_PAGES_ORDER);
+	kfree(conf);
+	mddev->private = NULL;
 	MOD_DEC_USE_COUNT;
 	return 0;
 }
 
-static int raid5_status (char *page, int minor, struct md_dev *mddev)
+static int raid5_status (char *page, mddev_t *mddev)
 {
-	struct raid5_data *raid_conf = (struct raid5_data *) mddev->private;
-	md_superblock_t *sb = mddev->sb;
+	raid5_conf_t *conf = (raid5_conf_t *) mddev->private;
+	mdp_super_t *sb = mddev->sb;
 	int sz = 0, i;
 
-	sz += sprintf (page+sz, " level %d, %dk chunk, algorithm %d", sb->level, sb->chunk_size >> 10, sb->parity_algorithm);
-	sz += sprintf (page+sz, " [%d/%d] [", raid_conf->raid_disks, raid_conf->working_disks);
-	for (i = 0; i < raid_conf->raid_disks; i++)
-		sz += sprintf (page+sz, "%s", raid_conf->disks[i].operational ? "U" : "_");
+	sz += sprintf (page+sz, " level %d, %dk chunk, algorithm %d", sb->level, sb->chunk_size >> 10, sb->layout);
+	sz += sprintf (page+sz, " [%d/%d] [", conf->raid_disks, conf->working_disks);
+	for (i = 0; i < conf->raid_disks; i++)
+		sz += sprintf (page+sz, "%s", conf->disks[i].operational ? "U" : "_");
 	sz += sprintf (page+sz, "]");
 	return sz;
 }
 
-static struct md_personality raid5_personality=
+static void print_raid5_conf (raid5_conf_t *conf)
+{
+	int i;
+	struct disk_info *tmp;
+
+	printk("RAID5 conf printout:\n");
+	if (!conf) {
+		printk("(conf==NULL)\n");
+		return;
+	}
+	printk(" --- rd:%d wd:%d fd:%d\n", conf->raid_disks,
+		 conf->working_disks, conf->failed_disks);
+
+	for (i = 0; i < MD_SB_DISKS; i++) {
+		tmp = conf->disks + i;
+		printk(" disk %d, s:%d, o:%d, n:%d rd:%d us:%d dev:%s\n",
+			i, tmp->spare,tmp->operational,
+			tmp->number,tmp->raid_disk,tmp->used_slot,
+			partition_name(tmp->dev));
+	}
+}
+
+static int raid5_diskop(mddev_t *mddev, mdp_disk_t **d, int state)
+{
+	int err = 0;
+	int i, failed_disk=-1, spare_disk=-1, removed_disk=-1, added_disk=-1;
+	raid5_conf_t *conf = mddev->private;
+	struct disk_info *tmp, *sdisk, *fdisk, *rdisk, *adisk;
+	unsigned long flags;
+	mdp_super_t *sb = mddev->sb;
+	mdp_disk_t *failed_desc, *spare_desc, *added_desc;
+
+	save_flags(flags);
+	cli();
+
+	print_raid5_conf(conf);
+	/*
+	 * find the disk ...
+	 */
+	switch (state) {
+
+	case DISKOP_SPARE_ACTIVE:
+
+		/*
+		 * Find the failed disk within the RAID5 configuration ...
+		 * (this can only be in the first conf->raid_disks part)
+		 */
+		for (i = 0; i < conf->raid_disks; i++) {
+			tmp = conf->disks + i;
+			if ((!tmp->operational && !tmp->spare) ||
+					!tmp->used_slot) {
+				failed_disk = i;
+				break;
+			}
+		}
+		/*
+		 * When we activate a spare disk we _must_ have a disk in
+		 * the lower (active) part of the array to replace. 
+		 */
+		if ((failed_disk == -1) || (failed_disk >= conf->raid_disks)) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		/* fall through */
+
+	case DISKOP_SPARE_WRITE:
+	case DISKOP_SPARE_INACTIVE:
+
+		/*
+		 * Find the spare disk ... (can only be in the 'high'
+		 * area of the array)
+		 */
+		for (i = conf->raid_disks; i < MD_SB_DISKS; i++) {
+			tmp = conf->disks + i;
+			if (tmp->spare && tmp->number == (*d)->number) {
+				spare_disk = i;
+				break;
+			}
+		}
+		if (spare_disk == -1) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		break;
+
+	case DISKOP_HOT_REMOVE_DISK:
+
+		for (i = 0; i < MD_SB_DISKS; i++) {
+			tmp = conf->disks + i;
+			if (tmp->used_slot && (tmp->number == (*d)->number)) {
+				if (tmp->operational) {
+					err = -EBUSY;
+					goto abort;
+				}
+				removed_disk = i;
+				break;
+			}
+		}
+		if (removed_disk == -1) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		break;
+
+	case DISKOP_HOT_ADD_DISK:
+
+		for (i = conf->raid_disks; i < MD_SB_DISKS; i++) {
+			tmp = conf->disks + i;
+			if (!tmp->used_slot) {
+				added_disk = i;
+				break;
+			}
+		}
+		if (added_disk == -1) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		break;
+	}
+
+	switch (state) {
+	/*
+	 * Switch the spare disk to write-only mode:
+	 */
+	case DISKOP_SPARE_WRITE:
+		if (conf->spare) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		sdisk = conf->disks + spare_disk;
+		sdisk->operational = 1;
+		sdisk->write_only = 1;
+		conf->spare = sdisk;
+		break;
+	/*
+	 * Deactivate a spare disk:
+	 */
+	case DISKOP_SPARE_INACTIVE:
+		sdisk = conf->disks + spare_disk;
+		sdisk->operational = 0;
+		sdisk->write_only = 0;
+		/*
+		 * Was the spare being resynced?
+		 */
+		if (conf->spare == sdisk)
+			conf->spare = NULL;
+		break;
+	/*
+	 * Activate (mark read-write) the (now sync) spare disk,
+	 * which means we switch it's 'raid position' (->raid_disk)
+	 * with the failed disk. (only the first 'conf->raid_disks'
+	 * slots are used for 'real' disks and we must preserve this
+	 * property)
+	 */
+	case DISKOP_SPARE_ACTIVE:
+		if (!conf->spare) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+		sdisk = conf->disks + spare_disk;
+		fdisk = conf->disks + failed_disk;
+
+		spare_desc = &sb->disks[sdisk->number];
+		failed_desc = &sb->disks[fdisk->number];
+
+		if (spare_desc != *d) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		if (spare_desc->raid_disk != sdisk->raid_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+			
+		if (sdisk->raid_disk != spare_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		if (failed_desc->raid_disk != fdisk->raid_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		if (fdisk->raid_disk != failed_disk) {
+			MD_BUG();
+			err = 1;
+			goto abort;
+		}
+
+		/*
+		 * do the switch finally
+		 */
+		xchg_values(*spare_desc, *failed_desc);
+		xchg_values(*fdisk, *sdisk);
+
+		/*
+		 * (careful, 'failed' and 'spare' are switched from now on)
+		 *
+		 * we want to preserve linear numbering and we want to
+		 * give the proper raid_disk number to the now activated
+		 * disk. (this means we switch back these values)
+		 */
+	
+		xchg_values(spare_desc->raid_disk, failed_desc->raid_disk);
+		xchg_values(sdisk->raid_disk, fdisk->raid_disk);
+		xchg_values(spare_desc->number, failed_desc->number);
+		xchg_values(sdisk->number, fdisk->number);
+
+		*d = failed_desc;
+
+		if (sdisk->dev == MKDEV(0,0))
+			sdisk->used_slot = 0;
+
+		/*
+		 * this really activates the spare.
+		 */
+		fdisk->spare = 0;
+		fdisk->write_only = 0;
+
+		/*
+		 * if we activate a spare, we definitely replace a
+		 * non-operational disk slot in the 'low' area of
+		 * the disk array.
+		 */
+		conf->failed_disks--;
+		conf->working_disks++;
+		conf->spare = NULL;
+
+		break;
+
+	case DISKOP_HOT_REMOVE_DISK:
+		rdisk = conf->disks + removed_disk;
+
+		if (rdisk->spare && (removed_disk < conf->raid_disks)) {
+			MD_BUG();	
+			err = 1;
+			goto abort;
+		}
+		rdisk->dev = MKDEV(0,0);
+		rdisk->used_slot = 0;
+
+		break;
+
+	case DISKOP_HOT_ADD_DISK:
+		adisk = conf->disks + added_disk;
+		added_desc = *d;
+
+		if (added_disk != added_desc->number) {
+			MD_BUG();	
+			err = 1;
+			goto abort;
+		}
+
+		adisk->number = added_desc->number;
+		adisk->raid_disk = added_desc->raid_disk;
+		adisk->dev = MKDEV(added_desc->major,added_desc->minor);
+
+		adisk->operational = 0;
+		adisk->write_only = 0;
+		adisk->spare = 1;
+		adisk->used_slot = 1;
+
+
+		break;
+
+	default:
+		MD_BUG();	
+		err = 1;
+		goto abort;
+	}
+abort:
+	restore_flags(flags);
+	print_raid5_conf(conf);
+	return err;
+}
+
+static mdk_personality_t raid5_personality=
 {
 	"raid5",
 	raid5_map,
@@ -1477,15 +1985,20 @@
 	raid5_status,
 	NULL,			/* no ioctls */
 	0,
-	raid5_error
+	raid5_error,
+	raid5_diskop,
+	raid5_stop_resync,
+	raid5_restart_resync
 };
 
 int raid5_init (void)
 {
-	if ((stripe_hashtbl = (struct stripe_head **) __get_free_pages(GFP_ATOMIC, HASH_PAGES_ORDER, 0)) == NULL)
-		return -ENOMEM;
-	memset(stripe_hashtbl, 0, HASH_PAGES * PAGE_SIZE);
-	return register_md_personality (RAID5, &raid5_personality);
+	int err;
+
+	err = register_md_personality (RAID5, &raid5_personality);
+	if (err)
+		return err;
+	return 0;
 }
 
 #ifdef MODULE
@@ -1496,9 +2009,6 @@
 
 void cleanup_module (void)
 {
-	free_pages((unsigned long) stripe_hashtbl, HASH_PAGES_ORDER);
-	shrink_stripe_cache(RAID5_STRIPE_POOL_SIZE);
-	shrink_buffers(RAID5_POOL_SIZE);
 	unregister_md_personality (RAID5);
 }
 #endif
--- linux/drivers/block/raid0.c.orig	Mon Aug  3 20:40:05 1998
+++ linux/drivers/block/raid0.c	Fri Feb  2 01:14:53 1996
@@ -1,4 +1,3 @@
-
 /*
    raid0.c : Multiple Devices driver for Linux
              Copyright (C) 1994-96 Marc ZYNGIER
@@ -18,139 +17,204 @@
 */
 
 #include <linux/module.h>
-#include <linux/md.h>
-#include <linux/raid0.h>
-#include <linux/malloc.h>
+#include <linux/raid/raid0.h>
 
 #define MAJOR_NR MD_MAJOR
 #define MD_DRIVER
 #define MD_PERSONALITY
 
-static int create_strip_zones (int minor, struct md_dev *mddev)
+static int create_strip_zones (mddev_t *mddev)
 {
-  int i, j, c=0;
-  int current_offset=0;
-  struct real_dev *smallest_by_zone;
-  struct raid0_data *data=(struct raid0_data *) mddev->private;
-  
-  data->nr_strip_zones=1;
-  
-  for (i=1; i<mddev->nb_dev; i++)
-  {
-    for (j=0; j<i; j++)
-      if (mddev->devices[i].size==mddev->devices[j].size)
-      {
-	c=1;
-	break;
-      }
-
-    if (!c)
-      data->nr_strip_zones++;
-
-    c=0;
-  }
-
-  if ((data->strip_zone=vmalloc(sizeof(struct strip_zone)*data->nr_strip_zones)) == NULL)
-    return 1;
-
-  data->smallest=NULL;
-  
-  for (i=0; i<data->nr_strip_zones; i++)
-  {
-    data->strip_zone[i].dev_offset=current_offset;
-    smallest_by_zone=NULL;
-    c=0;
-
-    for (j=0; j<mddev->nb_dev; j++)
-      if (mddev->devices[j].size>current_offset)
-      {
-	data->strip_zone[i].dev[c++]=mddev->devices+j;
-	if (!smallest_by_zone ||
-	    smallest_by_zone->size > mddev->devices[j].size)
-	  smallest_by_zone=mddev->devices+j;
-      }
-
-    data->strip_zone[i].nb_dev=c;
-    data->strip_zone[i].size=(smallest_by_zone->size-current_offset)*c;
-
-    if (!data->smallest ||
-	data->smallest->size > data->strip_zone[i].size)
-      data->smallest=data->strip_zone+i;
-
-    data->strip_zone[i].zone_offset=i ? (data->strip_zone[i-1].zone_offset+
-					   data->strip_zone[i-1].size) : 0;
-    current_offset=smallest_by_zone->size;
-  }
-  return 0;
+	int i, c, j, j1, j2;
+	int current_offset, curr_zone_offset;
+	raid0_conf_t *conf = mddev_to_conf(mddev);
+	mdk_rdev_t *smallest, *rdev1, *rdev2, *rdev;
+ 
+	/*
+	 * The number of 'same size groups'
+	 */
+	conf->nr_strip_zones = 0;
+ 
+	ITERATE_RDEV_ORDERED(mddev,rdev1,j1) {
+		printk("raid0: looking at %s\n", partition_name(rdev1->dev));
+		c = 0;
+		ITERATE_RDEV_ORDERED(mddev,rdev2,j2) {
+			printk("raid0:   comparing %s(%d) with %s(%d)\n", partition_name(rdev1->dev), rdev1->size, partition_name(rdev2->dev), rdev2->size);
+			if (rdev2 == rdev1) {
+				printk("raid0:   END\n");
+				break;
+			}
+			if (rdev2->size == rdev1->size)
+			{
+				/*
+				 * Not unique, dont count it as a new
+				 * group
+				 */
+				printk("raid0:   EQUAL\n");
+				c = 1;
+				break;
+			}
+			printk("raid0:   NOT EQUAL\n");
+		}
+		if (!c) {
+			printk("raid0:   ==> UNIQUE\n");
+			conf->nr_strip_zones++;
+			printk("raid0: %d zones\n", conf->nr_strip_zones);
+		}
+	}
+		printk("raid0: FINAL %d zones\n", conf->nr_strip_zones);
+
+	conf->strip_zone = vmalloc(sizeof(struct strip_zone)*
+				conf->nr_strip_zones);
+	if (!conf->strip_zone)
+		return 1;
+
+
+	conf->smallest = NULL;
+	current_offset = 0;
+	curr_zone_offset = 0;
+
+	for (i = 0; i < conf->nr_strip_zones; i++)
+	{
+		struct strip_zone *zone = conf->strip_zone + i;
+
+		printk("zone %d\n", i);
+		zone->dev_offset = current_offset;
+		smallest = NULL;
+		c = 0;
+
+		ITERATE_RDEV_ORDERED(mddev,rdev,j) {
+
+			printk(" checking %s ...", partition_name(rdev->dev));
+			if (rdev->size > current_offset)
+			{
+				printk(" contained as device %d\n", c);
+				zone->dev[c] = rdev;
+				c++;
+				if (!smallest || (rdev->size <smallest->size)) {
+					smallest = rdev;
+					printk("  (%d) is smallest!.\n", rdev->size);
+				}
+			} else
+				printk(" nope.\n");
+		}
+
+		zone->nb_dev = c;
+		zone->size = (smallest->size - current_offset) * c;
+		printk(" zone->nb_dev: %d, size: %d\n",zone->nb_dev,zone->size);
+
+		if (!conf->smallest || (zone->size < conf->smallest->size))
+			conf->smallest = zone;
+
+		zone->zone_offset = curr_zone_offset;
+		curr_zone_offset += zone->size;
+
+		current_offset = smallest->size;
+		printk("current zone offset: %d\n", current_offset);
+	}
+	printk("done.\n");
+	return 0;
 }
 
-static int raid0_run (int minor, struct md_dev *mddev)
+static int raid0_run (mddev_t *mddev)
 {
-  int cur=0, i=0, size, zone0_size, nb_zone;
-  struct raid0_data *data;
+	int cur=0, i=0, size, zone0_size, nb_zone;
+	raid0_conf_t *conf;
 
-  MOD_INC_USE_COUNT;
+	MOD_INC_USE_COUNT;
 
-  if ((mddev->private=vmalloc (sizeof (struct raid0_data))) == NULL) return 1;
-  data=(struct raid0_data *) mddev->private;
-  
-  if (create_strip_zones (minor, mddev)) return 1;
-
-  nb_zone=data->nr_zones=
-    md_size[minor]/data->smallest->size +
-    (md_size[minor]%data->smallest->size ? 1 : 0);
-
-  printk ("raid0 : Allocating %d bytes for hash.\n",sizeof(struct raid0_hash)*nb_zone);
-  if ((data->hash_table=vmalloc (sizeof (struct raid0_hash)*nb_zone)) == NULL)
-    return 1;
-
-  size=data->strip_zone[cur].size;
-
-  i=0;
-  while (cur<data->nr_strip_zones)
-  {
-    data->hash_table[i].zone0=data->strip_zone+cur;
-
-    if (size>=data->smallest->size)/* If we completely fill the slot */
-    {
-      data->hash_table[i++].zone1=NULL;
-      size-=data->smallest->size;
-
-      if (!size)
-      {
-	if (++cur==data->nr_strip_zones) continue;
-	size=data->strip_zone[cur].size;
-      }
-
-      continue;
-    }
-
-    if (++cur==data->nr_strip_zones) /* Last dev, set unit1 as NULL */
-    {
-      data->hash_table[i].zone1=NULL;
-      continue;
-    }
-
-    zone0_size=size;		/* Here, we use a 2nd dev to fill the slot */
-    size=data->strip_zone[cur].size;
-    data->hash_table[i++].zone1=data->strip_zone+cur;
-    size-=(data->smallest->size - zone0_size);
-  }
-
-  return (0);
+	conf = vmalloc(sizeof (raid0_conf_t));
+	if (!conf)
+		goto out;
+	mddev->private = (void *)conf;
+ 
+	if (md_check_ordering(mddev)) {
+		printk("raid0: disks are not ordered, aborting!\n");
+		goto out_free_conf;
+	}
+
+	if (create_strip_zones (mddev)) 
+		goto out_free_conf;
+
+	printk("raid0 : md_size is %d blocks.\n", md_size[mdidx(mddev)]);
+	printk("raid0 : conf->smallest->size is %d blocks.\n", conf->smallest->size);
+	nb_zone = md_size[mdidx(mddev)]/conf->smallest->size +
+			(md_size[mdidx(mddev)] % conf->smallest->size ? 1 : 0);
+	printk("raid0 : nb_zone is %d.\n", nb_zone);
+	conf->nr_zones = nb_zone;
+
+	printk("raid0 : Allocating %d bytes for hash.\n",
+				sizeof(struct raid0_hash)*nb_zone);
+
+	conf->hash_table = vmalloc (sizeof (struct raid0_hash)*nb_zone);
+	if (!conf->hash_table)
+		goto out_free_zone_conf;
+	size = conf->strip_zone[cur].size;
+
+	i = 0;
+	while (cur < conf->nr_strip_zones)
+	{
+		conf->hash_table[i].zone0 = conf->strip_zone + cur;
+
+		/*
+		 * If we completely fill the slot
+		 */
+		if (size >= conf->smallest->size)
+		{
+			conf->hash_table[i++].zone1 = NULL;
+			size -= conf->smallest->size;
+
+			if (!size)
+			{
+				if (++cur == conf->nr_strip_zones)
+					continue;
+				size = conf->strip_zone[cur].size;
+			}
+			continue;
+		}
+		if (++cur == conf->nr_strip_zones)
+		{
+			/*
+			 * Last dev, set unit1 as NULL
+			 */
+			conf->hash_table[i].zone1=NULL;
+			continue;
+		}
+
+		/*
+		 * Here we use a 2nd dev to fill the slot
+		 */
+		zone0_size = size;
+		size = conf->strip_zone[cur].size;
+		conf->hash_table[i++].zone1 = conf->strip_zone + cur;
+		size -= (conf->smallest->size - zone0_size);
+	}
+	return 0;
+
+out_free_zone_conf:
+	vfree(conf->strip_zone);
+	conf->strip_zone = NULL;
+
+out_free_conf:
+	vfree(conf);
+	mddev->private = NULL;
+out:
+	return 1;
 }
 
-
-static int raid0_stop (int minor, struct md_dev *mddev)
+static int raid0_stop (mddev_t *mddev)
 {
-  struct raid0_data *data=(struct raid0_data *) mddev->private;
+	raid0_conf_t *conf = mddev_to_conf(mddev);
 
-  vfree (data->hash_table);
-  vfree (data->strip_zone);
-  vfree (data);
+	vfree (conf->hash_table);
+	conf->hash_table = NULL;
+	vfree (conf->strip_zone);
+	conf->strip_zone = NULL;
+	vfree (conf);
+	mddev->private = NULL;
 
-  MOD_DEC_USE_COUNT;
-  return 0;
+	MOD_DEC_USE_COUNT;
+	return 0;
 }
 
 /*
@@ -160,126 +224,126 @@
  * Of course, those facts may not be valid anymore (and surely won't...)
  * Hey guys, there's some work out there ;-)
  */
-static int raid0_map (struct md_dev *mddev, kdev_t *rdev,
+static int raid0_map (mddev_t *mddev, kdev_t *rdev,
 		      unsigned long *rsector, unsigned long size)
 {
-  struct raid0_data *data=(struct raid0_data *) mddev->private;
-  static struct raid0_hash *hash;
-  struct strip_zone *zone;
-  struct real_dev *tmp_dev;
-  int blk_in_chunk, factor, chunk, chunk_size;
-  long block, rblock;
-
-  factor=FACTOR(mddev);
-  chunk_size=(1UL << FACTOR_SHIFT(factor));
-  block=*rsector >> 1;
-  hash=data->hash_table+(block/data->smallest->size);
-
-  /* Sanity check */
-  if ((chunk_size*2)<(*rsector % (chunk_size*2))+size)
-  {
-    printk ("raid0_convert : can't convert block across chunks or bigger than %dk %ld %ld\n", chunk_size, *rsector, size);
-    return (-1);
-  }
+	raid0_conf_t *conf = mddev_to_conf(mddev);
+	struct raid0_hash *hash;
+	struct strip_zone *zone;
+	mdk_rdev_t *tmp_dev;
+	int blk_in_chunk, chunksize_bits, chunk, chunk_size;
+	long block, rblock;
+
+	chunk_size = mddev->param.chunk_size >> 10;
+	chunksize_bits = ffs(chunk_size)-1;
+	block = *rsector >> 1;
+	hash = conf->hash_table + block / conf->smallest->size;
+
+	/* Sanity check */
+	if ((chunk_size * 2) < (*rsector % (chunk_size * 2)) + size)
+	{
+		printk ("raid0_convert : can't convert block across chunks or bigger than %dk %ld %ld\n", chunk_size, *rsector, size);
+		return -1;
+	}
   
-  if (block >= (hash->zone0->size +
-		hash->zone0->zone_offset))
-  {
-    if (!hash->zone1)
-    {
-      printk ("raid0_convert : hash->zone1==NULL for block %ld\n", block);
-      return (-1);
-    }
+	if (block >= (hash->zone0->size + hash->zone0->zone_offset))
+	{
+		if (!hash->zone1)
+		{
+			printk ("raid0_convert : hash->zone1==NULL for block %ld\n", block);
+			return -1;
+		}
     
-    zone=hash->zone1;
-  }
-  else
-    zone=hash->zone0;
+		zone = hash->zone1;
+	} else
+		zone = hash->zone0;
     
-  blk_in_chunk=block & (chunk_size -1);
-  chunk=(block - zone->zone_offset) / (zone->nb_dev<<FACTOR_SHIFT(factor));
-  tmp_dev=zone->dev[(block >> FACTOR_SHIFT(factor)) % zone->nb_dev];
-  rblock=(chunk << FACTOR_SHIFT(factor)) + blk_in_chunk + zone->dev_offset;
+	blk_in_chunk = block & (chunk_size -1);
+	chunk = (block - zone->zone_offset) / (zone->nb_dev << chunksize_bits);
+	tmp_dev = zone->dev[(block >> chunksize_bits) % zone->nb_dev];
+	rblock = (chunk << chunksize_bits) + blk_in_chunk + zone->dev_offset;
   
-  *rdev=tmp_dev->dev;
-  *rsector=rblock<<1;
+	*rdev = tmp_dev->dev;
+	*rsector = rblock << 1;
 
-  return (0);
+	return 0;
 }
 
 			   
-static int raid0_status (char *page, int minor, struct md_dev *mddev)
+static int raid0_status (char *page, mddev_t *mddev)
 {
-  int sz=0;
+	int sz = 0;
 #undef MD_DEBUG
 #ifdef MD_DEBUG
-  int j, k;
-  struct raid0_data *data=(struct raid0_data *) mddev->private;
+	int j, k;
+	raid0_conf_t *conf = mddev_to_conf(mddev);
   
-  sz+=sprintf (page+sz, "      ");
-  for (j=0; j<data->nr_zones; j++)
-  {
-    sz+=sprintf (page+sz, "[z%d",
-		 data->hash_table[j].zone0-data->strip_zone);
-    if (data->hash_table[j].zone1)
-      sz+=sprintf (page+sz, "/z%d] ",
-		   data->hash_table[j].zone1-data->strip_zone);
-    else
-      sz+=sprintf (page+sz, "] ");
-  }
+	sz += sprintf(page + sz, "      ");
+	for (j = 0; j < conf->nr_zones; j++)
+	{
+		sz += sprintf(page + sz, "[z%d",
+				conf->hash_table[j].zone0 - conf->strip_zone);
+		if (conf->hash_table[j].zone1)
+			sz += sprintf(page+sz, "/z%d] ",
+				conf->hash_table[j].zone1 - conf->strip_zone);
+		else
+			sz += sprintf(page+sz, "] ");
+	}
   
-  sz+=sprintf (page+sz, "\n");
+	sz += sprintf(page + sz, "\n");
   
-  for (j=0; j<data->nr_strip_zones; j++)
-  {
-    sz+=sprintf (page+sz, "      z%d=[", j);
-    for (k=0; k<data->strip_zone[j].nb_dev; k++)
-      sz+=sprintf (page+sz, "%s/",
-		   partition_name(data->strip_zone[j].dev[k]->dev));
-    sz--;
-    sz+=sprintf (page+sz, "] zo=%d do=%d s=%d\n",
-		 data->strip_zone[j].zone_offset,
-		 data->strip_zone[j].dev_offset,
-		 data->strip_zone[j].size);
-  }
+	for (j = 0; j < conf->nr_strip_zones; j++)
+	{
+		sz += sprintf(page + sz, "      z%d=[", j);
+		for (k = 0; k < conf->strip_zone[j].nb_dev; k++)
+			sz += sprintf (page+sz, "%s/", partition_name(
+				conf->strip_zone[j].dev[k]->dev));
+		sz--;
+		sz += sprintf (page+sz, "] zo=%d do=%d s=%d\n",
+				conf->strip_zone[j].zone_offset,
+				conf->strip_zone[j].dev_offset,
+				conf->strip_zone[j].size);
+	}
 #endif
-  sz+=sprintf (page+sz, " %dk chunks", 1<<FACTOR_SHIFT(FACTOR(mddev)));
-  return sz;
+	sz += sprintf(page + sz, " %dk chunks", mddev->param.chunk_size/1024);
+	return sz;
 }
 
-
-static struct md_personality raid0_personality=
+static mdk_personality_t raid0_personality=
 {
-  "raid0",
-  raid0_map,
-  NULL,				/* no special make_request */
-  NULL,				/* no special end_request */
-  raid0_run,
-  raid0_stop,
-  raid0_status,
-  NULL,				/* no ioctls */
-  0,
-  NULL,				/* no error_handler */
+	"raid0",
+	raid0_map,
+	NULL,				/* no special make_request */
+	NULL,				/* no special end_request */
+	raid0_run,
+	raid0_stop,
+	raid0_status,
+	NULL,				/* no ioctls */
+	0,
+	NULL,				/* no error_handler */
+	NULL,				/* no diskop */
+	NULL,				/* no stop resync */
+	NULL				/* no restart resync */
 };
 
-
 #ifndef MODULE
 
 void raid0_init (void)
 {
-  register_md_personality (RAID0, &raid0_personality);
+	register_md_personality (RAID0, &raid0_personality);
 }
 
 #else
 
 int init_module (void)
 {
-  return (register_md_personality (RAID0, &raid0_personality));
+	return (register_md_personality (RAID0, &raid0_personality));
 }
 
 void cleanup_module (void)
 {
-  unregister_md_personality (RAID0);
+	unregister_md_personality (RAID0);
 }
 
 #endif
+
--- linux/drivers/block/linear.c.orig	Mon Aug  3 20:40:04 1998
+++ linux/drivers/block/linear.c	Fri Feb  2 01:14:54 1996
@@ -1,4 +1,3 @@
-
 /*
    linear.c : Multiple Devices driver for Linux
               Copyright (C) 1994-96 Marc ZYNGIER
@@ -19,184 +18,206 @@
 
 #include <linux/module.h>
 
-#include <linux/md.h>
-#include <linux/linear.h>
+#include <linux/raid/md.h>
 #include <linux/malloc.h>
 
+#include <linux/raid/linear.h>
+
 #define MAJOR_NR MD_MAJOR
 #define MD_DRIVER
 #define MD_PERSONALITY
 
-static int linear_run (int minor, struct md_dev *mddev)
+static int linear_run (mddev_t *mddev)
 {
-  int cur=0, i, size, dev0_size, nb_zone;
-  struct linear_data *data;
+	linear_conf_t *conf;
+	struct linear_hash *table;
+	mdk_rdev_t *rdev;
+	int size, i, j, nb_zone;
+	unsigned int curr_offset;
 
-  MOD_INC_USE_COUNT;
+	MOD_INC_USE_COUNT;
 
-  mddev->private=kmalloc (sizeof (struct linear_data), GFP_KERNEL);
-  data=(struct linear_data *) mddev->private;
-
-  /*
-     Find out the smallest device. This was previously done
-     at registry time, but since it violates modularity,
-     I moved it here... Any comment ? ;-)
-   */
-
-  data->smallest=mddev->devices;
-  for (i=1; i<mddev->nb_dev; i++)
-    if (data->smallest->size > mddev->devices[i].size)
-      data->smallest=mddev->devices+i;
-  
-  nb_zone=data->nr_zones=
-    md_size[minor]/data->smallest->size +
-    (md_size[minor]%data->smallest->size ? 1 : 0);
-  
-  data->hash_table=kmalloc (sizeof (struct linear_hash)*nb_zone, GFP_KERNEL);
+	conf = kmalloc (sizeof (*conf), GFP_KERNEL);
+	if (!conf)
+		goto out;
+	mddev->private = conf;
+
+	if (md_check_ordering(mddev)) {
+		printk("linear: disks are not ordered, aborting!\n");
+		goto out;
+	}
+	/*
+	 * Find the smallest device.
+	 */
+
+	conf->smallest = NULL;
+	curr_offset = 0;
+	ITERATE_RDEV_ORDERED(mddev,rdev,j) {
+		dev_info_t *disk = conf->disks + j;
+
+		disk->dev = rdev->dev;
+		disk->size = rdev->size;
+		disk->offset = curr_offset;
 
-  size=mddev->devices[cur].size;
+		curr_offset += disk->size;
 
-  i=0;
-  while (cur<mddev->nb_dev)
-  {
-    data->hash_table[i].dev0=mddev->devices+cur;
+		if (!conf->smallest || (disk->size < conf->smallest->size))
+			conf->smallest = disk;
+	}
 
-    if (size>=data->smallest->size) /* If we completely fill the slot */
-    {
-      data->hash_table[i++].dev1=NULL;
-      size-=data->smallest->size;
+	nb_zone = conf->nr_zones =
+		md_size[mdidx(mddev)] / conf->smallest->size +
+		((md_size[mdidx(mddev)] % conf->smallest->size) ? 1 : 0);
+  
+	conf->hash_table = kmalloc (sizeof (struct linear_hash) * nb_zone,
+					GFP_KERNEL);
+	if (!conf->hash_table)
+		goto out_free_conf;
 
-      if (!size)
-      {
-	if (++cur==mddev->nb_dev) continue;
-	size=mddev->devices[cur].size;
-      }
+	/*
+	 * Here we generate the linear hash table
+	 */
+	table = conf->hash_table;
+	i = 0;
+	size = 0;
+	for (j = 0; j < mddev->nb_dev; j++) {
+		dev_info_t *disk = conf->disks + j;
 
-      continue;
-    }
+		if (size < 0) {
+			table->dev1 = disk;
+			table++;
+		}
+		size += disk->size;
 
-    if (++cur==mddev->nb_dev) /* Last dev, set dev1 as NULL */
-    {
-      data->hash_table[i].dev1=NULL;
-      continue;
-    }
+		while (size) {
+			table->dev0 = disk;
+			size -= conf->smallest->size;
+			if (size < 0)
+				break;
+			table->dev1 = NULL;
+			table++;
+		}
+	}
+	table->dev1 = NULL;
 
-    dev0_size=size;		/* Here, we use a 2nd dev to fill the slot */
-    size=mddev->devices[cur].size;
-    data->hash_table[i++].dev1=mddev->devices+cur;
-    size-=(data->smallest->size - dev0_size);
-  }
+	return 0;
 
-  return 0;
+out_free_conf:
+	kfree(conf);
+out:
+	return 1;
 }
 
-static int linear_stop (int minor, struct md_dev *mddev)
+static int linear_stop (mddev_t *mddev)
 {
-  struct linear_data *data=(struct linear_data *) mddev->private;
+	linear_conf_t *conf = mddev_to_conf(mddev);
   
-  kfree (data->hash_table);
-  kfree (data);
+	kfree(conf->hash_table);
+	kfree(conf);
 
-  MOD_DEC_USE_COUNT;
+	MOD_DEC_USE_COUNT;
 
-  return 0;
+	return 0;
 }
 
 
-static int linear_map (struct md_dev *mddev, kdev_t *rdev,
+static int linear_map (mddev_t *mddev, kdev_t *rdev,
 		       unsigned long *rsector, unsigned long size)
 {
-  struct linear_data *data=(struct linear_data *) mddev->private;
-  struct linear_hash *hash;
-  struct real_dev *tmp_dev;
-  long block;
-
-  block=*rsector >> 1;
-  hash=data->hash_table+(block/data->smallest->size);
-  
-  if (block >= (hash->dev0->size + hash->dev0->offset))
-  {
-    if (!hash->dev1)
-    {
-      printk ("linear_map : hash->dev1==NULL for block %ld\n", block);
-      return (-1);
-    }
-    
-    tmp_dev=hash->dev1;
-  }
-  else
-    tmp_dev=hash->dev0;
+	linear_conf_t *conf = mddev_to_conf(mddev);
+	struct linear_hash *hash;
+	dev_info_t *tmp_dev;
+	long block;
+
+	block = *rsector >> 1;
+	hash = conf->hash_table + (block / conf->smallest->size);
+  
+	if (block >= (hash->dev0->size + hash->dev0->offset))
+	{
+		if (!hash->dev1)
+		{
+			printk ("linear_map : hash->dev1==NULL for block %ld\n",
+						block);
+			return -1;
+		}
+		tmp_dev = hash->dev1;
+	} else
+		tmp_dev = hash->dev0;
     
-  if (block >= (tmp_dev->size + tmp_dev->offset) || block < tmp_dev->offset)
-    printk ("Block %ld out of bounds on dev %s size %d offset %d\n",
-	    block, kdevname(tmp_dev->dev), tmp_dev->size, tmp_dev->offset);
+	if (block >= (tmp_dev->size + tmp_dev->offset)
+				|| block < tmp_dev->offset)
+	printk ("Block %ld out of bounds on dev %s size %d offset %d\n",
+		block, kdevname(tmp_dev->dev), tmp_dev->size, tmp_dev->offset);
   
-  *rdev=tmp_dev->dev;
-  *rsector=(block-(tmp_dev->offset)) << 1;
+	*rdev = tmp_dev->dev;
+	*rsector = (block - tmp_dev->offset) << 1;
 
-  return (0);
+	return 0;
 }
 
-static int linear_status (char *page, int minor, struct md_dev *mddev)
+static int linear_status (char *page, mddev_t *mddev)
 {
-  int sz=0;
+	int sz=0;
 
 #undef MD_DEBUG
 #ifdef MD_DEBUG
-  int j;
-  struct linear_data *data=(struct linear_data *) mddev->private;
+	int j;
+	linear_conf_t *conf = mddev_to_conf(mddev);
   
-  sz+=sprintf (page+sz, "      ");
-  for (j=0; j<data->nr_zones; j++)
-  {
-    sz+=sprintf (page+sz, "[%s",
-		 partition_name (data->hash_table[j].dev0->dev));
-
-    if (data->hash_table[j].dev1)
-      sz+=sprintf (page+sz, "/%s] ",
-		   partition_name(data->hash_table[j].dev1->dev));
-    else
-      sz+=sprintf (page+sz, "] ");
-  }
-
-  sz+=sprintf (page+sz, "\n");
+	sz += sprintf(page+sz, "      ");
+	for (j = 0; j < conf->nr_zones; j++)
+	{
+		sz += sprintf(page+sz, "[%s",
+			partition_name(conf->hash_table[j].dev0->dev));
+
+		if (conf->hash_table[j].dev1)
+			sz += sprintf(page+sz, "/%s] ",
+			  partition_name(conf->hash_table[j].dev1->dev));
+		else
+			sz += sprintf(page+sz, "] ");
+	}
+	sz += sprintf(page+sz, "\n");
 #endif
-  sz+=sprintf (page+sz, " %dk rounding", 1<<FACTOR_SHIFT(FACTOR(mddev)));
-  return sz;
+	sz += sprintf(page+sz, " %dk rounding", mddev->param.chunk_size/1024);
+	return sz;
 }
 
 
-static struct md_personality linear_personality=
+static mdk_personality_t linear_personality=
 {
-  "linear",
-  linear_map,
-  NULL,
-  NULL,
-  linear_run,
-  linear_stop,
-  linear_status,
-  NULL,				/* no ioctls */
-  0
+	"linear",
+	linear_map,
+	NULL,
+	NULL,
+	linear_run,
+	linear_stop,
+	linear_status,
+	NULL,
+	0,
+	NULL,
+	NULL,
+	NULL,
+	NULL
 };
 
-
 #ifndef MODULE
 
-void linear_init (void)
+md__initfunc(void linear_init (void))
 {
-  register_md_personality (LINEAR, &linear_personality);
+	register_md_personality (LINEAR, &linear_personality);
 }
 
 #else
 
 int init_module (void)
 {
-  return (register_md_personality (LINEAR, &linear_personality));
+	return (register_md_personality (LINEAR, &linear_personality));
 }
 
 void cleanup_module (void)
 {
-  unregister_md_personality (LINEAR);
+	unregister_md_personality (LINEAR);
 }
 
 #endif
+
--- linux/drivers/block/xor.c.orig	Sat Sep  5 20:15:55 1998
+++ linux/drivers/block/xor.c	Fri Feb  2 01:14:53 1996
@@ -0,0 +1,490 @@
+/*
+ * xor.c : Multiple Devices driver for Linux
+ *
+ * Copyright (C) 1996, 1997, 1998 Ingo Molnar, Matti Aarnio, Jakub Jelinek
+ *
+ *
+ * optimized RAID-5 checksumming functions.
+ *
+ * This program is free software; you can redistribute it and/or modify
+ * it under the terms of the GNU General Public License as published by
+ * the Free Software Foundation; either version 2, or (at your option)
+ * any later version.
+ *
+ * You should have received a copy of the GNU General Public License
+ * (for example /usr/src/linux/COPYING); if not, write to the Free
+ * Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
+ */
+#include <linux/module.h>
+#include <linux/raid/md.h>
+#ifdef __sparc64__
+#include <asm/head.h>
+#include <asm/asi.h>
+#endif
+
+/*
+ * we use the 'XOR function template' to register multiple xor
+ * functions runtime. The kernel measures their speed upon bootup
+ * and decides which one to use. (compile-time registration is
+ * not enough as certain CPU features like MMX can only be detected
+ * runtime)
+ *
+ * this architecture makes it pretty easy to add new routines
+ * that are faster on certain CPUs, without killing other CPU's
+ * 'native' routine. Although the current routines are belived
+ * to be the physically fastest ones on all CPUs tested, but
+ * feel free to prove me wrong and add yet another routine =B-)
+ * --mingo
+ */
+
+#define SRCDEST (struct buffer_head *dest, struct buffer_head *source)
+
+typedef void (*xor_block_t) SRCDEST;
+xor_block_t xor_block = NULL;
+
+struct xor_block_template;
+
+struct xor_block_template {
+	char * name;
+	xor_block_t xor_block;
+	int speed;
+	struct xor_block_template * next;
+};
+
+struct xor_block_template * xor_functions = NULL;
+
+#define XORBLOCK_TEMPLATE(x) \
+static void xor_block_##x SRCDEST; \
+static struct xor_block_template t_xor_block_##x = \
+				 { #x, xor_block_##x, 0, NULL }; \
+static void xor_block_##x SRCDEST
+
+#ifdef __i386__
+/*
+ * high-speed RAID5 checksumming functions utilizing MMX instructions
+ * Copyright (C) 1998 Ingo Molnar
+ */
+
+XORBLOCK_TEMPLATE(pII_mmx)
+{
+	int len  = dest->b_size;
+	long *destp   = (long *) dest->b_data;
+	long *sourcep = (long *) source->b_data;
+	char fpu_save[108];
+        int lines = (len>>7) - 1;
+
+	if (!(current->flags & PF_USEDFPU))
+		__asm__ __volatile__ ( " clts;\n");
+
+	__asm__ __volatile__ ( " fsave %0; fwait\n"::"m"(fpu_save[0]) );
+
+        __asm__ __volatile__ (
+
+#define LD(x,y) \
+        "       movq   8*("#x")(%%esi), %%mm"#y"   ;\n"
+
+#define XO(x,y) \
+        "       pxor   8*("#x")(%%edi), %%mm"#y"   ;\n"
+
+#define ST(x,y) \
+        "       movq %%mm"#y",   8*("#x")(%%esi)   ;\n"
+
+#define BLOCK0(i) \
+	ST(i,0)						\
+					LD(i+4,4)	\
+					XO(i+4,4)	\
+		ST(i+1,1)				\
+	LD(i+5,5)					\
+	XO(i+5,5)					\
+			ST(i+2,2)			\
+		LD(i+6,6)				\
+		XO(i+6,6)				\
+				ST(i+3,3)		\
+			LD(i+7,7)			\
+			XO(i+7,7)
+
+#define BLOCK1(i) \
+	ST(i,4)						\
+					LD(i+4,0)	\
+					XO(i+4,0)	\
+		ST(i+1,5)				\
+	LD(i+5,1)					\
+	XO(i+5,1)					\
+			ST(i+2,6)			\
+		LD(i+6,2)				\
+		XO(i+6,2)				\
+				ST(i+3,7)		\
+			LD(i+7,3)			\
+			XO(i+7,3)
+
+	LD(0,0)
+	XO(0,0)
+		LD(1,1)
+		XO(1,1)
+			LD(2,2)
+			XO(2,2)
+				LD(3,3)
+				XO(3,3)
+
+	" .align 32,0x90		;\n"
+        " 1:                            ;\n"
+
+		BLOCK0(0)
+		BLOCK1(4)
+		BLOCK0(8)
+		BLOCK1(12)
+
+        "       addl $128, %%esi         ;\n"
+        "       addl $128, %%edi         ;\n"
+        "       decl %%ecx              ;\n"
+        "       jnz 1b                  ;\n"
+
+		BLOCK0(0)
+		BLOCK1(4)
+		BLOCK0(8)
+
+	ST(12,4)
+		ST(13,5)
+			ST(14,6)
+				ST(15,7)
+        :
+        : "D" (sourcep), "S" (destp), "c" (lines)
+        : "memory" );
+
+	__asm__ __volatile__ ( " frstor %0;\n"::"m"(fpu_save[0]) );
+
+	if (!(current->flags & PF_USEDFPU))
+		stts();
+}
+
+#undef LD
+#undef XO
+#undef ST
+
+XORBLOCK_TEMPLATE(p5_mmx)
+{
+	int len  = dest->b_size;
+	long *destp   = (long *) dest->b_data;
+	long *sourcep = (long *) source->b_data;
+	char fpu_save[108];
+        int lines = len / 64;
+
+	if (!(current->flags & PF_USEDFPU))
+		__asm__ __volatile__ ( " clts;\n");
+
+	__asm__ __volatile__ ( " fsave %0; fwait\n"::"m"(fpu_save[0]) );
+
+        __asm__ __volatile__ (
+
+        " .align 32,0x90                ;\n"
+        " 1:                            ;\n"
+        "       movq   (%%esi), %%mm0   ;\n"
+        "       movq  8(%%esi), %%mm1   ;\n"
+        "       pxor   (%%edi), %%mm0   ;\n"
+        "       movq 16(%%esi), %%mm2   ;\n"
+        "       movq %%mm0,   (%%esi)   ;\n"
+        "       pxor  8(%%edi), %%mm1   ;\n"
+        "       movq 24(%%esi), %%mm3   ;\n"
+        "       movq %%mm1,  8(%%esi)   ;\n"
+        "       pxor 16(%%edi), %%mm2   ;\n"
+        "       movq 32(%%esi), %%mm4   ;\n"
+        "       movq %%mm2, 16(%%esi)   ;\n"
+        "       pxor 24(%%edi), %%mm3   ;\n"
+        "       movq 40(%%esi), %%mm5   ;\n"
+        "       movq %%mm3, 24(%%esi)   ;\n"
+        "       pxor 32(%%edi), %%mm4   ;\n"
+        "       movq 48(%%esi), %%mm6   ;\n"
+        "       movq %%mm4, 32(%%esi)   ;\n"
+        "       pxor 40(%%edi), %%mm5   ;\n"
+        "       movq 56(%%esi), %%mm7   ;\n"
+        "       movq %%mm5, 40(%%esi)   ;\n"
+        "       pxor 48(%%edi), %%mm6   ;\n"
+        "       pxor 56(%%edi), %%mm7   ;\n"
+        "       movq %%mm6, 48(%%esi)   ;\n"
+        "       movq %%mm7, 56(%%esi)   ;\n"
+        
+        "       addl $64, %%esi         ;\n"
+        "       addl $64, %%edi         ;\n"
+        "       decl %%ecx              ;\n"
+        "       jnz 1b                  ;\n"
+
+        : 
+        : "D" (sourcep), "S" (destp), "c" (lines)
+        : "memory" );
+
+	__asm__ __volatile__ ( " frstor %0;\n"::"m"(fpu_save[0]) );
+
+	if (!(current->flags & PF_USEDFPU))
+		stts();
+}
+#endif
+
+#ifdef __sparc64__
+/*
+ * High speed xor_block operation for RAID4/5 utilizing the
+ * UltraSparc Visual Instruction Set.
+ *
+ * Copyright (C) 1997 Jakub Jelinek (jj@sunsite.mff.cuni.cz)
+ *
+ *
+ *	void __xor_block (char *dest, char *src, long len)
+ *	{
+ *		while (len--) *dest++ ^= *src++;
+ * 	}
+ *
+ *	#define MD_XORBLOCK_ALIGNMENT	64
+ *
+ *	Requirements:
+ *	!(((long)dest | (long)src) & (MD_XORBLOCK_ALIGNMENT - 1)) &&
+ *	!(len & 127) && len >= 256
+ */
+
+XORBLOCK_TEMPLATE(VIS)
+{
+	__asm__ __volatile__ ("
+	wr	%%g0, %3, %%fprs
+	wr	%%g0, %4, %%asi
+	membar	#LoadStore|#StoreLoad|#StoreStore
+	sub	%2, 128, %2
+	ldda	[%0] %4, %%f0
+	ldda	[%1] %4, %%f16
+1:	ldda	[%0 + 64] %%asi, %%f32
+	fxor	%%f0, %%f16, %%f16
+	fxor	%%f2, %%f18, %%f18
+	fxor	%%f4, %%f20, %%f20
+	fxor	%%f6, %%f22, %%f22
+	fxor	%%f8, %%f24, %%f24
+	fxor	%%f10, %%f26, %%f26
+	fxor	%%f12, %%f28, %%f28
+	fxor	%%f14, %%f30, %%f30
+	stda	%%f16, [%0] %4
+	ldda	[%1 + 64] %%asi, %%f48
+	ldda	[%0 + 128] %%asi, %%f0
+	fxor	%%f32, %%f48, %%f48
+	fxor	%%f34, %%f50, %%f50
+	add	%0, 128, %0
+	fxor	%%f36, %%f52, %%f52
+	add	%1, 128, %1
+	fxor	%%f38, %%f54, %%f54
+	subcc	%2, 128, %2
+	fxor	%%f40, %%f56, %%f56
+	fxor	%%f42, %%f58, %%f58
+	fxor	%%f44, %%f60, %%f60
+	fxor	%%f46, %%f62, %%f62
+	stda	%%f48, [%0 - 64] %%asi
+	bne,pt	%%xcc, 1b
+	 ldda	[%1] %4, %%f16
+	ldda	[%0 + 64] %%asi, %%f32
+	fxor	%%f0, %%f16, %%f16
+	fxor	%%f2, %%f18, %%f18
+	fxor	%%f4, %%f20, %%f20
+	fxor	%%f6, %%f22, %%f22
+	fxor	%%f8, %%f24, %%f24
+	fxor	%%f10, %%f26, %%f26
+	fxor	%%f12, %%f28, %%f28
+	fxor	%%f14, %%f30, %%f30
+	stda	%%f16, [%0] %4
+	ldda	[%1 + 64] %%asi, %%f48
+	membar	#Sync
+	fxor	%%f32, %%f48, %%f48
+	fxor	%%f34, %%f50, %%f50
+	fxor	%%f36, %%f52, %%f52
+	fxor	%%f38, %%f54, %%f54
+	fxor	%%f40, %%f56, %%f56
+	fxor	%%f42, %%f58, %%f58
+	fxor	%%f44, %%f60, %%f60
+	fxor	%%f46, %%f62, %%f62
+	stda	%%f48, [%0 + 64] %%asi
+	membar	#Sync|#StoreStore|#StoreLoad
+	wr	%%g0, 0, %%fprs
+	" : :
+	"r" (dest), "r" (src), "r" (len), "i" (FPRS_FEF), "i" (ASI_BLK_P) :
+	"cc", "memory");
+}
+#endif
+
+/*
+ * this one works reasonably on any x86 CPU
+ * (send me an assembly version for inclusion if you can make it faster)
+ *
+ * this one is just as fast as written in pure assembly on x86.
+ * the reason for this separate version is that the
+ * fast open-coded xor routine "32reg" produces suboptimal code
+ * on x86, due to lack of registers.
+ */
+XORBLOCK_TEMPLATE(8regs)
+{
+	int len  = dest->b_size;
+	long *destp   = (long *) dest->b_data;
+	long *sourcep = (long *) source->b_data;
+	long lines = len / (sizeof (long)) / 8, i;
+
+	for (i = lines; i > 0; i--) {
+		*(destp + 0) ^= *(sourcep + 0);
+		*(destp + 1) ^= *(sourcep + 1);
+		*(destp + 2) ^= *(sourcep + 2);
+		*(destp + 3) ^= *(sourcep + 3);
+		*(destp + 4) ^= *(sourcep + 4);
+		*(destp + 5) ^= *(sourcep + 5);
+		*(destp + 6) ^= *(sourcep + 6);
+		*(destp + 7) ^= *(sourcep + 7);
+		destp += 8;
+		sourcep += 8;
+	}
+}
+
+/*
+ * platform independent RAID5 checksum calculation, this should
+ * be very fast on any platform that has a decent amount of
+ * registers. (32 or more)
+ */
+XORBLOCK_TEMPLATE(32regs)
+{
+	int size  = dest->b_size;
+	int lines = size / (sizeof (long)) / 8, i;
+	long *destp   = (long *) dest->b_data;
+	long *sourcep = (long *) source->b_data;
+
+	for (i = lines; i > 0; i--) {
+
+	  /* LOTS of registers available...
+	     We do explicite loop-unrolling here for code which
+	     favours RISC machines.  In fact this is almoast direct
+	     RISC assembly on Alpha and SPARC :-)  */
+
+	  register long d0, d1, d2, d3, d4, d5, d6, d7;
+
+	  d0 = destp[0];	/* Pull the stuff into registers	*/
+	  d1 = destp[1];	/*  ... in bursts, if possible.		*/
+	  d2 = destp[2];
+	  d3 = destp[3];
+	  d4 = destp[4];
+	  d5 = destp[5];
+	  d6 = destp[6];
+	  d7 = destp[7];
+	  d0 ^= sourcep[0];
+	  d1 ^= sourcep[1];
+	  d2 ^= sourcep[2];
+	  d3 ^= sourcep[3];
+	  d4 ^= sourcep[4];
+	  d5 ^= sourcep[5];
+	  d6 ^= sourcep[6];
+	  d7 ^= sourcep[7];
+
+	  destp[0] = d0;	/* Store the result (in burts)		*/
+	  destp[1] = d1;
+	  destp[2] = d2;
+	  destp[3] = d3;
+	  destp[4] = d4;	/* Store the result (in burts)		*/
+	  destp[5] = d5;
+	  destp[6] = d6;
+	  destp[7] = d7;
+
+	  destp += 8;
+	  sourcep += 8;
+	}
+}
+
+/*
+ * (the -6*32 shift factor colors the cache)
+ */
+#define SIZE (PAGE_SIZE-6*32)
+
+static void xor_speed ( struct xor_block_template * func, 
+	struct buffer_head *b1, struct buffer_head *b2)
+{
+	int speed;
+	unsigned long now;
+	int i, count, max;
+
+	func->next = xor_functions;
+	xor_functions = func;
+
+	/*
+	 * count the number of XORs done during a whole jiffy.
+	 * calculate the speed of checksumming from this.
+	 * (we use a 2-page allocation to have guaranteed
+	 * color L1-cache layout)
+	 */
+	max = 0;
+	for (i = 0; i < 5; i++) {
+		now = jiffies;
+		count = 0;
+		while (jiffies == now) {
+			mb();
+			func->xor_block(b1,b2);
+			mb();
+			count++;
+			mb();
+		}
+		if (count > max)
+			max = count;
+	}
+
+	speed = max * (HZ*SIZE/1024);
+	func->speed = speed;
+
+	printk( "   %-10s: %5d.%03d MB/sec\n", func->name,
+		speed / 1000, speed % 1000);
+}
+
+static inline void pick_fastest_function(void)
+{
+	struct xor_block_template *f, *fastest;
+
+	fastest = xor_functions;
+	for (f = fastest; f; f = f->next) {
+		if (f->speed > fastest->speed)
+			fastest = f;
+	}
+	xor_block = fastest->xor_block;
+
+	printk( "using fastest function: %s (%d.%03d MB/sec)\n", fastest->name,
+		fastest->speed / 1000, fastest->speed % 1000);
+}
+ 
+
+void calibrate_xor_block(void)
+{
+	struct buffer_head b1, b2;
+
+	memset(&b1,0,sizeof(b1));
+	b2 = b1;
+
+	b1.b_data = (char *) md__get_free_pages(GFP_KERNEL,2);
+	if (!b1.b_data)
+		goto out;
+	b2.b_data = b1.b_data + 2*PAGE_SIZE + SIZE;
+
+	b1.b_size = SIZE;
+
+	printk(KERN_INFO "raid5: measuring checksumming speed\n");
+
+	sti(); /* should be safe */
+
+#ifdef __sparc64__
+	printk(KERN_INFO "raid5: using high-speed VIS checksum routine\n");
+	xor_speed(&t_xor_block_VIS,&b1,&b2);
+#endif
+
+#if 1
+#ifdef __i386__
+	if (md_cpu_has_mmx()) {
+		printk(KERN_INFO
+			"raid5: using high-speed MMX checksum routine\n");
+		xor_speed(&t_xor_block_pII_mmx,&b1,&b2);
+		xor_speed(&t_xor_block_p5_mmx,&b1,&b2);
+	}
+#endif
+#endif
+	xor_speed(&t_xor_block_8regs,&b1,&b2);
+	xor_speed(&t_xor_block_32regs,&b1,&b2);
+
+	free_pages((unsigned long)b1.b_data,2);
+
+out:
+	pick_fastest_function();
+}
+
+MD_EXPORT_SYMBOL(xor_block);
+
--- linux/drivers/block/ll_rw_blk.c.orig	Mon Aug  3 20:40:04 1998
+++ linux/drivers/block/ll_rw_blk.c	Mon Oct  5 03:01:22 1998
@@ -20,6 +20,7 @@
 #include <asm/system.h>
 #include <asm/io.h>
 #include <linux/blk.h>
+#include <linux/raid/md.h>
 
 /*
  * The request-struct contains all necessary data
@@ -335,8 +336,7 @@
                                kdevname(bh->b_rdev), rw,
                                (sector + count)>>1,
                                blk_size[major][MINOR(bh->b_rdev)]);
-			unlock_buffer(bh);
-			return;
+			goto end_io;
 		}
 
 	rw_ahead = 0;	/* normal case; gets changed below for READA/WRITEA */
@@ -349,8 +349,7 @@
 #if 0
 				printk ("make_request(): buffer uptodate for READ\n");
 #endif
-				unlock_buffer(bh); /* Hmmph! Already have it */
-				return;
+				goto end_io;
 			}
 			kstat.pgpgin++;
 			max_req = NR_REQUEST;	/* reads take precedence */
@@ -363,8 +362,7 @@
 #if 0
 				printk ("make_request(): buffer clean for WRITE\n");
 #endif
-				unlock_buffer(bh); /* Hmmph! Nothing to write */
-				return;
+				goto end_io;
 			}
 			/* We don't allow the write-requests to fill up the
 			 * queue completely:  we want some room for reads,
@@ -377,8 +375,7 @@
 		default:
 			printk(KERN_ERR "make_request: bad block dev cmd,"
                                " must be R/W/RA/WA\n");
-			unlock_buffer(bh);
-			return;
+			goto end_io;
 	}
 
 /* look for a free request. */
@@ -458,10 +455,8 @@
 
 /* if no request available: if rw_ahead, forget it; otherwise try again blocking.. */
 	if (!req) {
-		if (rw_ahead) {
-			unlock_buffer(bh);
-			return;
-		}
+		if (rw_ahead)
+			goto end_io;
 		req = __get_request_wait(max_req, bh->b_rdev);
 	}
 
@@ -477,6 +472,10 @@
 	req->bhtail = bh;
 	req->next = NULL;
 	add_request(major+blk_dev,req);
+	return;
+
+end_io:
+	bh->b_end_io(bh, test_bit(BH_Uptodate, &bh->b_state));
 }
 
 /* This function can be used to request a number of buffers from a block
@@ -648,6 +647,88 @@
 		}
 	}
 }
+
+/*
+ * First step of what used to be end_request
+ *
+ * 0 means continue with end_that_request_last,
+ * 1 means we are done
+ */
+
+int 
+end_that_request_first( struct request *req, int uptodate, char *name ) 
+{
+	struct buffer_head * bh;
+	int nsect;
+
+	req->errors = 0;
+	if (!uptodate) {
+		printk("end_request: I/O error, dev %s (%s), sector %lu\n",
+			kdevname(req->rq_dev), name, req->sector);
+		if ((bh = req->bh) != NULL) {
+			nsect = bh->b_size >> 9;
+			req->nr_sectors--;
+			req->nr_sectors &= ~(nsect - 1);
+			req->sector += nsect;
+			req->sector &= ~(nsect - 1);
+		}
+	}
+
+	if ((bh = req->bh) != NULL) {
+		req->bh = bh->b_reqnext;
+		bh->b_reqnext = NULL;
+		bh->b_end_io(bh, uptodate);
+		if ((bh = req->bh) != NULL) {
+			req->current_nr_sectors = bh->b_size >> 9;
+			if (req->nr_sectors < req->current_nr_sectors) {
+				req->nr_sectors = req->current_nr_sectors;
+				printk("end_request: buffer-list destroyed\n");
+			}
+			req->buffer = bh->b_data;
+			return 1;
+		}
+	}
+	return 0;
+}
+
+void
+end_that_request_last( struct request *req ) 
+{
+	if (req->sem != NULL)
+		up(req->sem);
+	req->rq_status = RQ_INACTIVE;
+	wake_up(&wait_for_request);
+}
+
+#define UNIT(dev) (MINOR(dev) >> hd->minor_shift)
+
+int is_device_idle(kdev_t dev)
+{
+	int i, unit;
+	register struct request *req;
+	struct gendisk *hd = find_gendisk(dev);
+
+	if (!hd)
+		return 1;
+
+	unit = UNIT(dev);
+	req = all_requests;
+	for (i = 0; i < NR_REQUEST; i++) {
+		if ((req->rq_status != RQ_INACTIVE) &&
+				/*
+				 * We want to have one resync per major
+				 * number at most.
+				 */
+				(UNIT(req->rq_dev) == unit))
+			break;
+		req++;
+	}
+	if (i == NR_REQUEST)
+		return 1;
+	return 0;
+}
+
+#undef UNIT
 
 int blk_dev_init(void)
 {
--- linux/drivers/block/genhd.c.orig	Mon Aug  3 20:33:03 1998
+++ linux/drivers/block/genhd.c	Thu Sep 24 20:44:53 1998
@@ -24,6 +24,7 @@
 #include <linux/kernel.h>
 #include <linux/major.h>
 #include <linux/string.h>
+#include <linux/raid/md.h>
 #ifdef CONFIG_BLK_DEV_INITRD
 #include <linux/blk.h>
 #endif
@@ -83,6 +84,14 @@
 			maj = "hd";
 	}
 #endif
+#ifdef CONFIG_BLK_DEV_MD
+	switch (hd->major) {
+		case MD_MAJOR:
+			unit -= 'a';
+			unit += '0';
+	}
+#endif
+
 	part = minor & ((1 << hd->minor_shift) - 1);
 	if (part)
 		sprintf(buf, "%s%c%d", maj, unit, part);
@@ -91,11 +100,12 @@
 	return buf;
 }
 
-static void add_partition (struct gendisk *hd, int minor, int start, int size)
+static void add_partition (struct gendisk *hd, int minor, int start, int size, int type)
 {
 	char buf[8];
 	hd->part[minor].start_sect = start;
 	hd->part[minor].nr_sects   = size;
+	hd->part[minor].type       = type;
 	printk(" %s", disk_name(hd, minor, buf));
 }
 
@@ -173,7 +183,7 @@
 			     first_sector + first_size))
 		      continue;
 
-		    add_partition(hd, current_minor, this_sector+START_SECT(p), NR_SECTS(p));
+		    add_partition(hd, current_minor, this_sector+START_SECT(p), NR_SECTS(p), ptype(p));
 		    current_minor++;
 		    if ((current_minor & mask) == 0)
 		      goto done;
@@ -232,7 +242,7 @@
 			break;
 
 		if (p->p_fstype != BSD_FS_UNUSED) {
-			add_partition(hd, current_minor, p->p_offset, p->p_size);
+			add_partition(hd, current_minor, p->p_offset, p->p_size, 0);
 			current_minor++;
 		}
 		p++;
@@ -347,7 +357,7 @@
 	for (i=1 ; i<=4 ; minor++,i++,p++) {
 		if (!NR_SECTS(p))
 			continue;
-		add_partition(hd, minor, first_sector+START_SECT(p), NR_SECTS(p));
+		add_partition(hd, minor, first_sector+START_SECT(p), NR_SECTS(p), ptype(p));
 		if (is_extended_partition(p)) {
 			printk(" <");
 			/*
@@ -384,7 +394,7 @@
 				break;
 			if (!(START_SECT(p) && NR_SECTS(p)))
 				continue;
-			add_partition(hd, current_minor, START_SECT(p), NR_SECTS(p));
+			add_partition(hd, current_minor, START_SECT(p), NR_SECTS(p), 0);
 		}
 	}
 	printk("\n");
@@ -457,7 +467,7 @@
 		if (partition->p_size)
 			add_partition(hd, current_minor,
 				first_sector+partition->p_offset,
-				partition->p_size);
+				partition->p_size, 0);
 		current_minor++;
 	}
 	printk("\n");
@@ -543,7 +553,7 @@
 		 * the minor numbers end up ok as per SunOS interpretation.
 		 */
 		st_sector = first_sector + SWAP32(p->start_cylinder) * spc;
-		add_partition(hd, current_minor, st_sector, SWAP32(p->num_sectors));
+		add_partition(hd, current_minor, st_sector, SWAP32(p->num_sectors), 0);
 		current_minor++;
 	}
 	printk("\n");
@@ -620,7 +630,7 @@
 					start_sect = htonl(pb->pb_Environment[9]) *
 						     htonl(pb->pb_Environment[3]) *
 						     htonl(pb->pb_Environment[5]);
-					add_partition(hd,current_minor,start_sect,nr_sects);
+					add_partition(hd,current_minor,start_sect,nr_sects, 0);
 					current_minor++;
 					res = 1;
 				}
@@ -751,6 +761,11 @@
 		setup_dev(p);
 		nr += p->nr_real;
 	}
+
+#ifdef CONFIG_BLK_DEV_MD
+	autodetect_raid();
+#endif
+
 #ifdef CONFIG_BLK_DEV_RAM
 #ifdef CONFIG_BLK_DEV_INITRD
 	if (initrd_start && mount_initrd) initrd_load();
--- linux/drivers/block/Config.in.orig	Mon Aug  3 20:40:04 1998
+++ linux/drivers/block/Config.in	Sat Sep  5 20:15:55 1998
@@ -43,6 +43,7 @@
 tristate 'Loopback device support' CONFIG_BLK_DEV_LOOP
 bool 'Multiple devices driver support' CONFIG_BLK_DEV_MD
 if [ "$CONFIG_BLK_DEV_MD" = "y" ]; then
+  bool 'Autodetect RAID partitions' CONFIG_AUTODETECT_RAID
   tristate '   Linear (append) mode' CONFIG_MD_LINEAR
   tristate '   RAID-0 (striping) mode' CONFIG_MD_STRIPED
   tristate '   RAID-1 (mirroring) mode' CONFIG_MD_MIRRORING
--- linux/drivers/block/Makefile.orig	Sat Sep  5 20:20:10 1998
+++ linux/drivers/block/Makefile	Tue Sep 22 12:35:15 1998
@@ -119,7 +119,7 @@
 endif
 
 ifeq ($(CONFIG_BLK_DEV_MD),y)
-LX_OBJS += md.o
+L_OBJS += md.o
 
 ifeq ($(CONFIG_MD_LINEAR),y)
 L_OBJS += linear.o
@@ -146,9 +146,10 @@
 endif
 
 ifeq ($(CONFIG_MD_RAID5),y)
-L_OBJS += raid5.o
+L_OBJS += xor.o raid5.o
 else
   ifeq ($(CONFIG_MD_RAID5),m)
+  L_OBJS += xor.o
   M_OBJS += raid5.o
   endif
 endif
--- linux/drivers/scsi/scsi.h.orig	Mon Aug  3 20:42:39 1998
+++ linux/drivers/scsi/scsi.h	Sun Oct  4 15:56:46 1998
@@ -521,23 +521,7 @@
 	    req->nr_sectors -= bh->b_size >> 9;
 	    req->sector += bh->b_size >> 9;
 	    bh->b_reqnext = NULL;
-	    /*
-	     * This is our 'MD IO has finished' event handler.
-	     * note that b_state should be cached in a register
-	     * anyways, so the overhead if this checking is almost 
-	     * zero. But anyways .. we never get OO for free :)
-	     */
-	    if (test_bit(BH_MD, &bh->b_state)) {
-		struct md_personality * pers=(struct md_personality *)bh->personality;
-		pers->end_request(bh,uptodate);
-	    }
-	    /*
-	     * the normal (nonmirrored and no RAID5) case:
-	     */
-	    else {
-		mark_buffer_uptodate(bh, uptodate);
-		unlock_buffer(bh);
-	    }
+            bh->b_end_io(bh, uptodate);
 	    sectors -= bh->b_size >> 9;
 	    if ((bh = req->bh) != NULL) {
 		req->current_nr_sectors = bh->b_size >> 9;
--- linux/arch/i386/kernel/entry.S.orig	Mon Aug  3 20:40:04 1998
+++ linux/arch/i386/kernel/entry.S	Sat Sep  5 20:15:55 1998
@@ -199,7 +199,7 @@
 6:	movl SYMBOL_NAME(smp_loops_per_tick), %ecx; \
 	cmpb SYMBOL_NAME(boot_cpu_id), %al; \
 	jne 7f; \
-	incl SYMBOL_NAME(jiffies);  \
+	lock; incl SYMBOL_NAME(jiffies);  \
 7:	btl $0, SYMBOL_NAME(kernel_flag); \
 	jc 2b; \
 	jmp 1b; \
--- linux/arch/i386/defconfig.orig	Mon Aug  3 20:40:04 1998
+++ linux/arch/i386/defconfig	Sat Sep  5 20:15:55 1998
@@ -55,7 +55,12 @@
 # Additional Block Devices
 #
 # CONFIG_BLK_DEV_LOOP is not set
-# CONFIG_BLK_DEV_MD is not set
+CONFIG_BLK_DEV_MD=y
+CONFIG_AUTODETECT_RAID=y
+CONFIG_MD_LINEAR=y
+CONFIG_MD_STRIPED=y
+CONFIG_MD_MIRRORING=y
+CONFIG_MD_RAID5=y
 # CONFIG_BLK_DEV_RAM is not set
 # CONFIG_BLK_DEV_XD is not set
 # CONFIG_PARIDE is not set
