Remove getinfo_super_n and do some other cleaning up.
[thirdparty/mdadm.git] / Assemble.c
1 /*
2  * mdadm - manage Linux "md" devices aka RAID arrays.
3  *
4  * Copyright (C) 2001-2006 Neil Brown <neilb@suse.de>
5  *
6  *
7  *    This program is free software; you can redistribute it and/or modify
8  *    it under the terms of the GNU General Public License as published by
9  *    the Free Software Foundation; either version 2 of the License, or
10  *    (at your option) any later version.
11  *
12  *    This program is distributed in the hope that it will be useful,
13  *    but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *    GNU General Public License for more details.
16  *
17  *    You should have received a copy of the GNU General Public License
18  *    along with this program; if not, write to the Free Software
19  *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20  *
21  *    Author: Neil Brown
22  *    Email: <neilb@cse.unsw.edu.au>
23  *    Paper: Neil Brown
24  *           School of Computer Science and Engineering
25  *           The University of New South Wales
26  *           Sydney, 2052
27  *           Australia
28  */
29
30 #include        "mdadm.h"
31 #include        <ctype.h>
32
33 static int name_matches(char *found, char *required, char *homehost)
34 {
35         /* See if the name found matches the required name, possibly
36          * prefixed with 'homehost'
37          */
38         char fnd[33];
39
40         strncpy(fnd, found, 32);
41         fnd[32] = 0;
42         if (strcmp(found, required)==0)
43                 return 1;
44         if (homehost) {
45                 int l = strlen(homehost);
46                 if (l < 32 && fnd[l] == ':' &&
47                     strcmp(fnd+l+1, required)==0)
48                         return 1;
49         }
50         return 0;
51 }
52
53 int Assemble(struct supertype *st, char *mddev, int mdfd,
54              mddev_ident_t ident,
55              mddev_dev_t devlist, char *backup_file,
56              int readonly, int runstop,
57              char *update, char *homehost,
58              int verbose, int force)
59 {
60         /*
61          * The task of Assemble is to find a collection of
62          * devices that should (according to their superblocks)
63          * form an array, and to give this collection to the MD driver.
64          * In Linux-2.4 and later, this involves submitting a
65          * SET_ARRAY_INFO ioctl with no arg - to prepare
66          * the array - and then submit a number of
67          * ADD_NEW_DISK ioctls to add disks into
68          * the array.  Finally RUN_ARRAY might
69          * be submitted to start the array.
70          *
71          * Much of the work of Assemble is in finding and/or
72          * checking the disks to make sure they look right.
73          *
74          * If mddev is not set, then scan must be set and we
75          *  read through the config file for dev+uuid mapping
76          *  We recurse, setting mddev, for each device that
77          *    - isn't running
78          *    - has a valid uuid (or any uuid if !uuidset)
79          *
80          * If mddev is set, we try to determine state of md.
81          *   check version - must be at least 0.90.0
82          *   check kernel version.  must be at least 2.4.
83          *    If not, we can possibly fall back on START_ARRAY
84          *   Try to GET_ARRAY_INFO.
85          *     If possible, give up
86          *     If not, try to STOP_ARRAY just to make sure
87          *
88          * If !uuidset and scan, look in conf-file for uuid
89          *       If not found, give up
90          * If !devlist and scan and uuidset, get list of devs from conf-file
91          *
92          * For each device:
93          *   Check superblock - discard if bad
94          *   Check uuid (set if we don't have one) - discard if no match
95          *   Check superblock similarity if we have a superblock - discard if different
96          *   Record events, devicenum
97          * This should give us a list of devices for the array
98          * We should collect the most recent event number
99          *
100          * Count disks with recent enough event count
101          * While force && !enough disks
102          *    Choose newest rejected disks, update event count
103          *     mark clean and rewrite superblock
104          * If recent kernel:
105          *    SET_ARRAY_INFO
106          *    foreach device with recent events : ADD_NEW_DISK
107          *    if runstop == 1 || "enough" disks and runstop==0 -> RUN_ARRAY
108          * If old kernel:
109          *    Check the device numbers in superblock are right
110          *    update superblock if any changes
111          *    START_ARRAY
112          *
113          */
114         int clean = 0;
115         int must_close = 0;
116         int old_linux = 0;
117         int vers = 0; /* Keep gcc quite - it really is initialised */
118         struct {
119                 char *devname;
120                 int uptodate; /* set once we decide that this device is as
121                                * recent as everything else in the array.
122                                */
123                 struct mdinfo i;
124         } *devices;
125         int *best = NULL; /* indexed by raid_disk */
126         unsigned int bestcnt = 0;
127         int devcnt = 0;
128         unsigned int okcnt, sparecnt;
129         unsigned int req_cnt;
130         unsigned int i;
131         int most_recent = 0;
132         int chosen_drive;
133         int change = 0;
134         int inargv = 0;
135         int bitmap_done;
136         int start_partial_ok = (runstop >= 0) && (force || devlist==NULL || mdfd < 0);
137         unsigned int num_devs;
138         mddev_dev_t tmpdev;
139         struct mdinfo info;
140         char *avail;
141         int nextspare = 0;
142
143         if (get_linux_version() < 2004000)
144                 old_linux = 1;
145
146         if (mdfd >= 0) {
147                 vers = md_get_version(mdfd);
148                 if (vers <= 0) {
149                         fprintf(stderr, Name ": %s appears not to be an md device.\n", mddev);
150                         return 1;
151                 }
152                 if (vers < 9000) {
153                         fprintf(stderr, Name ": Assemble requires driver version 0.90.0 or later.\n"
154                                 "    Upgrade your kernel or try --build\n");
155                         return 1;
156                 }
157
158                 if (ioctl(mdfd, GET_ARRAY_INFO, &info.array)>=0) {
159                         fprintf(stderr, Name ": device %s already active - cannot assemble it\n",
160                                 mddev);
161                         return 1;
162                 }
163                 ioctl(mdfd, STOP_ARRAY, NULL); /* just incase it was started but has no content */
164         }
165         /*
166          * If any subdevs are listed, then any that don't
167          * match ident are discarded.  Remainder must all match and
168          * become the array.
169          * If no subdevs, then we scan all devices in the config file, but
170          * there must be something in the identity
171          */
172
173         if (!devlist &&
174             ident->uuid_set == 0 &&
175             ident->super_minor < 0 &&
176             ident->devices == NULL) {
177                 fprintf(stderr, Name ": No identity information available for %s - cannot assemble.\n",
178                         mddev ? mddev : "further assembly");
179                 return 1;
180         }
181         if (devlist == NULL)
182                 devlist = conf_get_devs();
183         else if (mdfd >= 0)
184                 inargv = 1;
185
186  try_again:
187
188         tmpdev = devlist; num_devs = 0;
189         while (tmpdev) {
190                 if (tmpdev->used)
191                         tmpdev->used = 2;
192                 else
193                         num_devs++;
194                 tmpdev = tmpdev->next;
195         }
196         devices = malloc(num_devs * sizeof(*devices));
197
198         if (!st && ident->st) st = ident->st;
199
200         if (verbose>0)
201             fprintf(stderr, Name ": looking for devices for %s\n",
202                     mddev ? mddev : "further assembly");
203
204         /* first walk the list of devices to find a consistent set
205          * that match the criterea, if that is possible.
206          * We flag the one we like with 'used'.
207          */
208         for (tmpdev = devlist;
209              tmpdev;
210              tmpdev = tmpdev->next) {
211                 char *devname = tmpdev->devname;
212                 int dfd;
213                 struct stat stb;
214                 struct supertype *tst = dup_super(st);
215
216                 if (tmpdev->used > 1) continue;
217
218                 if (ident->devices &&
219                     !match_oneof(ident->devices, devname)) {
220                         if ((inargv && verbose>=0) || verbose > 0)
221                                 fprintf(stderr, Name ": %s is not one of %s\n", devname, ident->devices);
222                         continue;
223                 }
224
225                 dfd = dev_open(devname, O_RDONLY|O_EXCL);
226                 if (dfd < 0) {
227                         if ((inargv && verbose >= 0) || verbose > 0)
228                                 fprintf(stderr, Name ": cannot open device %s: %s\n",
229                                         devname, strerror(errno));
230                         tmpdev->used = 2;
231                 } else if (fstat(dfd, &stb)< 0) {
232                         /* Impossible! */
233                         fprintf(stderr, Name ": fstat failed for %s: %s\n",
234                                 devname, strerror(errno));
235                         tmpdev->used = 2;
236                 } else if ((stb.st_mode & S_IFMT) != S_IFBLK) {
237                         fprintf(stderr, Name ": %s is not a block device.\n",
238                                 devname);
239                         tmpdev->used = 2;
240                 } else if (!tst && (tst = guess_super(dfd)) == NULL) {
241                         if ((inargv && verbose >= 0) || verbose > 0)
242                                 fprintf(stderr, Name ": no recogniseable superblock on %s\n",
243                                         devname);
244                         tmpdev->used = 2;
245                 } else if (tst->ss->load_super(tst,dfd, NULL)) {
246                         if ((inargv && verbose >= 0) || verbose > 0)
247                                 fprintf( stderr, Name ": no RAID superblock on %s\n",
248                                          devname);
249                 } else {
250                         tst->ss->getinfo_super(tst, &info);
251                 }
252                 if (dfd >= 0) close(dfd);
253
254                 if (ident->uuid_set && (!update || strcmp(update, "uuid")!= 0) &&
255                     (!tst || !tst->sb ||
256                      same_uuid(info.uuid, ident->uuid, tst->ss->swapuuid)==0)) {
257                         if ((inargv && verbose >= 0) || verbose > 0)
258                                 fprintf(stderr, Name ": %s has wrong uuid.\n",
259                                         devname);
260                         goto loop;
261                 }
262                 if (ident->name[0] && (!update || strcmp(update, "name")!= 0) &&
263                     (!tst || !tst->sb ||
264                      name_matches(info.name, ident->name, homehost)==0)) {
265                         if ((inargv && verbose >= 0) || verbose > 0)
266                                 fprintf(stderr, Name ": %s has wrong name.\n",
267                                         devname);
268                         goto loop;
269                 }
270                 if (ident->super_minor != UnSet &&
271                     (!tst || !tst->sb ||
272                      ident->super_minor != info.array.md_minor)) {
273                         if ((inargv && verbose >= 0) || verbose > 0)
274                                 fprintf(stderr, Name ": %s has wrong super-minor.\n",
275                                         devname);
276                         goto loop;
277                 }
278                 if (ident->level != UnSet &&
279                     (!tst || !tst->sb ||
280                      ident->level != info.array.level)) {
281                         if ((inargv && verbose >= 0) || verbose > 0)
282                                 fprintf(stderr, Name ": %s has wrong raid level.\n",
283                                         devname);
284                         goto loop;
285                 }
286                 if (ident->raid_disks != UnSet &&
287                     (!tst || !tst->sb ||
288                      ident->raid_disks!= info.array.raid_disks)) {
289                         if ((inargv && verbose >= 0) || verbose > 0)
290                                 fprintf(stderr, Name ": %s requires wrong number of drives.\n",
291                                         devname);
292                         goto loop;
293                 }
294                 if (mdfd < 0) {
295                         if (tst == NULL || tst->sb == NULL)
296                                 continue;
297                         if (update == NULL &&
298                             tst->ss->match_home(tst, homehost)==0) {
299                                 if ((inargv && verbose >= 0) || verbose > 0)
300                                         fprintf(stderr, Name ": %s is not built for host %s.\n",
301                                                 devname, homehost);
302                                 /* Auto-assemble, and this is not a usable host */
303                                 /* if update != NULL, we are updating the host
304                                  * name... */
305                                 goto loop;
306                         }
307                 }
308                 /* If we are this far, then we are nearly commited to this device.
309                  * If the super_block doesn't exist, or doesn't match others,
310                  * then we probably cannot continue
311                  * However if one of the arrays is for the homehost, and
312                  * the other isn't that can disambiguate.
313                  */
314
315                 if (!tst || !tst->sb) {
316                         fprintf(stderr, Name ": %s has no superblock - assembly aborted\n",
317                                 devname);
318                         if (st)
319                                 st->ss->free_super(st);
320                         return 1;
321                 }
322
323                 if (st == NULL)
324                         st = dup_super(tst);
325                 if (st->minor_version == -1)
326                         st->minor_version = tst->minor_version;
327                 if (st->ss != tst->ss ||
328                     st->minor_version != tst->minor_version ||
329                     st->ss->compare_super(st, tst) != 0) {
330                         /* Some mismatch. If exactly one array matches this host,
331                          * we can resolve on that one.
332                          * Or, if we are auto assembling, we just ignore the second
333                          * for now.
334                          */
335                         if (mdfd < 0)
336                                 goto loop;
337                         if (homehost) {
338                                 int first = st->ss->match_home(st, homehost);
339                                 int last = tst->ss->match_home(tst, homehost);
340                                 if (first+last == 1) {
341                                         /* We can do something */
342                                         if (first) {/* just ignore this one */
343                                                 if ((inargv && verbose >= 0) || verbose > 0)
344                                                         fprintf(stderr, Name ": %s misses out due to wrong homehost\n",
345                                                                 devname);
346                                                 goto loop;
347                                         } else { /* reject all those sofar */
348                                                 mddev_dev_t td;
349                                                 if ((inargv && verbose >= 0) || verbose > 0)
350                                                         fprintf(stderr, Name ": %s overrides previous devices due to good homehost\n",
351                                                                 devname);
352                                                 for (td=devlist; td != tmpdev; td=td->next)
353                                                         if (td->used == 1)
354                                                                 td->used = 0;
355                                                 tmpdev->used = 1;
356                                                 goto loop;
357                                         }
358                                 }
359                         }
360                         fprintf(stderr, Name ": superblock on %s doesn't match others - assembly aborted\n",
361                                 devname);
362                         tst->ss->free_super(tst);
363                         st->ss->free_super(st);
364                         return 1;
365                 }
366
367                 tmpdev->used = 1;
368
369         loop:
370                 if (tst)
371                         tst->ss->free_super(tst);
372         }
373
374         if (mdfd < 0) {
375                 /* So... it is up to me to open the device.
376                  * We create a name '/dev/md/XXX' based on the info in the
377                  * superblock, and call open_mddev on that
378                  */
379                 mdu_array_info_t inf;
380                 char *c;
381                 if (!st || !st->sb) {
382                         return 2;
383                 }
384                 st->ss->getinfo_super(st, &info);
385                 c = strchr(info.name, ':');
386                 if (c) c++; else c= info.name;
387                 if (isdigit(*c) && ((ident->autof & 7)==4 || (ident->autof&7)==6))
388                         /* /dev/md/d0 style for partitionable */
389                         asprintf(&mddev, "/dev/md/d%s", c);
390                 else
391                         asprintf(&mddev, "/dev/md/%s", c);
392                 mdfd = open_mddev(mddev, ident->autof);
393                 if (mdfd < 0) {
394                         st->ss->free_super(st);
395                         free(devices);
396                         goto try_again;
397                 }
398                 vers = md_get_version(mdfd);
399                 if (ioctl(mdfd, GET_ARRAY_INFO, &inf)==0) {
400                         for (tmpdev = devlist ;
401                              tmpdev && tmpdev->used != 1;
402                              tmpdev = tmpdev->next)
403                                 ;
404                         fprintf(stderr, Name ": %s already active, cannot restart it!\n", mddev);
405                         if (tmpdev)
406                                 fprintf(stderr, Name ":   %s needed for %s...\n",
407                                         mddev, tmpdev->devname);
408                         close(mdfd);
409                         mdfd = -1;
410                         st->ss->free_super(st);
411                         free(devices);
412                         goto try_again;
413                 }
414                 must_close = 1;
415         }
416
417         /* Ok, no bad inconsistancy, we can try updating etc */
418         bitmap_done = 0;
419         for (tmpdev = devlist; tmpdev; tmpdev=tmpdev->next) if (tmpdev->used == 1) {
420                 char *devname = tmpdev->devname;
421                 struct stat stb;
422                 /* looks like a good enough match to update the super block if needed */
423 #ifndef MDASSEMBLE
424                 if (update) {
425                         int dfd;
426                         /* prepare useful information in info structures */
427                         struct stat stb2;
428                         struct supertype *tst;
429                         fstat(mdfd, &stb2);
430
431                         if (strcmp(update, "uuid")==0 &&
432                             !ident->uuid_set) {
433                                 int rfd;
434                                 if ((rfd = open("/dev/urandom", O_RDONLY)) < 0 ||
435                                     read(rfd, ident->uuid, 16) != 16) {
436                                         *(__u32*)(ident->uuid) = random();
437                                         *(__u32*)(ident->uuid+1) = random();
438                                         *(__u32*)(ident->uuid+2) = random();
439                                         *(__u32*)(ident->uuid+3) = random();
440                                 }
441                                 if (rfd >= 0) close(rfd);
442                         }
443                         dfd = dev_open(devname, O_RDWR|O_EXCL);
444
445                         remove_partitions(dfd);
446
447                         tst = dup_super(st);
448                         tst->ss->load_super(tst, dfd, NULL);
449                         tst->ss->getinfo_super(tst, &info);
450
451                         memcpy(info.uuid, ident->uuid, 16);
452                         strcpy(info.name, ident->name);
453                         info.array.md_minor = minor(stb2.st_rdev);
454
455                         tst->ss->update_super(tst, &info, update,
456                                               devname, verbose,
457                                               ident->uuid_set, homehost);
458                         if (strcmp(update, "uuid")==0 &&
459                             !ident->uuid_set) {
460                                 ident->uuid_set = 1;
461                                 memcpy(ident->uuid, info.uuid, 16);
462                         }
463                         if (dfd < 0)
464                                 fprintf(stderr, Name ": Cannot open %s for superblock update\n",
465                                         devname);
466                         else if (tst->ss->store_super(tst, dfd))
467                                 fprintf(stderr, Name ": Could not re-write superblock on %s.\n",
468                                         devname);
469                         if (dfd >= 0)
470                                 close(dfd);
471
472                         if (strcmp(update, "uuid")==0 &&
473                             ident->bitmap_fd >= 0 && !bitmap_done) {
474                                 if (bitmap_update_uuid(ident->bitmap_fd,
475                                                        info.uuid,
476                                                        tst->ss->swapuuid) != 0)
477                                         fprintf(stderr, Name ": Could not update uuid on external bitmap.\n");
478                                 else
479                                         bitmap_done = 1;
480                         }
481                         tst->ss->free_super(tst);
482                 } else
483 #endif
484                 {
485                         struct supertype *tst = dup_super(st);
486                         int dfd;
487                         dfd = dev_open(devname, O_RDWR|O_EXCL);
488
489                         remove_partitions(dfd);
490
491                         tst->ss->load_super(tst, dfd, NULL);
492                         tst->ss->getinfo_super(tst, &info);
493                         tst->ss->free_super(tst);
494                         close(dfd);
495                 }
496
497                 stat(devname, &stb);
498
499                 if (verbose > 0)
500                         fprintf(stderr, Name ": %s is identified as a member of %s, slot %d.\n",
501                                 devname, mddev, info.disk.raid_disk);
502                 devices[devcnt].devname = devname;
503                 devices[devcnt].uptodate = 0;
504                 devices[devcnt].i = info;
505                 devices[devcnt].i.disk.major = major(stb.st_rdev);
506                 devices[devcnt].i.disk.minor = minor(stb.st_rdev);
507                 if (most_recent < devcnt) {
508                         if (devices[devcnt].i.events
509                             > devices[most_recent].i.events)
510                                 most_recent = devcnt;
511                 }
512                 if (info.array.level == -4)
513                         /* with multipath, the raid_disk from the superblock is meaningless */
514                         i = devcnt;
515                 else
516                         i = devices[devcnt].i.disk.raid_disk;
517                 if (i+1 == 0) {
518                         if (nextspare < info.array.raid_disks)
519                                 nextspare = info.array.raid_disks;
520                         i = nextspare++;
521                 } else {
522                         if (i >= info.array.raid_disks &&
523                             i >= nextspare)
524                                 nextspare = i+1;
525                 }
526                 if (i < 10000) {
527                         if (i >= bestcnt) {
528                                 unsigned int newbestcnt = i+10;
529                                 int *newbest = malloc(sizeof(int)*newbestcnt);
530                                 unsigned int c;
531                                 for (c=0; c < newbestcnt; c++)
532                                         if (c < bestcnt)
533                                                 newbest[c] = best[c];
534                                         else
535                                                 newbest[c] = -1;
536                                 if (best)free(best);
537                                 best = newbest;
538                                 bestcnt = newbestcnt;
539                         }
540                         if (best[i] >=0 &&
541                             devices[best[i]].i.events
542                             == devices[devcnt].i.events
543                             && (devices[best[i]].i.disk.minor
544                                 != devices[devcnt].i.disk.minor)
545                             && st->ss == &super0
546                             && info.array.level != LEVEL_MULTIPATH) {
547                                 /* two different devices with identical superblock.
548                                  * Could be a mis-detection caused by overlapping
549                                  * partitions.  fail-safe.
550                                  */
551                                 fprintf(stderr, Name ": WARNING %s and %s appear"
552                                         " to have very similar superblocks.\n"
553                                         "      If they are really different, "
554                                         "please --zero the superblock on one\n"
555                                         "      If they are the same or overlap,"
556                                         " please remove one from %s.\n",
557                                         devices[best[i]].devname, devname,
558                                         inargv ? "the list" :
559                                            "the\n      DEVICE list in mdadm.conf"
560                                         );
561                                 if (must_close) close(mdfd);
562                                 return 1;
563                         }
564                         if (best[i] == -1
565                             || (devices[best[i]].i.events
566                                 < devices[devcnt].i.events))
567                                 best[i] = devcnt;
568                 }
569                 devcnt++;
570         }
571
572         if (devcnt == 0) {
573                 fprintf(stderr, Name ": no devices found for %s\n",
574                         mddev);
575                 if (st)
576                         st->ss->free_super(st);
577                 if (must_close) close(mdfd);
578                 return 1;
579         }
580
581         if (update && strcmp(update, "byteorder")==0)
582                 st->minor_version = 90;
583
584         st->ss->getinfo_super(st, &info);
585         clean = info.array.state & 1;
586
587         /* now we have some devices that might be suitable.
588          * I wonder how many
589          */
590         avail = malloc(info.array.raid_disks);
591         memset(avail, 0, info.array.raid_disks);
592         okcnt = 0;
593         sparecnt=0;
594         for (i=0; i< bestcnt ;i++) {
595                 int j = best[i];
596                 int event_margin = 1; /* always allow a difference of '1'
597                                        * like the kernel does
598                                        */
599                 if (j < 0) continue;
600                 /* note: we ignore error flags in multipath arrays
601                  * as they don't make sense
602                  */
603                 if (info.array.level != -4)
604                         if (!(devices[j].i.disk.state & (1<<MD_DISK_SYNC))) {
605                                 if (!(devices[j].i.disk.state
606                                       & (1<<MD_DISK_FAULTY)))
607                                         sparecnt++;
608                                 continue;
609                         }
610                 if (devices[j].i.events+event_margin >=
611                     devices[most_recent].i.events) {
612                         devices[j].uptodate = 1;
613                         if (i < info.array.raid_disks) {
614                                 okcnt++;
615                                 avail[i]=1;
616                         } else
617                                 sparecnt++;
618                 }
619         }
620         while (force && !enough(info.array.level, info.array.raid_disks,
621                                 info.array.layout, 1,
622                                 avail, okcnt)) {
623                 /* Choose the newest best drive which is
624                  * not up-to-date, update the superblock
625                  * and add it.
626                  */
627                 int fd;
628                 struct supertype *tst;
629                 long long current_events;
630                 chosen_drive = -1;
631                 for (i=0; i<info.array.raid_disks && i < bestcnt; i++) {
632                         int j = best[i];
633                         if (j>=0 &&
634                             !devices[j].uptodate &&
635                             devices[j].i.events > 0 &&
636                             (chosen_drive < 0 ||
637                              devices[j].i.events
638                              > devices[chosen_drive].i.events))
639                                 chosen_drive = j;
640                 }
641                 if (chosen_drive < 0)
642                         break;
643                 current_events = devices[chosen_drive].i.events;
644         add_another:
645                 if (verbose >= 0)
646                         fprintf(stderr, Name ": forcing event count in %s(%d) from %d upto %d\n",
647                                 devices[chosen_drive].devname,
648                                 devices[chosen_drive].i.disk.raid_disk,
649                                 (int)(devices[chosen_drive].i.events),
650                                 (int)(devices[most_recent].i.events));
651                 fd = dev_open(devices[chosen_drive].devname, O_RDWR|O_EXCL);
652                 if (fd < 0) {
653                         fprintf(stderr, Name ": Couldn't open %s for write - not updating\n",
654                                 devices[chosen_drive].devname);
655                         devices[chosen_drive].i.events = 0;
656                         continue;
657                 }
658                 tst = dup_super(st);
659                 if (tst->ss->load_super(tst,fd, NULL)) {
660                         close(fd);
661                         fprintf(stderr, Name ": RAID superblock disappeared from %s - not updating.\n",
662                                 devices[chosen_drive].devname);
663                         devices[chosen_drive].i.events = 0;
664                         continue;
665                 }
666                 info.events = devices[most_recent].i.events;
667                 tst->ss->update_super(tst, &info, "force-one",
668                                      devices[chosen_drive].devname, verbose,
669                                      0, NULL);
670
671                 if (tst->ss->store_super(tst, fd)) {
672                         close(fd);
673                         fprintf(stderr, Name ": Could not re-write superblock on %s\n",
674                                 devices[chosen_drive].devname);
675                         devices[chosen_drive].i.events = 0;
676                         tst->ss->free_super(tst);
677                         continue;
678                 }
679                 close(fd);
680                 devices[chosen_drive].i.events = devices[most_recent].i.events;
681                 devices[chosen_drive].uptodate = 1;
682                 avail[chosen_drive] = 1;
683                 okcnt++;
684                 tst->ss->free_super(tst);
685
686                 /* If there are any other drives of the same vintage,
687                  * add them in as well.  We can't lose and we might gain
688                  */
689                 for (i=0; i<info.array.raid_disks && i < bestcnt ; i++) {
690                         int j = best[i];
691                         if (j >= 0 &&
692                             !devices[j].uptodate &&
693                             devices[j].i.events > 0 &&
694                             devices[j].i.events == current_events) {
695                                 chosen_drive = j;
696                                 goto add_another;
697                         }
698                 }
699         }
700
701         /* Now we want to look at the superblock which the kernel will base things on
702          * and compare the devices that we think are working with the devices that the
703          * superblock thinks are working.
704          * If there are differences and --force is given, then update this chosen
705          * superblock.
706          */
707         chosen_drive = -1;
708         st->ss->free_super(st);
709         for (i=0; chosen_drive < 0 && i<bestcnt; i++) {
710                 int j = best[i];
711                 int fd;
712
713                 if (j<0)
714                         continue;
715                 if (!devices[j].uptodate)
716                         continue;
717                 chosen_drive = j;
718                 if ((fd=dev_open(devices[j].devname, O_RDONLY|O_EXCL))< 0) {
719                         fprintf(stderr, Name ": Cannot open %s: %s\n",
720                                 devices[j].devname, strerror(errno));
721                         if (must_close) close(mdfd);
722                         return 1;
723                 }
724                 if (st->ss->load_super(st,fd, NULL)) {
725                         close(fd);
726                         fprintf(stderr, Name ": RAID superblock has disappeared from %s\n",
727                                 devices[j].devname);
728                         if (must_close) close(mdfd);
729                         return 1;
730                 }
731                 close(fd);
732         }
733         if (st->sb == NULL) {
734                 fprintf(stderr, Name ": No suitable drives found for %s\n", mddev);
735                 if (must_close) close(mdfd);
736                 return 1;
737         }
738         st->ss->getinfo_super(st, &info);
739         for (i=0; i<bestcnt; i++) {
740                 int j = best[i];
741                 unsigned int desired_state;
742
743                 if (i < info.array.raid_disks)
744                         desired_state = (1<<MD_DISK_ACTIVE) | (1<<MD_DISK_SYNC);
745                 else
746                         desired_state = 0;
747
748                 if (j<0)
749                         continue;
750                 if (!devices[j].uptodate)
751                         continue;
752
753                 devices[j].i.disk.state = desired_state;
754
755                 if (st->ss->update_super(st, &devices[j].i, "assemble", NULL,
756                                          verbose, 0, NULL)) {
757                         if (force) {
758                                 if (verbose >= 0)
759                                         fprintf(stderr, Name ": "
760                                                 "clearing FAULTY flag for device %d in %s for %s\n",
761                                                 j, mddev, devices[j].devname);
762                                 change = 1;
763                         } else {
764                                 if (verbose >= -1)
765                                         fprintf(stderr, Name ": "
766                                                 "device %d in %s has wrong state in superblock, but %s seems ok\n",
767                                                 i, mddev, devices[j].devname);
768                         }
769                 }
770 #if 0
771                 if (!(super.disks[i].i.disk.state & (1 << MD_DISK_FAULTY))) {
772                         fprintf(stderr, Name ": devices %d of %s is not marked FAULTY in superblock, but cannot be found\n",
773                                 i, mddev);
774                 }
775 #endif
776         }
777         if (force && !clean &&
778             !enough(info.array.level, info.array.raid_disks,
779                     info.array.layout, clean,
780                     avail, okcnt)) {
781                 change += st->ss->update_super(st, &info, "force-array",
782                                         devices[chosen_drive].devname, verbose,
783                                                0, NULL);
784                 clean = 1;
785         }
786
787         if (change) {
788                 int fd;
789                 fd = dev_open(devices[chosen_drive].devname, O_RDWR|O_EXCL);
790                 if (fd < 0) {
791                         fprintf(stderr, Name ": Could not open %s for write - cannot Assemble array.\n",
792                                 devices[chosen_drive].devname);
793                         if (must_close) close(mdfd);
794                         return 1;
795                 }
796                 if (st->ss->store_super(st, fd)) {
797                         close(fd);
798                         fprintf(stderr, Name ": Could not re-write superblock on %s\n",
799                                 devices[chosen_drive].devname);
800                         if (must_close) close(mdfd);
801                         return 1;
802                 }
803                 close(fd);
804         }
805
806         /* If we are in the middle of a reshape we may need to restore saved data
807          * that was moved aside due to the reshape overwriting live data
808          * The code of doing this lives in Grow.c
809          */
810 #ifndef MDASSEMBLE
811         if (info.reshape_active) {
812                 int err = 0;
813                 int *fdlist = malloc(sizeof(int)* bestcnt);
814                 for (i=0; i<bestcnt; i++) {
815                         int j = best[i];
816                         if (j >= 0) {
817                                 fdlist[i] = dev_open(devices[j].devname, O_RDWR|O_EXCL);
818                                 if (fdlist[i] < 0) {
819                                         fprintf(stderr, Name ": Could not open %s for write - cannot Assemble array.\n",
820                                                 devices[j].devname);
821                                         err = 1;
822                                         break;
823                                 }
824                         } else
825                                 fdlist[i] = -1;
826                 }
827                 if (!err)
828                         err = Grow_restart(st, &info, fdlist, bestcnt, backup_file);
829                 while (i>0) {
830                         i--;
831                         if (fdlist[i]>=0) close(fdlist[i]);
832                 }
833                 if (err) {
834                         fprintf(stderr, Name ": Failed to restore critical section for reshape, sorry.\n");
835                         if (must_close) close(mdfd);
836                         return err;
837                 }
838         }
839 #endif
840         /* count number of in-sync devices according to the superblock.
841          * We must have this number to start the array without -s or -R
842          */
843         req_cnt = info.array.working_disks;
844
845         /* Almost ready to actually *do* something */
846         if (!old_linux) {
847                 int rv;
848
849 #ifndef MDASSEMBLE
850                 struct mdinfo *sra;
851                 if (st->ss->external) {
852                         char ver[100];
853                         strcat(strcpy(ver, "external:"), info.text_version);
854                         sra = sysfs_read(mdfd, 0, 0);
855                         if ((vers % 100) < 2 ||
856                             sra == NULL ||
857                             sysfs_set_str(sra, NULL, "metadata_version",
858                                           ver) < 0) {
859                                 fprintf(stderr, Name ": This kernel does not "
860                                         "support external metadata.\n");
861                                 return 1;
862                         }
863                         rv = sysfs_set_array(sra, &info);
864                 } else
865 #endif
866                 if ((vers % 100) >= 1) { /* can use different versions */
867                         mdu_array_info_t inf;
868                         memset(&inf, 0, sizeof(inf));
869                         inf.major_version = info.array.major_version;
870                         inf.minor_version = info.array.minor_version;
871                         rv = ioctl(mdfd, SET_ARRAY_INFO, &inf);
872                 } else
873                         rv = ioctl(mdfd, SET_ARRAY_INFO, NULL);
874
875                 if (rv) {
876                         fprintf(stderr, Name ": SET_ARRAY_INFO failed for %s: %s\n",
877                                 mddev, strerror(errno));
878                         if (must_close) close(mdfd);
879                         return 1;
880                 }
881                 if (ident->bitmap_fd >= 0) {
882                         if (ioctl(mdfd, SET_BITMAP_FILE, ident->bitmap_fd) != 0) {
883                                 fprintf(stderr, Name ": SET_BITMAP_FILE failed.\n");
884                                 if (must_close) close(mdfd);
885                                 return 1;
886                         }
887                 } else if (ident->bitmap_file) {
888                         /* From config file */
889                         int bmfd = open(ident->bitmap_file, O_RDWR);
890                         if (bmfd < 0) {
891                                 fprintf(stderr, Name ": Could not open bitmap file %s\n",
892                                         ident->bitmap_file);
893                                 if (must_close) close(mdfd);
894                                 return 1;
895                         }
896                         if (ioctl(mdfd, SET_BITMAP_FILE, bmfd) != 0) {
897                                 fprintf(stderr, Name ": Failed to set bitmapfile for %s\n", mddev);
898                                 close(bmfd);
899                                 if (must_close) close(mdfd);
900                                 return 1;
901                         }
902                         close(bmfd);
903                 }
904
905                 /* First, add the raid disks, but add the chosen one last */
906                 for (i=0; i<= bestcnt; i++) {
907                         int j;
908                         if (i < bestcnt) {
909                                 j = best[i];
910                                 if (j == chosen_drive)
911                                         continue;
912                         } else
913                                 j = chosen_drive;
914
915                         if (j >= 0 /* && devices[j].uptodate */) {
916 #ifndef MDASSEMBLE
917                                 if (st->ss->external)
918                                         rv = sysfs_add_disk(sra, &devices[j].i);
919                                 else
920 #endif
921                                         rv = ioctl(mdfd, ADD_NEW_DISK,
922                                           &devices[j].i.disk);
923                                 if (rv) {
924                                         fprintf(stderr, Name ": failed to add "
925                                                         "%s to %s: %s\n",
926                                                 devices[j].devname,
927                                                 mddev,
928                                                 strerror(errno));
929                                         if (i < info.array.raid_disks
930                                             || i == bestcnt)
931                                                 okcnt--;
932                                         else
933                                                 sparecnt--;
934                                 } else if (verbose > 0)
935                                         fprintf(stderr, Name ": added %s "
936                                                         "to %s as %d\n",
937                                                 devices[j].devname, mddev,
938                                                 devices[j].i.disk.raid_disk);
939                         } else if (verbose > 0 && i < info.array.raid_disks)
940                                 fprintf(stderr, Name ": no uptodate device for "
941                                                 "slot %d of %s\n",
942                                         i, mddev);
943                 }
944
945                 if (info.array.level == LEVEL_CONTAINER) {
946                         if (verbose >= 0) {
947                                 fprintf(stderr, Name ": Container %s has been "
948                                         "assembled with %d drive%s",
949                                         mddev, okcnt, okcnt==1?"":"s");
950                                 if (okcnt < info.array.raid_disks)
951                                         fprintf(stderr, " (out of %d)",
952                                                 info.array.raid_disks);
953                                 fprintf(stderr, "\n");
954                         }
955                         if (must_close)
956                                 close(mdfd);
957                         return 0;
958                 }
959
960                 if (runstop == 1 ||
961                     (runstop <= 0 &&
962                      ( enough(info.array.level, info.array.raid_disks,
963                               info.array.layout, clean, avail, okcnt) &&
964                        (okcnt >= req_cnt || start_partial_ok)
965                              ))) {
966                         if (ioctl(mdfd, RUN_ARRAY, NULL)==0) {
967                                 if (verbose >= 0) {
968                                         fprintf(stderr, Name ": %s has been started with %d drive%s",
969                                                 mddev, okcnt, okcnt==1?"":"s");
970                                         if (okcnt < info.array.raid_disks)
971                                                 fprintf(stderr, " (out of %d)", info.array.raid_disks);
972                                         if (sparecnt)
973                                                 fprintf(stderr, " and %d spare%s", sparecnt, sparecnt==1?"":"s");
974                                         fprintf(stderr, ".\n");
975                                 }
976                                 if (must_close) {
977                                         int usecs = 1;
978                                         close(mdfd);
979                                         /* There is a nasty race with 'mdadm --monitor'.
980                                          * If it opens this device before we close it,
981                                          * it gets an incomplete open on which IO
982                                          * doesn't work and the capacity is
983                                          * wrong.
984                                          * If we reopen (to check for layered devices)
985                                          * before --monitor closes, we loose.
986                                          *
987                                          * So: wait upto 1 second for there to be
988                                          * a non-zero capacity.
989                                          */
990                                         while (usecs < 1000) {
991                                                 mdfd = open(mddev, O_RDONLY);
992                                                 if (mdfd >= 0) {
993                                                         unsigned long long size;
994                                                         if (get_dev_size(mdfd, NULL, &size) &&
995                                                             size > 0)
996                                                                 break;
997                                                         close(mdfd);
998                                                 }
999                                                 usleep(usecs);
1000                                                 usecs <<= 1;
1001                                         }
1002                                 }
1003                                 return 0;
1004                         }
1005                         fprintf(stderr, Name ": failed to RUN_ARRAY %s: %s\n",
1006                                 mddev, strerror(errno));
1007
1008                         if (!enough(info.array.level, info.array.raid_disks,
1009                                     info.array.layout, 1, avail, okcnt))
1010                                 fprintf(stderr, Name ": Not enough devices to "
1011                                         "start the array.\n");
1012                         else if (!enough(info.array.level,
1013                                          info.array.raid_disks,
1014                                          info.array.layout, clean,
1015                                          avail, okcnt))
1016                                 fprintf(stderr, Name ": Not enough devices to "
1017                                         "start the array while not clean "
1018                                         "- consider --force.\n");
1019
1020                         if (must_close) {
1021                                 ioctl(mdfd, STOP_ARRAY, NULL);
1022                                 close(mdfd);
1023                         }
1024                         return 1;
1025                 }
1026                 if (runstop == -1) {
1027                         fprintf(stderr, Name ": %s assembled from %d drive%s",
1028                                 mddev, okcnt, okcnt==1?"":"s");
1029                         if (okcnt != info.array.raid_disks)
1030                                 fprintf(stderr, " (out of %d)", info.array.raid_disks);
1031                         fprintf(stderr, ", but not started.\n");
1032                         if (must_close) close(mdfd);
1033                         return 0;
1034                 }
1035                 if (verbose >= -1) {
1036                         fprintf(stderr, Name ": %s assembled from %d drive%s", mddev, okcnt, okcnt==1?"":"s");
1037                         if (sparecnt)
1038                                 fprintf(stderr, " and %d spare%s", sparecnt, sparecnt==1?"":"s");
1039                         if (!enough(info.array.level, info.array.raid_disks,
1040                                     info.array.layout, 1, avail, okcnt))
1041                                 fprintf(stderr, " - not enough to start the array.\n");
1042                         else if (!enough(info.array.level,
1043                                          info.array.raid_disks,
1044                                          info.array.layout, clean,
1045                                          avail, okcnt))
1046                                 fprintf(stderr, " - not enough to start the "
1047                                         "array while not clean - consider "
1048                                         "--force.\n");
1049                         else {
1050                                 if (req_cnt == info.array.raid_disks)
1051                                         fprintf(stderr, " - need all %d to start it", req_cnt);
1052                                 else
1053                                         fprintf(stderr, " - need %d of %d to start", req_cnt, info.array.raid_disks);
1054                                 fprintf(stderr, " (use --run to insist).\n");
1055                         }
1056                 }
1057                 if (must_close) {
1058                         ioctl(mdfd, STOP_ARRAY, NULL);
1059                         close(mdfd);
1060                 }
1061                 return 1;
1062         } else {
1063                 /* The "chosen_drive" is a good choice, and if necessary, the superblock has
1064                  * been updated to point to the current locations of devices.
1065                  * so we can just start the array
1066                  */
1067                 unsigned long dev;
1068                 dev = makedev(devices[chosen_drive].i.disk.major,
1069                             devices[chosen_drive].i.disk.minor);
1070                 if (ioctl(mdfd, START_ARRAY, dev)) {
1071                     fprintf(stderr, Name ": Cannot start array: %s\n",
1072                             strerror(errno));
1073                 }
1074
1075         }
1076         if (must_close) close(mdfd);
1077         return 0;
1078 }