]> git.ipfire.org Git - thirdparty/mdadm.git/blobdiff - Grow.c
Disk removal support for Raid10->Raid0 takeover
[thirdparty/mdadm.git] / Grow.c
diff --git a/Grow.c b/Grow.c
index f36704191a73650b448169ba5655c4e80c8ce168..1d92d68024332ee4e782e023c4597b86010cea4c 100644 (file)
--- a/Grow.c
+++ b/Grow.c
@@ -51,33 +51,41 @@ int Grow_Add_device(char *devname, int fd, char *newdev)
        int nfd, fd2;
        int d, nd;
        struct supertype *st = NULL;
-
+       char *subarray = NULL;
 
        if (ioctl(fd, GET_ARRAY_INFO, &info.array) < 0) {
                fprintf(stderr, Name ": cannot get array info for %s\n", devname);
                return 1;
        }
 
-       st = super_by_fd(fd);
+       if (info.array.level != -1) {
+               fprintf(stderr, Name ": can only add devices to linear arrays\n");
+               return 1;
+       }
+
+       st = super_by_fd(fd, &subarray);
        if (!st) {
                fprintf(stderr, Name ": cannot handle arrays with superblock version %d\n", info.array.major_version);
                return 1;
        }
 
-       if (info.array.level != -1) {
-               fprintf(stderr, Name ": can only add devices to linear arrays\n");
-               return 1;
+       if (subarray) {
+               fprintf(stderr, Name ": Cannot grow linear sub-arrays yet\n");
+               free(subarray);
+               free(st);
        }
 
        nfd = open(newdev, O_RDWR|O_EXCL|O_DIRECT);
        if (nfd < 0) {
                fprintf(stderr, Name ": cannot open %s\n", newdev);
+               free(st);
                return 1;
        }
        fstat(nfd, &stb);
        if ((stb.st_mode & S_IFMT) != S_IFBLK) {
                fprintf(stderr, Name ": %s is not a block device!\n", newdev);
                close(nfd);
+               free(st);
                return 1;
        }
        /* now check out all the devices and make sure we can read the superblock */
@@ -85,28 +93,37 @@ int Grow_Add_device(char *devname, int fd, char *newdev)
                mdu_disk_info_t disk;
                char *dv;
 
+               st->ss->free_super(st);
+
                disk.number = d;
                if (ioctl(fd, GET_DISK_INFO, &disk) < 0) {
                        fprintf(stderr, Name ": cannot get device detail for device %d\n",
                                d);
+                       close(nfd);
+                       free(st);
                        return 1;
                }
                dv = map_dev(disk.major, disk.minor, 1);
                if (!dv) {
                        fprintf(stderr, Name ": cannot find device file for device %d\n",
                                d);
+                       close(nfd);
+                       free(st);
                        return 1;
                }
                fd2 = dev_open(dv, O_RDWR);
                if (!fd2) {
                        fprintf(stderr, Name ": cannot open device file %s\n", dv);
+                       close(nfd);
+                       free(st);
                        return 1;
                }
-               st->ss->free_super(st);
 
                if (st->ss->load_super(st, fd2, NULL)) {
                        fprintf(stderr, Name ": cannot find super block on %s\n", dv);
+                       close(nfd);
                        close(fd2);
+                       free(st);
                        return 1;
                }
                close(fd2);
@@ -204,6 +221,7 @@ int Grow_addbitmap(char *devname, int fd, char *file, int chunk, int delay, int
        mdu_bitmap_file_t bmf;
        mdu_array_info_t array;
        struct supertype *st;
+       char *subarray = NULL;
        int major = BITMAP_MAJOR_HI;
        int vers = md_get_version(fd);
        unsigned long long bitmapsize, array_size;
@@ -253,6 +271,11 @@ int Grow_addbitmap(char *devname, int fd, char *file, int chunk, int delay, int
                        devname);
                return 1;
        }
+
+       if (strcmp(file, "none") == 0) {
+               fprintf(stderr, Name ": no bitmap found on %s\n", devname);
+               return 1;
+       }
        if (array.level <= 0) {
                fprintf(stderr, Name ": Bitmaps not meaningful with level %s\n",
                        map_num(pers, array.level)?:"of this array");
@@ -277,17 +300,25 @@ int Grow_addbitmap(char *devname, int fd, char *file, int chunk, int delay, int
                bitmapsize = bitmapsize * array.raid_disks / ncopies;
        }
 
-       st = super_by_fd(fd);
+       st = super_by_fd(fd, &subarray);
        if (!st) {
                fprintf(stderr, Name ": Cannot understand version %d.%d\n",
                        array.major_version, array.minor_version);
                return 1;
        }
-       if (strcmp(file, "none") == 0) {
-               fprintf(stderr, Name ": no bitmap found on %s\n", devname);
+       if (subarray) {
+               fprintf(stderr, Name ": Cannot add bitmaps to sub-arrays yet\n");
+               free(subarray);
+               free(st);
                return 1;
-       } else if (strcmp(file, "internal") == 0) {
+       }
+       if (strcmp(file, "internal") == 0) {
                int d;
+               if (st->ss->add_internal_bitmap == NULL) {
+                       fprintf(stderr, Name ": Internal bitmaps not supported "
+                               "with %s metadata\n", st->ss->name);
+                       return 1;
+               }
                for (d=0; d< st->max_devs; d++) {
                        mdu_disk_info_t disk;
                        char *dv;
@@ -381,7 +412,7 @@ int Grow_addbitmap(char *devname, int fd, char *file, int chunk, int delay, int
 /*
  * When reshaping an array we might need to backup some data.
  * This is written to all spares with a 'super_block' describing it.
- * The superblock goes 1K form the end of the used space on the
+ * The superblock goes 4K from the end of the used space on the
  * device.
  * It if written after the backup is complete.
  * It has the following structure.
@@ -404,7 +435,7 @@ static struct mdp_backup_super {
        __u8 pad[512-68-32];
 } __attribute__((aligned(512))) bsb, bsb2;
 
-int bsb_csum(char *buf, int len)
+static __u32 bsb_csum(char *buf, int len)
 {
        int i;
        int csum = 0;
@@ -427,32 +458,83 @@ static int child_same_size(int afd, struct mdinfo *sra, unsigned long blocks,
                           int disks, int chunk, int level, int layout, int data,
                           int dests, int *destfd, unsigned long long *destoffsets);
 
-int freeze_array(struct mdinfo *sra)
+static int freeze_container(struct supertype *st)
+{
+       int container_dev = (st->container_dev != NoMdDev
+                            ? st->container_dev : st->devnum);
+       char *container = devnum2devname(container_dev);
+
+       if (!container) {
+               fprintf(stderr, Name
+                       ": could not determine container name, freeze aborted\n");
+               return -2;
+       }
+
+       if (block_monitor(container, 1)) {
+               fprintf(stderr, Name ": failed to freeze container\n");
+               return -2;
+       }
+
+       return 1;
+}
+
+static void unfreeze_container(struct supertype *st)
 {
-       /* Try to freeze resync on this array.
+       int container_dev = (st->container_dev != NoMdDev
+                            ? st->container_dev : st->devnum);
+       char *container = devnum2devname(container_dev);
+
+       if (!container) {
+               fprintf(stderr, Name
+                       ": could not determine container name, unfreeze aborted\n");
+               return;
+       }
+
+       unblock_monitor(container, 1);
+}
+
+static int freeze(struct supertype *st)
+{
+       /* Try to freeze resync/rebuild on this array/container.
         * Return -1 if the array is busy,
+        * return -2 container cannot be frozen,
         * return 0 if this kernel doesn't support 'frozen'
         * return 1 if it worked.
         */
-       char buf[20];
-       if (sysfs_get_str(sra, NULL, "sync_action", buf, 20) <= 0)
-               return 0;
-       if (strcmp(buf, "idle\n") != 0 &&
-           strcmp(buf, "frozen\n") != 0)
-               return -1;
-       if (sysfs_set_str(sra, NULL, "sync_action", "frozen") < 0)
-               return 0;
-       return 1;
+       if (st->ss->external)
+               return freeze_container(st);
+       else {
+               struct mdinfo *sra = sysfs_read(-1, st->devnum, GET_VERSION);
+               int err;
+
+               if (!sra)
+                       return -1;
+               err = sysfs_freeze_array(sra);
+               sysfs_free(sra);
+               return err;
+       }
 }
 
-void unfreeze_array(struct mdinfo *sra, int frozen)
+static void unfreeze(struct supertype *st, int frozen)
 {
        /* If 'frozen' is 1, unfreeze the array */
-       if (frozen > 0)
-               sysfs_set_str(sra, NULL, "sync_action", "idle");
+       if (frozen <= 0)
+               return;
+
+       if (st->ss->external)
+               return unfreeze_container(st);
+       else {
+               struct mdinfo *sra = sysfs_read(-1, st->devnum, GET_VERSION);
+
+               if (sra)
+                       sysfs_set_str(sra, NULL, "sync_action", "idle");
+               else
+                       fprintf(stderr, Name ": failed to unfreeze array\n");
+               sysfs_free(sra);
+       }
 }
 
-void wait_reshape(struct mdinfo *sra)
+static void wait_reshape(struct mdinfo *sra)
 {
        int fd = sysfs_get_fd(sra, NULL, "sync_action");
        char action[20];
@@ -469,8 +551,296 @@ void wait_reshape(struct mdinfo *sra)
                }
        } while  (strncmp(action, "reshape", 7) == 0);
 }
-                       
-               
+
+static int reshape_super(struct supertype *st, long long size, int level,
+                        int layout, int chunksize, int raid_disks,
+                        char *backup_file, char *dev, int verbose)
+{
+       /* nothing extra to check in the native case */
+       if (!st->ss->external)
+               return 0;
+       if (!st->ss->reshape_super ||
+           !st->ss->manage_reshape) {
+               fprintf(stderr, Name ": %s metadata does not support reshape\n",
+                       st->ss->name);
+               return 1;
+       }
+
+       return st->ss->reshape_super(st, size, level, layout, chunksize,
+                                    raid_disks, backup_file, dev, verbose);
+}
+
+static void sync_metadata(struct supertype *st)
+{
+       if (st->ss->external) {
+               if (st->update_tail)
+                       flush_metadata_updates(st);
+               else
+                       st->ss->sync_metadata(st);
+       }
+}
+
+static int subarray_set_num(char *container, struct mdinfo *sra, char *name, int n)
+{
+       /* when dealing with external metadata subarrays we need to be
+        * prepared to handle EAGAIN.  The kernel may need to wait for
+        * mdmon to mark the array active so the kernel can handle
+        * allocations/writeback when preparing the reshape action
+        * (md_allow_write()).  We temporarily disable safe_mode_delay
+        * to close a race with the array_state going clean before the
+        * next write to raid_disks / stripe_cache_size
+        */
+       char safe[50];
+       int rc;
+
+       /* only 'raid_disks' and 'stripe_cache_size' trigger md_allow_write */
+       if (strcmp(name, "raid_disks") != 0 &&
+           strcmp(name, "stripe_cache_size") != 0)
+               return sysfs_set_num(sra, NULL, name, n);
+
+       rc = sysfs_get_str(sra, NULL, "safe_mode_delay", safe, sizeof(safe));
+       if (rc <= 0)
+               return -1;
+       sysfs_set_num(sra, NULL, "safe_mode_delay", 0);
+       rc = sysfs_set_num(sra, NULL, name, n);
+       if (rc < 0 && errno == EAGAIN) {
+               ping_monitor(container);
+               /* if we get EAGAIN here then the monitor is not active
+                * so stop trying
+                */
+               rc = sysfs_set_num(sra, NULL, name, n);
+       }
+       sysfs_set_str(sra, NULL, "safe_mode_delay", safe);
+       return rc;
+}
+
+static int reshape_container_raid_disks(char *container, int raid_disks)
+{
+       /* for each subarray switch to a raid level that can
+        * support the reshape, and set raid disks
+        */
+       struct mdstat_ent *ent, *e;
+       int changed = 0, rv = 0, err = 0;
+
+       ent = mdstat_read(1, 0);
+       if (!ent) {
+               fprintf(stderr, Name ": unable to read /proc/mdstat\n");
+               return -1;
+       }
+
+       changed = 0;
+       for (e = ent; e; e = e->next) {
+               struct mdinfo *sub;
+               unsigned int cache;
+               int level, takeover_delta = 0;
+
+               if (!is_container_member(e, container))
+                       continue;
+
+               level = map_name(pers, e->level);
+               if (level == 0) {
+                       sub = sysfs_read(-1, e->devnum, GET_VERSION);
+                       if (!sub)
+                               break;
+                       /* metadata records 'orig_level' */
+                       rv = sysfs_set_num(sub, NULL, "level", 4);
+                       if (rv < 0) {
+                               err = errno;
+                               break;
+                       }
+                       /* we want spares to be used for capacity
+                        * expansion, not rebuild
+                        */
+                       takeover_delta = 1;
+
+                       sysfs_free(sub);
+                       level = 4;
+               }
+
+               sub = NULL;
+               switch (level) {
+               default:
+                       rv = -1;
+                       break;
+               case 4:
+               case 5:
+               case 6:
+                       sub = sysfs_read(-1, e->devnum, GET_CHUNK|GET_CACHE);
+                       if (!sub)
+                               break;
+                       cache = (sub->array.chunk_size / 4096) * 4;
+                       if (cache > sub->cache_size)
+                               rv = subarray_set_num(container, sub,
+                                                     "stripe_cache_size", cache);
+                       if (rv) {
+                               err = errno;
+                               break;
+                       }
+                       /* fall through */
+               case 1:
+                       if (!sub)
+                               sub = sysfs_read(-1, e->devnum, GET_VERSION);
+                       if (!sub)
+                               break;
+
+                       rv = subarray_set_num(container, sub, "raid_disks",
+                                             raid_disks + takeover_delta);
+                       if (rv)
+                               err = errno;
+                       else
+                               changed++;
+                       break;
+               }
+               sysfs_free(sub);
+               if (rv)
+                       break;
+       }
+       free_mdstat(ent);
+       if (rv) {
+               fprintf(stderr, Name
+                       ": failed to initiate container reshape%s%s\n",
+                       err ? ": " : "", err ? strerror(err) : "");
+               return rv;
+       }
+
+       return changed;
+}
+
+static void revert_container_raid_disks(struct supertype *st, int fd, char *container)
+{
+       /* we failed to prepare all subarrays in the container for
+        * reshape, so cancel the changes and restore the nominal raid
+        * level
+        */
+       struct mdstat_ent *ent, *e;
+
+       ent = mdstat_read(0, 0);
+       if (!ent) {
+               fprintf(stderr, Name
+                       ": failed to read /proc/mdstat while aborting reshape\n");
+               return;
+       }
+
+       if (st->ss->load_container(st, fd, NULL)) {
+               fprintf(stderr, Name
+                       ": failed read metadata while aborting reshape\n");
+               return ;
+       }
+
+
+       for (e = ent; e; e = e->next) {
+               int level_fixed = 0, disks_fixed = 0;
+               struct mdinfo *sub, *prev;
+               char *subarray;
+
+               if (!is_container_member(e, container))
+                       continue;
+
+               subarray = to_subarray(e, container);
+               prev = st->ss->container_content(st, subarray);
+
+               /* changing level might change raid_disks so we do it
+                * first and then check if raid_disks still needs fixing
+                */
+               if (map_name(pers, e->level) != prev->array.level) {
+                       sub = sysfs_read(-1, e->devnum, GET_VERSION);
+                       if (sub &&
+                           !sysfs_set_num(sub, NULL, "level", prev->array.level))
+                               level_fixed = 1;
+                       sysfs_free(sub);
+               } else
+                       level_fixed = 1;
+
+               sub = sysfs_read(-1, e->devnum, GET_DISKS);
+               if (sub && sub->array.raid_disks != prev->array.raid_disks) {
+                       if (!subarray_set_num(container, sub, "raid_disks",
+                                             prev->array.raid_disks))
+                               disks_fixed = 1;
+               } else if (sub)
+                       disks_fixed = 1;
+               sysfs_free(sub);
+
+               if (!disks_fixed || !level_fixed)
+                       fprintf(stderr, Name
+                               ": failed to restore %s to a %d-disk %s array\n",
+                               e->dev, prev->array.raid_disks,
+                               map_num(pers, prev->array.level));
+               free(prev);
+       }
+       st->ss->free_super(st);
+       free_mdstat(ent);
+}
+
+int remove_disks_on_raid10_to_raid0_takeover(struct supertype *st,
+                                            struct mdinfo *sra,
+                                            int layout)
+{
+       int nr_of_copies;
+       struct mdinfo *remaining;
+       int slot;
+
+       nr_of_copies = layout & 0xff;
+
+       remaining = sra->devs;
+       sra->devs = NULL;
+       /* for each 'copy', select one device and remove from the list. */
+       for (slot = 0; slot < sra->array.raid_disks; slot += nr_of_copies) {
+               struct mdinfo **diskp;
+               int found = 0;
+
+               /* Find a working device to keep */
+               for (diskp =  &remaining; *diskp ; diskp = &(*diskp)->next) {
+                       struct mdinfo *disk = *diskp;
+
+                       if (disk->disk.raid_disk < slot)
+                               continue;
+                       if (disk->disk.raid_disk >= slot + nr_of_copies)
+                               continue;
+                       if (disk->disk.state & (1<<MD_DISK_REMOVED))
+                               continue;
+                       if (disk->disk.state & (1<<MD_DISK_FAULTY))
+                               continue;
+                       if (!(disk->disk.state & (1<<MD_DISK_SYNC)))
+                               continue;
+
+                       /* We have found a good disk to use! */
+                       *diskp = disk->next;
+                       disk->next = sra->devs;
+                       sra->devs = disk;
+                       found = 1;
+                       break;
+               }
+               if (!found)
+                       break;
+       }
+
+       if (slot < sra->array.raid_disks) {
+               /* didn't find all slots */
+               struct mdinfo **e;
+               e = &remaining;
+               while (*e)
+                       e = &(*e)->next;
+               *e = sra->devs;
+               sra->devs = remaining;
+               return 1;
+       }
+
+       /* Remove all 'remaining' devices from the array */
+       while (remaining) {
+               struct mdinfo *sd = remaining;
+               remaining = sd->next;
+
+               sysfs_set_str(sra, sd, "state", "faulty");
+               sysfs_set_str(sra, sd, "slot", "none");
+               sysfs_set_str(sra, sd, "state", "remove");
+               sd->disk.state |= (1<<MD_DISK_REMOVED);
+               sd->disk.state &= ~(1<<MD_DISK_SYNC);
+               sd->next = sra->devs;
+               sra->devs = sd;
+       }
+       return 0;
+}
+
 int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                 long long size,
                 int level, char *layout_str, int chunksize, int raid_disks)
@@ -496,11 +866,12 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
        char *c;
        int rv = 0;
        struct supertype *st;
+       char *subarray = NULL;
 
        int nchunk, ochunk;
        int nlayout, olayout;
        int ndisks, odisks;
-       int ndata, odata;
+       unsigned int ndata, odata;
        int orig_level = UnSet;
        char alt_layout[40];
        int *fdlist;
@@ -510,9 +881,11 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
        int err;
        int frozen;
        unsigned long a,b, blocks, stripes;
-       int cache;
+       unsigned long cache;
        unsigned long long array_size;
        int changed = 0;
+       char *container = NULL;
+       int cfd = -1;
        int done;
 
        struct mdinfo *sra;
@@ -524,6 +897,15 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                return 1;
        }
 
+       if (size >= 0 &&
+           (chunksize || level!= UnSet || layout_str || raid_disks)) {
+               fprintf(stderr, Name ": cannot change component size at the same time "
+                       "as other changes.\n"
+                       "   Change size first, then check data is intact before "
+                       "making other changes.\n");
+               return 1;
+       }
+
        if (raid_disks && raid_disks < array.raid_disks && array.level > 1 &&
            get_linux_version() < 2006032 &&
            !check_env("MDADM_FORCE_FEWER")) {
@@ -531,9 +913,81 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        "       Please use a newer kernel\n");
                return 1;
        }
-       sra = sysfs_read(fd, 0, GET_LEVEL);
-       frozen = freeze_array(sra);
-       if (frozen < 0) {
+
+       st = super_by_fd(fd, &subarray);
+       if (!st) {
+               fprintf(stderr, Name ": Unable to determine metadata format for %s\n", devname);
+               return 1;
+       }
+
+       /* in the external case we need to check that the requested reshape is
+        * supported, and perform an initial check that the container holds the
+        * pre-requisite spare devices (mdmon owns final validation)
+        */
+       if (st->ss->external) {
+               int container_dev;
+               int rv;
+
+               if (subarray) {
+                       container_dev = st->container_dev;
+                       cfd = open_dev_excl(st->container_dev);
+               } else if (size >= 0 || layout_str != NULL || chunksize != 0 ||
+                          level != UnSet) {
+                       fprintf(stderr,
+                               Name ": %s is a container, only 'raid-devices' can be changed\n",
+                               devname);
+                       return 1;
+               } else {
+                       container_dev = st->devnum;
+                       close(fd);
+                       cfd = open_dev_excl(st->devnum);
+                       fd = cfd;
+               }
+               if (cfd < 0) {
+                       fprintf(stderr, Name ": Unable to open container for %s\n",
+                               devname);
+                       free(subarray);
+                       return 1;
+               }
+
+               container = devnum2devname(st->devnum);
+               if (!container) {
+                       fprintf(stderr, Name ": Could not determine container name\n");
+                       free(subarray);
+                       return 1;
+               }
+
+               if (subarray)
+                       rv = st->ss->load_container(st, cfd, NULL);
+               else
+                       rv = st->ss->load_super(st, cfd, NULL);
+               if (rv) {
+                       fprintf(stderr, Name ": Cannot read superblock for %s\n",
+                               devname);
+                       free(subarray);
+                       return 1;
+               }
+
+               if (mdmon_running(container_dev))
+                       st->update_tail = &st->updates;
+       }
+
+       sra = sysfs_read(fd, 0, GET_LEVEL | GET_DISKS | GET_DEVS | GET_STATE);
+       if (sra) {
+               if (st->ss->external && subarray == NULL) {
+                       array.level = LEVEL_CONTAINER;
+                       sra->array.level = LEVEL_CONTAINER;
+               }
+       } else {
+               fprintf(stderr, Name ": failed to read sysfs parameters for %s\n",
+                       devname);
+               return 1;
+       }
+       frozen = freeze(st);
+       if (frozen < -1) {
+               /* freeze() already spewed the reason */
+               return 1;
+       } else if (frozen < 0) {
                fprintf(stderr, Name ": %s is performing resync/recovery and cannot"
                        " be reshaped\n", devname);
                return 1;
@@ -541,6 +995,13 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
 
        /* ========= set size =============== */
        if (size >= 0 && (size == 0 || size != array.size)) {
+               long long orig_size = array.size;
+
+               if (reshape_super(st, size, UnSet, UnSet, 0, 0, NULL, devname, !quiet)) {
+                       rv = 1;
+                       goto release;
+               }
+               sync_metadata(st);
                array.size = size;
                if (array.size != size) {
                        /* got truncated to 32bit, write to
@@ -554,16 +1015,51 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                } else
                        rv = ioctl(fd, SET_ARRAY_INFO, &array);
                if (rv != 0) {
+                       int err = errno;
+
+                       /* restore metadata */
+                       if (reshape_super(st, orig_size, UnSet, UnSet, 0, 0,
+                                         NULL, devname, !quiet) == 0)
+                               sync_metadata(st);
                        fprintf(stderr, Name ": Cannot set device size for %s: %s\n",
-                               devname, strerror(errno));
+                               devname, strerror(err));
+                       if (err == EBUSY && 
+                           (array.state & (1<<MD_SB_BITMAP_PRESENT)))
+                               fprintf(stderr, "       Bitmap must be removed before size can be changed\n");
                        rv = 1;
                        goto release;
                }
                ioctl(fd, GET_ARRAY_INFO, &array);
+               size = get_component_size(fd)/2;
+               if (size == 0)
+                       size = array.size;
                if (!quiet)
-                       fprintf(stderr, Name ": component size of %s has been set to %dK\n",
-                               devname, array.size);
+                       fprintf(stderr, Name ": component size of %s has been set to %lluK\n",
+                               devname, size);
                changed = 1;
+       } else if (array.level != LEVEL_CONTAINER) {
+               size = get_component_size(fd)/2;
+               if (size == 0)
+                       size = array.size;
+       }
+
+       /* ========= check for Raid10 -> Raid0 conversion ===============
+        * current implemenation assumes that following conditions must be met:
+        * - far_copies == 1
+        * - near_copies == 2
+        */
+       if (level == 0 && array.level == 10 &&
+           array.layout == ((1 << 8) + 2) && !(array.raid_disks & 1)) {
+               int err;
+               err = remove_disks_on_raid10_to_raid0_takeover(st, sra, array.layout);
+               if (err) {
+                       dprintf(Name": Array cannot be reshaped\n");
+                       if (container)
+                               free(container);
+                       if (cfd > -1)
+                               close(cfd);
+                       return 1;
+               }
        }
 
        /* ======= set level =========== */
@@ -643,13 +1139,26 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        } else
                                layout_str = "parity-last";
                } else {
+                       /* Level change is a simple takeover.  In the external
+                        * case we don't check with the metadata handler until
+                        * we establish what the final layout will be.  If the
+                        * level change is disallowed we will revert to
+                        * orig_level without disturbing the metadata, otherwise
+                        * we will send an update.
+                        */
                        c = map_num(pers, level);
-                       if (c == NULL)
-                               return 1;/* not possible */
+                       if (c == NULL) {
+                               rv = 1;/* not possible */
+                               goto release;
+                       }
                        err = sysfs_set_str(sra, NULL, "level", c);
                        if (err) {
+                               err = errno;
                                fprintf(stderr, Name ": %s: could not set level to %s\n",
                                        devname, c);
+                               if (err == EBUSY && 
+                                   (array.state & (1<<MD_SB_BITMAP_PRESENT)))
+                                       fprintf(stderr, "       Bitmap must be removed before level can be changed\n");
                                rv = 1;
                                goto release;
                        }
@@ -669,9 +1178,9 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
 
        /* ========= set shape (chunk_size / layout / ndisks)  ============== */
        /* Check if layout change is a no-op */
-       if (layout_str) switch(array.level) {
+       switch (array.level) {
        case 5:
-               if (array.layout == map_name(r5layout, layout_str))
+               if (layout_str && array.layout == map_name(r5layout, layout_str))
                        layout_str = NULL;
                break;
        case 6:
@@ -687,8 +1196,9 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        rv = 1;
                        goto release;
                }
-               if (strcmp(layout_str, "normalise") == 0 ||
-                   strcmp(layout_str, "normalize") == 0) {
+               if (layout_str &&
+                   (strcmp(layout_str, "normalise") == 0 ||
+                    strcmp(layout_str, "normalize") == 0)) {
                        char *hyphen;
                        strcpy(alt_layout, map_num(r6layout, array.layout));
                        hyphen = strrchr(alt_layout, '-');
@@ -698,7 +1208,7 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        }
                }
 
-               if (array.layout == map_name(r6layout, layout_str))
+               if (layout_str && array.layout == map_name(r6layout, layout_str))
                        layout_str = NULL;
                if (layout_str && strcmp(layout_str, "preserve") == 0)
                        layout_str = NULL;
@@ -707,6 +1217,11 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
        if (layout_str == NULL
            && (chunksize == 0 || chunksize*1024 == array.chunk_size)
            && (raid_disks == 0 || raid_disks == array.raid_disks)) {
+               if (reshape_super(st, -1, level, UnSet, 0, 0, NULL, devname, !quiet)) {
+                       rv = 1;
+                       goto release;
+               }
+               sync_metadata(st);
                rv = 0;
                if (level != UnSet && level != array.level) {
                        /* Looks like this level change doesn't need
@@ -715,25 +1230,82 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        c = map_num(pers, level);
                        if (c) {
                                rv = sysfs_set_str(sra, NULL, "level", c);
-                               if (rv)
+                               if (rv) {
+                                       int err = errno;
                                        fprintf(stderr, Name ": %s: could not set level to %s\n",
                                                devname, c);
+                                       if (err == EBUSY && 
+                                           (array.state & (1<<MD_SB_BITMAP_PRESENT)))
+                                               fprintf(stderr, "       Bitmap must be removed before level can be changed\n");
+                                       rv = 1;
+                               }
                        }
                } else if (!changed && !quiet)
                        fprintf(stderr, Name ": %s: no change requested\n",
                                devname);
+
+               if (st->ss->external && !mdmon_running(st->container_dev) &&
+                   level > 0) {
+                       start_mdmon(st->container_dev);
+                       ping_monitor(container);
+               }
                goto release;
        }
 
        c = map_num(pers, array.level);
        if (c == NULL) c = "-unknown-";
-       switch(array.level) {
+       switch (array.level) {
        default: /* raid0, linear, multipath cannot be reconfigured */
                fprintf(stderr, Name ": %s array %s cannot be reshaped.\n",
                        c, devname);
+               /* TODO raid0 raiddisks can be reshaped via raid4 */
                rv = 1;
                break;
+       case LEVEL_CONTAINER: {
+               int count;
+
+               /* double check that we are not changing anything but raid_disks */
+               if (size >= 0 || layout_str != NULL || chunksize != 0 || level != UnSet) {
+                       fprintf(stderr,
+                               Name ": %s is a container, only 'raid-devices' can be changed\n",
+                               devname);
+                       rv = 1;
+                       goto release;
+               }
 
+               st->update_tail = &st->updates;
+               if (reshape_super(st, -1, UnSet, UnSet, 0, raid_disks,
+                                 backup_file, devname, !quiet)) {
+                       rv = 1;
+                       goto release;
+               }
+
+               count = reshape_container_raid_disks(container, raid_disks);
+               if (count < 0) {
+                       revert_container_raid_disks(st, fd, container);
+                       rv = 1;
+                       goto release;
+               } else if (count == 0) {
+                       if (!quiet)
+                               fprintf(stderr, Name
+                                       ": no active subarrays to reshape\n");
+                       goto release;
+               }
+
+               if (!mdmon_running(st->devnum)) {
+                       start_mdmon(st->devnum);
+                       ping_monitor(container);
+               }
+               sync_metadata(st);
+
+               /* give mdmon a chance to allocate spares */
+               ping_manager(container);
+
+               /* manage_reshape takes care of releasing the array(s) */
+               st->ss->manage_reshape(st, backup_file);
+               frozen = 0;
+               goto release;
+       }
        case LEVEL_FAULTY: /* only 'layout' change is permitted */
 
                if (chunksize  || raid_disks) {
@@ -747,7 +1319,6 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
 
                array.layout = parse_layout_faulty(layout_str);
                if (array.layout < 0) {
-                       int rv;
                        fprintf(stderr, Name ": %s: layout %s not understood for 'faulty' array\n",
                                devname, layout_str);
                        rv = 1;
@@ -770,6 +1341,12 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        break;
                }
                if (raid_disks > 0) {
+                       if (reshape_super(st, -1, UnSet, UnSet, 0, raid_disks,
+                                         NULL, devname, !quiet)) {
+                               rv = 1;
+                               goto release;
+                       }
+                       sync_metadata(st);
                        array.raid_disks = raid_disks;
                        if (ioctl(fd, SET_ARRAY_INFO, &array) != 0) {
                                fprintf(stderr, Name ": Cannot set raid-devices for %s: %s\n",
@@ -787,7 +1364,10 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                 * layout/chunksize/raid_disks can be changed
                 * though the kernel may not support it all.
                 */
-               st = super_by_fd(fd);
+               if (subarray) {
+                       fprintf(stderr, Name ": Cannot reshape subarrays yet\n");
+                       break;
+               }
 
                /*
                 * There are three possibilities.
@@ -833,10 +1413,10 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
 
                if (chunksize) {
                        nchunk = chunksize * 1024;
-                       if (array.size % chunksize) {
-                               fprintf(stderr, Name ": component size %dK is not"
+                       if (size % chunksize) {
+                               fprintf(stderr, Name ": component size %lluK is not"
                                        " a multiple of chunksize %dK\n",
-                                       array.size, chunksize);
+                                       size, chunksize);
                                break;
                        }
                }
@@ -849,7 +1429,8 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                                if (nlayout == UnSet) {
                                        fprintf(stderr, Name ": layout %s not understood for raid5.\n",
                                                layout_str);
-                                       return 1;
+                                       rv = 1;
+                                       goto release;
                                }
                                break;
 
@@ -858,7 +1439,8 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                                if (nlayout == UnSet) {
                                        fprintf(stderr, Name ": layout %s not understood for raid6.\n",
                                                layout_str);
-                                       return 1;
+                                       rv = 1;
+                                       goto release;
                                }
                                break;
                        }
@@ -871,14 +1453,19 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        ndata--;
                }
 
+               if (odata == ndata &&
+                   get_linux_version() < 2006032) {
+                       fprintf(stderr, Name ": in-place reshape is not safe before 2.6.32, sorry.\n");
+                       break;
+               }
+
                /* Check that we can hold all the data */
-               size = ndata * array.size;
                get_dev_size(fd, NULL, &array_size);
-               if (size < (array_size/1024)) {
+               if (ndata * (unsigned long long)size < (array_size/1024)) {
                        fprintf(stderr, Name ": this change will reduce the size of the array.\n"
                                "       use --grow --array-size first to truncate array.\n"
                                "       e.g. mdadm --grow %s --array-size %llu\n",
-                               devname, size);
+                               devname, ndata * size);
                        rv = 1;
                        break;
                }
@@ -888,8 +1475,8 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                 * old stripes and a whole number of new stripes.
                 * So LCM for (chunksize*datadisks).
                 */
-               a = ochunk/512 * odata;
-               b = nchunk/512 * ndata;
+               a = (ochunk/512) * odata;
+               b = (nchunk/512) * ndata;
                /* Find GCD */
                while (a != b) {
                        if (a < b)
@@ -898,22 +1485,13 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                                a -= b;
                }
                /* LCM == product / GCD */
-               blocks = ochunk/512 * nchunk/512 * odata * ndata / a;
-
-               if (ndata == odata) {
-                       /* Make 'blocks' bigger for better throughput, but
-                        * not so big that we reject it below.
-                        */
-                       if (blocks * 32 < sra->component_size)
-                               blocks *= 16;
-               } else
-                       fprintf(stderr, Name ": Need to backup %luK of critical "
-                               "section..\n", blocks/2);
+               blocks = (ochunk/512) * (nchunk/512) * odata * ndata / a;
 
                sysfs_free(sra);
                sra = sysfs_read(fd, 0,
                                 GET_COMPONENT|GET_DEVS|GET_OFFSET|GET_STATE|
                                 GET_CACHE);
+
                if (!sra) {
                        fprintf(stderr, Name ": %s: Cannot get array details from sysfs\n",
                                devname);
@@ -921,13 +1499,25 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        break;
                }
 
+               if (ndata == odata) {
+                       /* Make 'blocks' bigger for better throughput, but
+                        * not so big that we reject it below.
+                        * Try for 16 megabytes
+                        */
+                       while (blocks * 32 < sra->component_size &&
+                              blocks < 16*1024*2)
+                              blocks *= 2;
+               } else
+                       fprintf(stderr, Name ": Need to backup %luK of critical "
+                               "section..\n", blocks/2);
+
                if (blocks >= sra->component_size/2) {
                        fprintf(stderr, Name ": %s: Something wrong - reshape aborted\n",
                                devname);
                        rv = 1;
                        break;
                }
-               nrdisks = array.nr_disks + sra->array.spare_disks;
+               nrdisks = array.raid_disks + sra->array.spare_disks;
                /* Now we need to open all these devices so we can read/write.
                 */
                fdlist = malloc((1+nrdisks) * sizeof(int));
@@ -960,7 +1550,7 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                                char *dn = map_dev(sd->disk.major,
                                                   sd->disk.minor, 1);
                                fdlist[d] = dev_open(dn, O_RDWR);
-                               offsets[d] = (sra->component_size - blocks - 8)*512;
+                               offsets[d] = (sd->data_offset + sra->component_size - blocks - 8)*512;
                                if (fdlist[d]<0) {
                                        fprintf(stderr, Name ": %s: cannot open component %s\n",
                                                devname, dn?dn:"-unknown");
@@ -971,6 +1561,12 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        }
                }
                if (backup_file == NULL) {
+                       if (st->ss->external && !st->ss->manage_reshape) {
+                               fprintf(stderr, Name ": %s Grow operation not supported by %s metadata\n",
+                                       devname, st->ss->name);
+                               rv = 1;
+                               break;
+                       }
                        if (ndata <= odata) {
                                fprintf(stderr, Name ": %s: Cannot grow - need backup-file\n",
                                        devname);
@@ -1002,7 +1598,7 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                                break;
                        }
                        memset(buf, 0, 512);
-                       for (i=0; i < blocks + 1 ; i++) {
+                       for (i=0; i < (signed)blocks + 1 ; i++) {
                                if (write(fdlist[d], buf, 512) != 512) {
                                        fprintf(stderr, Name ": %s: cannot create backup file %s: %s\n",
                                                devname, backup_file, strerror(errno));
@@ -1019,12 +1615,22 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        d++;
                }
 
+               /* check that the operation is supported by the metadata */
+               if (reshape_super(st, -1, level, nlayout, nchunk, ndisks,
+                                 backup_file, devname, !quiet)) {
+                       rv = 1;
+                       break;
+               }
+
                /* lastly, check that the internal stripe cache is
                 * large enough, or it won't work.
                 */
                
                cache = (nchunk < ochunk) ? ochunk : nchunk;
                cache = cache * 4 / 4096;
+               if (cache < blocks / 8 / odisks + 16)
+                       /* Make it big enough to hold 'blocks' */
+                       cache = blocks / 8 / odisks + 16;
                if (sra->cache_size < cache)
                        sysfs_set_num(sra, NULL, "stripe_cache_size",
                                      cache+1);
@@ -1032,15 +1638,20 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                 * If only changing raid_disks, use ioctl, else use
                 * sysfs.
                 */
+               sync_metadata(st);
                if (ochunk == nchunk && olayout == nlayout) {
                        array.raid_disks = ndisks;
                        if (ioctl(fd, SET_ARRAY_INFO, &array) != 0) {
+                               int err = errno;
                                rv = 1;
                                fprintf(stderr, Name ": Cannot set device shape for %s: %s\n",
                                        devname, strerror(errno));
                                if (ndisks < odisks &&
                                    get_linux_version() < 2006030)
                                        fprintf(stderr, Name ": linux 2.6.30 or later required\n");
+                               if (err == EBUSY && 
+                                   (array.state & (1<<MD_SB_BITMAP_PRESENT)))
+                                       fprintf(stderr, "       Bitmap must be removed before shape can be changed\n");
 
                                break;
                        }
@@ -1048,17 +1659,24 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        /* set them all just in case some old 'new_*' value
                         * persists from some earlier problem
                         */
+                       int err = err; /* only used if rv==1, and always set if
+                                       * rv==1, so initialisation not needed,
+                                       * despite gcc warning
+                                       */
                        if (sysfs_set_num(sra, NULL, "chunk_size", nchunk) < 0)
-                               rv = 1;
-                       if (sysfs_set_num(sra, NULL, "layout", nlayout) < 0)
-                               rv = 1;
-                       if (sysfs_set_num(sra, NULL, "raid_disks", ndisks) < 0)
-                               rv = 1;
+                               rv = 1, err = errno;
+                       if (!rv && sysfs_set_num(sra, NULL, "layout", nlayout) < 0)
+                               rv = 1, err = errno;
+                       if (!rv && sysfs_set_num(sra, NULL, "raid_disks", ndisks) < 0)
+                               rv = 1, err = errno;
                        if (rv) {
                                fprintf(stderr, Name ": Cannot set device shape for %s\n",
                                        devname);
                                if (get_linux_version() < 2006030)
                                        fprintf(stderr, Name ": linux 2.6.30 or later required\n");
+                               if (err == EBUSY && 
+                                   (array.state & (1<<MD_SB_BITMAP_PRESENT)))
+                                       fprintf(stderr, "       Bitmap must be removed before shape can be changed\n");
                                break;
                        }
                }
@@ -1069,6 +1687,14 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                        break;
                }
 
+               if (st->ss->external) {
+                       /* metadata handler takes it from here */
+                       ping_manager(container);
+                       st->ss->manage_reshape(st, backup_file);
+                       frozen = 0;
+                       break;
+               }
+
                /* set up the backup-super-block.  This requires the
                 * uuid from the array.
                 */
@@ -1170,8 +1796,7 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
                if (c && sysfs_set_str(sra, NULL, "level", c) == 0)
                        fprintf(stderr, Name ": aborting level change\n");
        }
-       if (sra)
-               unfreeze_array(sra, frozen);
+       unfreeze(st, frozen);
        return rv;
 }
 
@@ -1199,13 +1824,14 @@ int Grow_reshape(char *devname, int fd, int quiet, char *backup_file,
  * 
  */
 
-int grow_backup(struct mdinfo *sra,
+/* FIXME return status is never checked */
+static int grow_backup(struct mdinfo *sra,
                unsigned long long offset, /* per device */
                unsigned long stripes, /* per device */
                int *sources, unsigned long long *offsets,
                int disks, int chunk, int level, int layout,
                int dests, int *destfd, unsigned long long *destoffsets,
-               int part,
+               int part, int *degraded,
                char *buf)
 {
        /* Backup 'blocks' sectors at 'offset' on each device of the array,
@@ -1217,18 +1843,46 @@ int grow_backup(struct mdinfo *sra,
        int odata = disks;
        int rv = 0;
        int i;
+       unsigned long long ll;
+       int new_degraded;
        //printf("offset %llu\n", offset);
        if (level >= 4)
                odata--;
        if (level == 6)
                odata--;
-       sysfs_set_num(sra, NULL, "suspend_hi", (offset + stripes * chunk/512) * odata);
+       sysfs_set_num(sra, NULL, "suspend_hi", (offset + stripes * (chunk/512)) * odata);
+       /* Check that array hasn't become degraded, else we might backup the wrong data */
+       sysfs_get_ll(sra, NULL, "degraded", &ll);
+       new_degraded = (int)ll;
+       if (new_degraded != *degraded) {
+               /* check each device to ensure it is still working */
+               struct mdinfo *sd;
+               for (sd = sra->devs ; sd ; sd = sd->next) {
+                       if (sd->disk.state & (1<<MD_DISK_FAULTY))
+                               continue;
+                       if (sd->disk.state & (1<<MD_DISK_SYNC)) {
+                               char sbuf[20];
+                               if (sysfs_get_str(sra, sd, "state", sbuf, 20) < 0 ||
+                                   strstr(sbuf, "faulty") ||
+                                   strstr(sbuf, "in_sync") == NULL) {
+                                       /* this device is dead */
+                                       sd->disk.state = (1<<MD_DISK_FAULTY);
+                                       if (sd->disk.raid_disk >= 0 &&
+                                           sources[sd->disk.raid_disk] >= 0) {
+                                               close(sources[sd->disk.raid_disk]);
+                                               sources[sd->disk.raid_disk] = -1;
+                                       }
+                               }
+                       }
+               }
+               *degraded = new_degraded;
+       }
        if (part) {
                bsb.arraystart2 = __cpu_to_le64(offset * odata);
-               bsb.length2 = __cpu_to_le64(stripes * chunk/512 * odata);
+               bsb.length2 = __cpu_to_le64(stripes * (chunk/512) * odata);
        } else {
                bsb.arraystart = __cpu_to_le64(offset * odata);
-               bsb.length = __cpu_to_le64(stripes * chunk/512 * odata);
+               bsb.length = __cpu_to_le64(stripes * (chunk/512) * odata);
        }
        if (part)
                bsb.magic[15] = '2';
@@ -1255,12 +1909,24 @@ int grow_backup(struct mdinfo *sra,
                        bsb.sb_csum2 = bsb_csum((char*)&bsb,
                                                ((char*)&bsb.sb_csum2)-((char*)&bsb));
 
-               lseek64(destfd[i], destoffsets[i] - 4096, 0);
-               write(destfd[i], &bsb, 512);
+               rv = -1;
+               if ((unsigned long long)lseek64(destfd[i], destoffsets[i] - 4096, 0)
+                   != destoffsets[i] - 4096)
+                       break;
+               if (write(destfd[i], &bsb, 512) != 512)
+                       break;
+               if (destoffsets[i] > 4096) {
+                       if ((unsigned long long)lseek64(destfd[i], destoffsets[i]+stripes*chunk*odata, 0) !=
+                           destoffsets[i]+stripes*chunk*odata)
+                               break;
+                       if (write(destfd[i], &bsb, 512) != 512)
+                               break;
+               }
                fsync(destfd[i]);
+               rv = 0;
        }
 
-       return 0;
+       return rv;
 }
 
 /* in 2.6.30, the value reported by sync_completed can be
@@ -1273,7 +1939,8 @@ int grow_backup(struct mdinfo *sra,
  * The various caller give appropriate values so that
  * every works.
  */
-int wait_backup(struct mdinfo *sra,
+/* FIXME return value is often ignored */
+static int wait_backup(struct mdinfo *sra,
                unsigned long long offset, /* per device */
                unsigned long long blocks, /* per device */
                unsigned long long blocks2, /* per device - hack */
@@ -1286,6 +1953,7 @@ int wait_backup(struct mdinfo *sra,
        int fd = sysfs_get_fd(sra, NULL, "sync_completed");
        unsigned long long completed;
        int i;
+       int rv;
 
        if (fd < 0)
                return -1;
@@ -1317,28 +1985,34 @@ int wait_backup(struct mdinfo *sra,
                bsb.length = __cpu_to_le64(0);
        }
        bsb.mtime = __cpu_to_le64(time(0));
+       rv = 0;
        for (i = 0; i < dests; i++) {
                bsb.devstart = __cpu_to_le64(destoffsets[i]/512);
                bsb.sb_csum = bsb_csum((char*)&bsb, ((char*)&bsb.sb_csum)-((char*)&bsb));
                if (memcmp(bsb.magic, "md_backup_data-2", 16) == 0)
                        bsb.sb_csum2 = bsb_csum((char*)&bsb,
                                                ((char*)&bsb.sb_csum2)-((char*)&bsb));
-               lseek64(destfd[i], destoffsets[i]-4096, 0);
-               write(destfd[i], &bsb, 512);
+               if ((unsigned long long)lseek64(destfd[i], destoffsets[i]-4096, 0) !=
+                   destoffsets[i]-4096)
+                       rv = -1;
+               if (rv == 0 && 
+                   write(destfd[i], &bsb, 512) != 512)
+                       rv = -1;
                fsync(destfd[i]);
        }
-       return 0;
+       return rv;
 }
 
 static void fail(char *msg)
 {
-       write(2, msg, strlen(msg));
-       write(2, "\n", 1);
-       exit(1);
+       int rv;
+       rv = (write(2, msg, strlen(msg)) != (int)strlen(msg));
+       rv |= (write(2, "\n", 1) != 1);
+       exit(rv ? 1 : 2);
 }
 
 static char *abuf, *bbuf;
-static int abuflen;
+static unsigned long long abuflen;
 static void validate(int afd, int bfd, unsigned long long offset)
 {
        /* check that the data in the backup against the array.
@@ -1370,27 +2044,33 @@ static void validate(int afd, int bfd, unsigned long long offset)
                        free(abuf);
                        free(bbuf);
                        abuflen = len;
-                       posix_memalign((void**)&abuf, 4096, abuflen);
-                       posix_memalign((void**)&bbuf, 4096, abuflen);
+                       if (posix_memalign((void**)&abuf, 4096, abuflen) ||
+                           posix_memalign((void**)&bbuf, 4096, abuflen)) {
+                               abuflen = 0;
+                               /* just stop validating on mem-alloc failure */
+                               return;
+                       }
                }
 
                lseek64(bfd, offset, 0);
-               if (read(bfd, bbuf, len) != len) {
-                       printf("len %llu\n", len);
+               if ((unsigned long long)read(bfd, bbuf, len) != len) {
+                       //printf("len %llu\n", len);
                        fail("read first backup failed");
                }
                lseek64(afd, __le64_to_cpu(bsb2.arraystart)*512, 0);
-               if (read(afd, abuf, len) != len)
+               if ((unsigned long long)read(afd, abuf, len) != len)
                        fail("read first from array failed");
                if (memcmp(bbuf, abuf, len) != 0) {
+                       #if 0
                        int i;
                        printf("offset=%llu len=%llu\n",
-                              __le64_to_cpu(bsb2.arraystart)*512, len);
+                              (unsigned long long)__le64_to_cpu(bsb2.arraystart)*512, len);
                        for (i=0; i<len; i++)
                                if (bbuf[i] != abuf[i]) {
                                        printf("first diff byte %d\n", i);
                                        break;
                                }
+                       #endif
                        fail("data1 compare failed");
                }
        }
@@ -1406,10 +2086,10 @@ static void validate(int afd, int bfd, unsigned long long offset)
                }
 
                lseek64(bfd, offset+__le64_to_cpu(bsb2.devstart2)*512, 0);
-               if (read(bfd, bbuf, len) != len)
+               if ((unsigned long long)read(bfd, bbuf, len) != len)
                        fail("read second backup failed");
                lseek64(afd, __le64_to_cpu(bsb2.arraystart2)*512, 0);
-               if (read(afd, abuf, len) != len)
+               if ((unsigned long long)read(afd, abuf, len) != len)
                        fail("read second from array failed");
                if (memcmp(bbuf, abuf, len) != 0)
                        fail("data2 compare failed");
@@ -1422,19 +2102,22 @@ static int child_grow(int afd, struct mdinfo *sra, unsigned long stripes,
                      int dests, int *destfd, unsigned long long *destoffsets)
 {
        char *buf;
+       int degraded = 0;
 
-       posix_memalign((void**)&buf, 4096, disks * chunk);
+       if (posix_memalign((void**)&buf, 4096, disks * chunk))
+               /* Don't start the 'reshape' */
+               return 0;
        sysfs_set_num(sra, NULL, "suspend_hi", 0);
        sysfs_set_num(sra, NULL, "suspend_lo", 0);
        grow_backup(sra, 0, stripes,
                    fds, offsets, disks, chunk, level, layout,
                    dests, destfd, destoffsets,
-                   0, buf);
+                   0, &degraded, buf);
        validate(afd, destfd[0], destoffsets[0]);
-       wait_backup(sra, 0, stripes * chunk / 512, stripes * chunk / 512,
+       wait_backup(sra, 0, stripes * (chunk / 512), stripes * (chunk / 512),
                    dests, destfd, destoffsets,
                    0);
-       sysfs_set_num(sra, NULL, "suspend_lo", (stripes * chunk/512) * data);
+       sysfs_set_num(sra, NULL, "suspend_lo", (stripes * (chunk/512)) * data);
        free(buf);
        /* FIXME this should probably be numeric */
        sysfs_set_str(sra, NULL, "sync_max", "max");
@@ -1449,14 +2132,16 @@ static int child_shrink(int afd, struct mdinfo *sra, unsigned long stripes,
        char *buf;
        unsigned long long start;
        int rv;
+       int degraded = 0;
 
-       posix_memalign((void**)&buf, 4096, disks * chunk);
-       start = sra->component_size - stripes * chunk/512;
+       if (posix_memalign((void**)&buf, 4096, disks * chunk))
+               return 0;
+       start = sra->component_size - stripes * (chunk/512);
        sysfs_set_num(sra, NULL, "sync_max", start);
        sysfs_set_str(sra, NULL, "sync_action", "reshape");
        sysfs_set_num(sra, NULL, "suspend_lo", 0);
        sysfs_set_num(sra, NULL, "suspend_hi", 0);
-       rv = wait_backup(sra, 0, start - stripes * chunk/512, stripes * chunk/512,
+       rv = wait_backup(sra, 0, start - stripes * (chunk/512), stripes * (chunk/512),
                         dests, destfd, destoffsets, 0);
        if (rv < 0)
                return 0;
@@ -1464,11 +2149,11 @@ static int child_shrink(int afd, struct mdinfo *sra, unsigned long stripes,
                    fds, offsets,
                    disks, chunk, level, layout,
                    dests, destfd, destoffsets,
-                   0, buf);
+                   0, &degraded, buf);
        validate(afd, destfd[0], destoffsets[0]);
-       wait_backup(sra, start, stripes*chunk/512, 0,
+       wait_backup(sra, start, stripes*(chunk/512), 0,
                    dests, destfd, destoffsets, 0);
-       sysfs_set_num(sra, NULL, "suspend_lo", (stripes * chunk/512) * data);
+       sysfs_set_num(sra, NULL, "suspend_lo", (stripes * (chunk/512)) * data);
        free(buf);
        /* FIXME this should probably be numeric */
        sysfs_set_str(sra, NULL, "sync_max", "max");
@@ -1486,9 +2171,11 @@ static int child_same_size(int afd, struct mdinfo *sra, unsigned long stripes,
        int part;
        char *buf;
        unsigned long long speed;
+       int degraded = 0;
 
 
-       posix_memalign((void**)&buf, 4096, disks * chunk);
+       if (posix_memalign((void**)&buf, 4096, disks * chunk))
+               return 0;
 
        sysfs_set_num(sra, NULL, "suspend_lo", 0);
        sysfs_set_num(sra, NULL, "suspend_hi", 0);
@@ -1500,44 +2187,44 @@ static int child_same_size(int afd, struct mdinfo *sra, unsigned long stripes,
                    fds, offsets,
                    disks, chunk, level, layout,
                    dests, destfd, destoffsets,
-                   0, buf);
-       grow_backup(sra, (start + stripes) * chunk/512, stripes,
+                   0, &degraded, buf);
+       grow_backup(sra, (start + stripes) * (chunk/512), stripes,
                    fds, offsets,
                    disks, chunk, level, layout,
                    dests, destfd, destoffsets,
-                   1, buf);
+                   1, &degraded, buf);
        validate(afd, destfd[0], destoffsets[0]);
        part = 0;
        start += stripes * 2; /* where to read next */
        size = sra->component_size / (chunk/512);
        while (start < size) {
-               if (wait_backup(sra, (start-stripes*2)*chunk/512,
-                               stripes*chunk/512, 0,
+               if (wait_backup(sra, (start-stripes*2)*(chunk/512),
+                               stripes*(chunk/512), 0,
                                dests, destfd, destoffsets,
                                part) < 0)
                        return 0;
-               sysfs_set_num(sra, NULL, "suspend_lo", start*chunk/512 * data);
+               sysfs_set_num(sra, NULL, "suspend_lo", start*(chunk/512) * data);
                if (start + stripes > size)
                        tailstripes = (size - start);
 
-               grow_backup(sra, start*chunk/512, tailstripes,
+               grow_backup(sra, start*(chunk/512), tailstripes,
                            fds, offsets,
                            disks, chunk, level, layout,
                            dests, destfd, destoffsets,
-                           part, buf);
+                           part, &degraded, buf);
                start += stripes;
                part = 1 - part;
                validate(afd, destfd[0], destoffsets[0]);
        }
-       if (wait_backup(sra, (start-stripes*2) * chunk/512, stripes * chunk/512, 0,
+       if (wait_backup(sra, (start-stripes*2) * (chunk/512), stripes * (chunk/512), 0,
                        dests, destfd, destoffsets,
                        part) < 0)
                return 0;
-       sysfs_set_num(sra, NULL, "suspend_lo", ((start-stripes)*chunk/512) * data);
-       wait_backup(sra, (start-stripes) * chunk/512, tailstripes * chunk/512, 0,
+       sysfs_set_num(sra, NULL, "suspend_lo", ((start-stripes)*(chunk/512)) * data);
+       wait_backup(sra, (start-stripes) * (chunk/512), tailstripes * (chunk/512), 0,
                    dests, destfd, destoffsets,
                    1-part);
-       sysfs_set_num(sra, NULL, "suspend_lo", (size*chunk/512) * data);
+       sysfs_set_num(sra, NULL, "suspend_lo", (size*(chunk/512)) * data);
        sysfs_set_num(sra, NULL, "sync_speed_min", speed);
        free(buf);
        return 1;
@@ -1574,7 +2261,6 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                old_disks = cnt;
        for (i=old_disks-(backup_file?1:0); i<cnt; i++) {
                struct mdinfo dinfo;
-               char buf[4096];
                int fd;
                int bsbsize;
                char *devname, namebuf[20];
@@ -1601,7 +2287,7 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                        if (st->ss->load_super(st, fd, NULL))
                                continue;
 
-                       st->ss->getinfo_super(st, &dinfo);
+                       st->ss->getinfo_super(st, &dinfo, NULL);
                        st->ss->free_super(st);
 
                        if (lseek64(fd,
@@ -1641,11 +2327,23 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                        continue; /* Wrong uuid */
                }
 
-               if (info->array.utime > __le64_to_cpu(bsb.mtime) + 10*60 ||
-                   info->array.utime < __le64_to_cpu(bsb.mtime) - 10*60) {
-                       if (verbose)
-                               fprintf(stderr, Name ": too-old timestamp on backup-metadata on %s\n", devname);
-                       continue; /* time stamp is too bad */
+               /* array utime and backup-mtime should be updated at much the same time, but it seems that
+                * sometimes they aren't... So allow considerable flexability in matching, and allow
+                * this test to be overridden by an environment variable.
+                */
+               if (info->array.utime > (int)__le64_to_cpu(bsb.mtime) + 2*60*60 ||
+                   info->array.utime < (int)__le64_to_cpu(bsb.mtime) - 10*60) {
+                       if (check_env("MDADM_GROW_ALLOW_OLD")) {
+                               fprintf(stderr, Name ": accepting backup with timestamp %lu "
+                                       "for array with timestamp %lu\n",
+                                       (unsigned long)__le64_to_cpu(bsb.mtime),
+                                       (unsigned long)info->array.utime);
+                       } else {
+                               if (verbose)
+                                       fprintf(stderr, Name ": too-old timestamp on "
+                                               "backup-metadata on %s\n", devname);
+                               continue; /* time stamp is too bad */
+                       }
                }
 
                if (bsb.magic[15] == '1') {
@@ -1690,13 +2388,13 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                }
                /* There should be a duplicate backup superblock 4k before here */
                if (lseek64(fd, -4096, 1) < 0 ||
-                   read(fd, buf, 4096) != 4096)
+                   read(fd, &bsb2, sizeof(bsb2)) != sizeof(bsb2))
                        goto second_fail; /* Cannot find leading superblock */
                if (bsb.magic[15] == '1')
                        bsbsize = offsetof(struct mdp_backup_super, pad1);
                else
                        bsbsize = offsetof(struct mdp_backup_super, pad);
-               if (memcmp(buf, &bsb, bsbsize) != 0)
+               if (memcmp(&bsb2, &bsb, bsbsize) != 0)
                        goto second_fail; /* Cannot find leading superblock */
 
                /* Now need the data offsets for all devices. */
@@ -1707,9 +2405,9 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                        if (st->ss->load_super(st, fdlist[j], NULL))
                                /* FIXME should be this be an error */
                                continue;
-                       st->ss->getinfo_super(st, &dinfo);
+                       st->ss->getinfo_super(st, &dinfo, NULL);
                        st->ss->free_super(st);
-                       offsets[j] = dinfo.data_offset;
+                       offsets[j] = dinfo.data_offset * 512;
                }
                printf(Name ": restoring critical section\n");
 
@@ -1719,7 +2417,7 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                                    info->new_level,
                                    info->new_layout,
                                    fd, __le64_to_cpu(bsb.devstart)*512,
-                                   __le64_to_cpu(bsb.arraystart),
+                                   __le64_to_cpu(bsb.arraystart)*512,
                                    __le64_to_cpu(bsb.length)*512)) {
                        /* didn't succeed, so giveup */
                        if (verbose)
@@ -1736,7 +2434,7 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                                    info->new_layout,
                                    fd, __le64_to_cpu(bsb.devstart)*512 +
                                    __le64_to_cpu(bsb.devstart2)*512,
-                                   __le64_to_cpu(bsb.arraystart2),
+                                   __le64_to_cpu(bsb.arraystart2)*512,
                                    __le64_to_cpu(bsb.length2)*512)) {
                        /* didn't succeed, so giveup */
                        if (verbose)
@@ -1769,7 +2467,7 @@ int Grow_restart(struct supertype *st, struct mdinfo *info, int *fdlist, int cnt
                        if (fdlist[j] < 0) continue;
                        if (st->ss->load_super(st, fdlist[j], NULL))
                                continue;
-                       st->ss->getinfo_super(st, &dinfo);
+                       st->ss->getinfo_super(st, &dinfo, NULL);
                        dinfo.reshape_progress = info->reshape_progress;
                        st->ss->update_super(st, &dinfo,
                                             "_reshape_progress",
@@ -1843,6 +2541,7 @@ int Grow_continue(int mdfd, struct supertype *st, struct mdinfo *info,
        int d;
        struct mdinfo *sra, *sd;
        int rv;
+       unsigned long cache;
        int done = 0;
 
        err = sysfs_set_str(info, NULL, "array_state", "readonly");
@@ -1852,7 +2551,13 @@ int Grow_continue(int mdfd, struct supertype *st, struct mdinfo *info,
        /* make sure reshape doesn't progress until we are ready */
        sysfs_set_str(info, NULL, "sync_max", "0");
        sysfs_set_str(info, NULL, "array_state", "active"); /* FIXME or clean */
-       
+
+       sra = sysfs_read(-1, devname2devnum(info->sys_name),
+                        GET_COMPONENT|GET_DEVS|GET_OFFSET|GET_STATE|
+                        GET_CACHE);
+       if (!sra)
+               return 1;
+
        /* ndisks is not growing, so raid_disks is old and +delta is new */
        odisks = info->array.raid_disks;
        ndisks = odisks + info->delta_disks;
@@ -1865,9 +2570,8 @@ int Grow_continue(int mdfd, struct supertype *st, struct mdinfo *info,
        ochunk = info->array.chunk_size;
        nchunk = info->new_chunk;
 
-
-       a = ochunk/512 * odata;
-       b = nchunk/512 * ndata;
+       a = (ochunk/512) * odata;
+       b = (nchunk/512) * ndata;
        /* Find GCD */
        while (a != b) {
                if (a < b)
@@ -1876,12 +2580,25 @@ int Grow_continue(int mdfd, struct supertype *st, struct mdinfo *info,
                        a -= b;
        }
        /* LCM == product / GCD */
-       blocks = ochunk/512 * nchunk/512 * odata * ndata / a;
+       blocks = (ochunk/512) * (nchunk/512) * odata * ndata / a;
 
        if (ndata == odata)
-               blocks *= 16;
+               while (blocks * 32 < sra->component_size &&
+                      blocks < 16*1024*2)
+                       blocks *= 2;
        stripes = blocks / (info->array.chunk_size/512) / odata;
 
+       /* check that the internal stripe cache is
+        * large enough, or it won't work.
+        */
+       cache = (nchunk < ochunk) ? ochunk : nchunk;
+       cache = cache * 4 / 4096;
+       if (cache < blocks / 8 / odisks + 16)
+               /* Make it big enough to hold 'blocks' */
+               cache = blocks / 8 / odisks + 16;
+       if (sra->cache_size < cache)
+               sysfs_set_num(sra, NULL, "stripe_cache_size",
+                             cache+1);
 
        memset(&bsb, 0, 512);
        memcpy(bsb.magic, "md_backup_data-1", 16);
@@ -1897,10 +2614,6 @@ int Grow_continue(int mdfd, struct supertype *st, struct mdinfo *info,
        for (d=0; d<odisks; d++)
                fds[d] = -1;
 
-       sra = sysfs_read(-1, devname2devnum(info->sys_name),
-                        GET_COMPONENT|GET_DEVS|GET_OFFSET|GET_STATE|
-                        GET_CACHE);
-
        for (sd = sra->devs; sd; sd = sd->next) {
                if (sd->disk.state & (1<<MD_DISK_FAULTY))
                        continue;