Check all member devices in enough_fd
[thirdparty/mdadm.git] / Monitor.c
1 /*
2  * mdadm - manage Linux "md" devices aka RAID arrays.
3  *
4  * Copyright (C) 2001-2009 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@suse.de>
23  */
24
25 #include        "mdadm.h"
26 #include        "md_p.h"
27 #include        "md_u.h"
28 #include        <sys/wait.h>
29 #include        <signal.h>
30 #include        <limits.h>
31 #include        <syslog.h>
32
33 /* The largest number of disks current arrays can manage is 384
34  * This really should be dynamically, but that will have to wait
35  * At least it isn't MD_SB_DISKS.
36  */
37 #define MaxDisks 384
38 struct state {
39         char *devname;
40         int devnum;     /* to sync with mdstat info */
41         long utime;
42         int err;
43         char *spare_group;
44         int active, working, failed, spare, raid;
45         int expected_spares;
46         int devstate[MaxDisks];
47         dev_t devid[MaxDisks];
48         int percent;
49         int parent_dev; /* For subarray, devnum of parent.
50                          * For others, NoMdDev
51                          */
52         struct supertype *metadata;
53         struct state *subarray;/* for a container it is a link to first subarray
54                                 * for a subarray it is a link to next subarray
55                                 * in the same container */
56         struct state *parent;  /* for a subarray it is a link to its container
57                                 */
58         struct state *next;
59 };
60
61 struct alert_info {
62         char *mailaddr;
63         char *mailfrom;
64         char *alert_cmd;
65         int dosyslog;
66 };
67 static int make_daemon(char *pidfile);
68 static int check_one_sharer(int scan);
69 static void alert(char *event, char *dev, char *disc, struct alert_info *info);
70 static int check_array(struct state *st, struct mdstat_ent *mdstat,
71                        int test, struct alert_info *info,
72                        int increments);
73 static int add_new_arrays(struct mdstat_ent *mdstat, struct state **statelist,
74                           int test, struct alert_info *info);
75 static void try_spare_migration(struct state *statelist, struct alert_info *info);
76 static void link_containers_with_subarrays(struct state *list);
77
78 int Monitor(struct mddev_dev *devlist,
79             char *mailaddr, char *alert_cmd,
80             int period, int daemonise, int scan, int oneshot,
81             int dosyslog, int test, char *pidfile, int increments,
82             int share)
83 {
84         /*
85          * Every few seconds, scan every md device looking for changes
86          * When a change is found, log it, possibly run the alert command,
87          * and possibly send Email
88          *
89          * For each array, we record:
90          *   Update time
91          *   active/working/failed/spare drives
92          *   State of each device.
93          *   %rebuilt if rebuilding
94          *
95          * If the update time changes, check out all the data again
96          * It is possible that we cannot get the state of each device
97          * due to bugs in the md kernel module.
98          * We also read /proc/mdstat to get rebuild percent,
99          * and to get state on all active devices incase of kernel bug.
100          *
101          * Events are:
102          *    Fail
103          *      An active device had Faulty set or Active/Sync removed
104          *    FailSpare
105          *      A spare device had Faulty set
106          *    SpareActive
107          *      An active device had a reverse transition
108          *    RebuildStarted
109          *      percent went from -1 to +ve
110          *    RebuildNN
111          *      percent went from below to not-below NN%
112          *    DeviceDisappeared
113          *      Couldn't access a device which was previously visible
114          *
115          * if we detect an array with active<raid and spare==0
116          * we look at other arrays that have same spare-group
117          * If we find one with active==raid and spare>0,
118          *  and if we can get_disk_info and find a name
119          *  Then we hot-remove and hot-add to the other array
120          *
121          * If devlist is NULL, then we can monitor everything because --scan
122          * was given.  We get an initial list from config file and add anything
123          * that appears in /proc/mdstat
124          */
125
126         struct state *statelist = NULL;
127         int finished = 0;
128         struct mdstat_ent *mdstat = NULL;
129         char *mailfrom = NULL;
130         struct alert_info info;
131
132         if (!mailaddr) {
133                 mailaddr = conf_get_mailaddr();
134                 if (mailaddr && ! scan)
135                         fprintf(stderr, Name ": Monitor using email address \"%s\" from config file\n",
136                                mailaddr);
137         }
138         mailfrom = conf_get_mailfrom();
139
140         if (!alert_cmd) {
141                 alert_cmd = conf_get_program();
142                 if (alert_cmd && ! scan)
143                         fprintf(stderr, Name ": Monitor using program \"%s\" from config file\n",
144                                alert_cmd);
145         }
146         if (scan && !mailaddr && !alert_cmd && !dosyslog) {
147                 fprintf(stderr, Name ": No mail address or alert command - not monitoring.\n");
148                 return 1;
149         }
150         info.alert_cmd = alert_cmd;
151         info.mailaddr = mailaddr;
152         info.mailfrom = mailfrom;
153         info.dosyslog = dosyslog;
154
155         if (daemonise) {
156                 int rv = make_daemon(pidfile);
157                 if (rv >= 0)
158                         return rv;
159         }
160
161         if (share) 
162                 if (check_one_sharer(scan))
163                         return 1;
164
165         if (devlist == NULL) {
166                 struct mddev_ident *mdlist = conf_get_ident(NULL);
167                 for (; mdlist; mdlist=mdlist->next) {
168                         struct state *st;
169                         if (mdlist->devname == NULL)
170                                 continue;
171                         if (strcasecmp(mdlist->devname, "<ignore>") == 0)
172                                 continue;
173                         st = calloc(1, sizeof *st);
174                         if (st == NULL)
175                                 continue;
176                         if (mdlist->devname[0] == '/')
177                                 st->devname = strdup(mdlist->devname);
178                         else {
179                                 st->devname = malloc(8+strlen(mdlist->devname)+1);
180                                 strcpy(strcpy(st->devname, "/dev/md/"),
181                                        mdlist->devname);
182                         }
183                         st->next = statelist;
184                         st->devnum = INT_MAX;
185                         st->percent = -2;
186                         st->expected_spares = mdlist->spare_disks;
187                         if (mdlist->spare_group)
188                                 st->spare_group = strdup(mdlist->spare_group);
189                         statelist = st;
190                 }
191         } else {
192                 struct mddev_dev *dv;
193                 for (dv=devlist ; dv; dv=dv->next) {
194                         struct mddev_ident *mdlist = conf_get_ident(dv->devname);
195                         struct state *st = calloc(1, sizeof *st);
196                         if (st == NULL)
197                                 continue;
198                         st->devname = strdup(dv->devname);
199                         st->next = statelist;
200                         st->devnum = INT_MAX;
201                         st->percent = -2;
202                         st->expected_spares = -1;
203                         if (mdlist) {
204                                 st->expected_spares = mdlist->spare_disks;
205                                 if (mdlist->spare_group)
206                                         st->spare_group = strdup(mdlist->spare_group);
207                         }
208                         statelist = st;
209                 }
210         }
211
212
213         while (! finished) {
214                 int new_found = 0;
215                 struct state *st;
216                 int anydegraded = 0;
217
218                 if (mdstat)
219                         free_mdstat(mdstat);
220                 mdstat = mdstat_read(oneshot?0:1, 0);
221
222                 for (st=statelist; st; st=st->next)
223                         if (check_array(st, mdstat, test, &info, increments))
224                                 anydegraded = 1;
225                 
226                 /* now check if there are any new devices found in mdstat */
227                 if (scan)
228                         new_found = add_new_arrays(mdstat, &statelist, test,
229                                                    &info);
230
231                 /* If an array has active < raid && spare == 0 && spare_group != NULL
232                  * Look for another array with spare > 0 and active == raid and same spare_group
233                  *  if found, choose a device and hotremove/hotadd
234                  */
235                 if (share && anydegraded)
236                         try_spare_migration(statelist, &info);
237                 if (!new_found) {
238                         if (oneshot)
239                                 break;
240                         else
241                                 mdstat_wait(period);
242                 }
243                 test = 0;
244         }
245         if (pidfile)
246                 unlink(pidfile);
247         return 0;
248 }
249
250 static int make_daemon(char *pidfile)
251 {
252         /* Return:
253          * -1 in the forked daemon
254          *  0 in the parent
255          *  1 on error
256          * so a none-negative becomes the exit code.
257          */
258         int pid = fork();
259         if (pid > 0) {
260                 if (!pidfile)
261                         printf("%d\n", pid);
262                 else {
263                         FILE *pid_file;
264                         pid_file=fopen(pidfile, "w");
265                         if (!pid_file)
266                                 perror("cannot create pid file");
267                         else {
268                                 fprintf(pid_file,"%d\n", pid);
269                                 fclose(pid_file);
270                         }
271                 }
272                 return 0;
273         }
274         if (pid < 0) {
275                 perror("daemonise");
276                 return 1;
277         }
278         close(0);
279         open("/dev/null", O_RDWR);
280         dup2(0,1);
281         dup2(0,2);
282         setsid();
283         return -1;
284 }
285
286 static int check_one_sharer(int scan)
287 {
288         int pid, rv;
289         FILE *fp;
290         char dir[20];
291         struct stat buf;
292         fp = fopen("/var/run/mdadm/autorebuild.pid", "r");
293         if (fp) {
294                 if (fscanf(fp, "%d", &pid) != 1)
295                         pid = -1;
296                 sprintf(dir, "/proc/%d", pid);
297                 rv = stat(dir, &buf);
298                 if (rv != -1) {
299                         if (scan) {
300                                 fprintf(stderr, Name ": Only one "
301                                         "autorebuild process allowed"
302                                         " in scan mode, aborting\n");
303                                 fclose(fp);
304                                 return 1;
305                         } else {
306                                 fprintf(stderr, Name ": Warning: One"
307                                         " autorebuild process already"
308                                         " running.\n");
309                         }
310                 }
311                 fclose(fp);
312         }
313         if (scan) {
314                 if (mkdir("/var/run/mdadm", S_IRWXU) < 0 &&
315                     errno != EEXIST) {
316                         fprintf(stderr, Name ": Can't create "
317                                 "autorebuild.pid file\n");
318                 } else {
319                         fp = fopen("/var/run/mdadm/autorebuild.pid", "w");
320                         if (!fp)
321                                 fprintf(stderr, Name ": Cannot create"
322                                         " autorebuild.pid"
323                                         "file\n");
324                         else {
325                                 pid = getpid();
326                                 fprintf(fp, "%d\n", pid);
327                                 fclose(fp);
328                         }
329                 }
330         }
331         return 0;
332 }
333
334 static void alert(char *event, char *dev, char *disc, struct alert_info *info)
335 {
336         int priority;
337
338         if (!info->alert_cmd && !info->mailaddr && !info->dosyslog) {
339                 time_t now = time(0);
340
341                 printf("%1.15s: %s on %s %s\n", ctime(&now)+4, event, dev, disc?disc:"unknown device");
342         }
343         if (info->alert_cmd) {
344                 int pid = fork();
345                 switch(pid) {
346                 default:
347                         waitpid(pid, NULL, 0);
348                         break;
349                 case -1:
350                         break;
351                 case 0:
352                         execl(info->alert_cmd, info->alert_cmd,
353                               event, dev, disc, NULL);
354                         exit(2);
355                 }
356         }
357         if (info->mailaddr &&
358             (strncmp(event, "Fail", 4)==0 ||
359              strncmp(event, "Test", 4)==0 ||
360              strncmp(event, "Spares", 6)==0 ||
361              strncmp(event, "Degrade", 7)==0)) {
362                 FILE *mp = popen(Sendmail, "w");
363                 if (mp) {
364                         FILE *mdstat;
365                         char hname[256];
366                         gethostname(hname, sizeof(hname));
367                         signal(SIGPIPE, SIG_IGN);
368                         if (info->mailfrom)
369                                 fprintf(mp, "From: %s\n", info->mailfrom);
370                         else
371                                 fprintf(mp, "From: " Name " monitoring <root>\n");
372                         fprintf(mp, "To: %s\n", info->mailaddr);
373                         fprintf(mp, "Subject: %s event on %s:%s\n\n",
374                                 event, dev, hname);
375
376                         fprintf(mp,
377                                 "This is an automatically generated"
378                                 " mail message from " Name "\n");
379                         fprintf(mp, "running on %s\n\n", hname);
380
381                         fprintf(mp,
382                                 "A %s event had been detected on"
383                                 " md device %s.\n\n", event, dev);
384
385                         if (disc && disc[0] != ' ')
386                                 fprintf(mp,
387                                         "It could be related to"
388                                         " component device %s.\n\n", disc);
389                         if (disc && disc[0] == ' ')
390                                 fprintf(mp, "Extra information:%s.\n\n", disc);
391
392                         fprintf(mp, "Faithfully yours, etc.\n");
393
394                         mdstat = fopen("/proc/mdstat", "r");
395                         if (mdstat) {
396                                 char buf[8192];
397                                 int n;
398                                 fprintf(mp,
399                                         "\nP.S. The /proc/mdstat file"
400                                         " currently contains the following:\n\n");
401                                 while ( (n=fread(buf, 1, sizeof(buf), mdstat)) > 0)
402                                         n=fwrite(buf, 1, n, mp);
403                                 fclose(mdstat);
404                         }
405                         pclose(mp);
406                 }
407         }
408
409         /* log the event to syslog maybe */
410         if (info->dosyslog) {
411                 /* Log at a different severity depending on the event.
412                  *
413                  * These are the critical events:  */
414                 if (strncmp(event, "Fail", 4)==0 ||
415                     strncmp(event, "Degrade", 7)==0 ||
416                     strncmp(event, "DeviceDisappeared", 17)==0)
417                         priority = LOG_CRIT;
418                 /* Good to know about, but are not failures: */
419                 else if (strncmp(event, "Rebuild", 7)==0 ||
420                          strncmp(event, "MoveSpare", 9)==0 ||
421                          strncmp(event, "Spares", 6) != 0)
422                         priority = LOG_WARNING;
423                 /* Everything else: */
424                 else
425                         priority = LOG_INFO;
426
427                 if (disc)
428                         syslog(priority,
429                                "%s event detected on md device %s,"
430                                " component device %s", event, dev, disc);
431                 else
432                         syslog(priority,
433                                "%s event detected on md device %s",
434                                event, dev);
435         }
436 }
437
438 static int check_array(struct state *st, struct mdstat_ent *mdstat,
439                        int test, struct alert_info *ainfo,
440                        int increments)
441 {
442         /* Update the state 'st' to reflect any changes shown in mdstat,
443          * or found by directly examining the array, and return
444          * '1' if the array is degraded, or '0' if it is optimal (or dead).
445          */
446         struct { int state, major, minor; } info[MaxDisks];
447         mdu_array_info_t array;
448         struct mdstat_ent *mse = NULL, *mse2;
449         char *dev = st->devname;
450         int fd;
451         int i;
452         int remaining_disks;
453         int last_disk;
454
455         if (test)
456                 alert("TestMessage", dev, NULL, ainfo);
457         fd = open(dev, O_RDONLY);
458         if (fd < 0) {
459                 if (!st->err)
460                         alert("DeviceDisappeared", dev, NULL, ainfo);
461                 st->err=1;
462                 return 0;
463         }
464         fcntl(fd, F_SETFD, FD_CLOEXEC);
465         if (ioctl(fd, GET_ARRAY_INFO, &array)<0) {
466                 if (!st->err)
467                         alert("DeviceDisappeared", dev, NULL, ainfo);
468                 st->err=1;
469                 close(fd);
470                 return 0;
471         }
472         /* It's much easier to list what array levels can't
473          * have a device disappear than all of them that can
474          */
475         if (array.level == 0 || array.level == -1) {
476                 if (!st->err)
477                         alert("DeviceDisappeared", dev, "Wrong-Level", ainfo);
478                 st->err = 1;
479                 close(fd);
480                 return 0;
481         }
482         if (st->devnum == INT_MAX) {
483                 struct stat stb;
484                 if (fstat(fd, &stb) == 0 &&
485                     (S_IFMT&stb.st_mode)==S_IFBLK) {
486                         if (major(stb.st_rdev) == MD_MAJOR)
487                                 st->devnum = minor(stb.st_rdev);
488                         else
489                                 st->devnum = -1- (minor(stb.st_rdev)>>6);
490                 }
491         }
492
493         for (mse2 = mdstat ; mse2 ; mse2=mse2->next)
494                 if (mse2->devnum == st->devnum) {
495                         mse2->devnum = INT_MAX; /* flag it as "used" */
496                         mse = mse2;
497                 }
498
499         if (!mse) {
500                 /* duplicated array in statelist
501                  * or re-created after reading mdstat*/
502                 st->err = 1;
503                 close(fd);
504                 return 0;
505         }
506         /* this array is in /proc/mdstat */
507         if (array.utime == 0)
508                 /* external arrays don't update utime, so
509                  * just make sure it is always different. */
510                 array.utime = st->utime + 1;;
511
512         if (st->utime == array.utime &&
513             st->failed == array.failed_disks &&
514             st->working == array.working_disks &&
515             st->spare == array.spare_disks &&
516             (mse == NULL  || (
517                     mse->percent == st->percent
518                     ))) {
519                 close(fd);
520                 st->err = 0;
521                 if ((st->active < st->raid) && st->spare == 0)
522                         return 1;
523                 else
524                         return 0;
525         }
526         if (st->utime == 0 && /* new array */
527             mse->pattern && strchr(mse->pattern, '_') /* degraded */
528                 )
529                 alert("DegradedArray", dev, NULL, ainfo);
530
531         if (st->utime == 0 && /* new array */
532             st->expected_spares > 0 &&
533             array.spare_disks < st->expected_spares)
534                 alert("SparesMissing", dev, NULL, ainfo);
535         if (st->percent == -1 &&
536             mse->percent >= 0)
537                 alert("RebuildStarted", dev, NULL, ainfo);
538         if (st->percent >= 0 &&
539             mse->percent >= 0 &&
540             (mse->percent / increments) > (st->percent / increments)) {
541                 char percentalert[15]; // "RebuildNN" (10 chars) or "RebuildStarted" (15 chars)
542
543                 if((mse->percent / increments) == 0)
544                         snprintf(percentalert, sizeof(percentalert), "RebuildStarted");
545                 else
546                         snprintf(percentalert, sizeof(percentalert), "Rebuild%02d", mse->percent);
547
548                 alert(percentalert, dev, NULL, ainfo);
549         }
550
551         if (mse->percent == -1 &&
552             st->percent >= 0) {
553                 /* Rebuild/sync/whatever just finished.
554                  * If there is a number in /mismatch_cnt,
555                  * we should report that.
556                  */
557                 struct mdinfo *sra =
558                         sysfs_read(-1, st->devnum, GET_MISMATCH);
559                 if (sra && sra->mismatch_cnt > 0) {
560                         char cnt[40];
561                         sprintf(cnt, " mismatches found: %d", sra->mismatch_cnt);
562                         alert("RebuildFinished", dev, cnt, ainfo);
563                 } else
564                         alert("RebuildFinished", dev, NULL, ainfo);
565                 if (sra)
566                         free(sra);
567         }
568         st->percent = mse->percent;
569
570         remaining_disks = array.nr_disks;
571         for (i=0; i<MaxDisks && remaining_disks > 0;
572              i++) {
573                 mdu_disk_info_t disc;
574                 disc.number = i;
575                 if (ioctl(fd, GET_DISK_INFO, &disc) >= 0) {
576                         info[i].state = disc.state;
577                         info[i].major = disc.major;
578                         info[i].minor = disc.minor;
579                         if (disc.major || disc.minor)
580                                 remaining_disks --;
581                 } else
582                         info[i].major = info[i].minor = 0;
583         }
584         last_disk = i;
585
586         if (mse->metadata_version &&
587             strncmp(mse->metadata_version, "external:", 9) == 0 &&
588             is_subarray(mse->metadata_version+9))
589                 st->parent_dev =
590                         devname2devnum(mse->metadata_version+10);
591         else
592                 st->parent_dev = NoMdDev;
593         if (st->metadata == NULL &&
594             st->parent_dev == NoMdDev)
595                 st->metadata = super_by_fd(fd, NULL);
596
597         close(fd);
598
599         for (i=0; i<MaxDisks; i++) {
600                 mdu_disk_info_t disc = {0,0,0,0,0};
601                 int newstate=0;
602                 int change;
603                 char *dv = NULL;
604                 disc.number = i;
605                 if (i >= last_disk) {
606                         newstate = 0;
607                         disc.major = disc.minor = 0;
608                 } else if (info[i].major || info[i].minor) {
609                         newstate = info[i].state;
610                         dv = map_dev(info[i].major, info[i].minor, 1);
611                         disc.state = newstate;
612                         disc.major = info[i].major;
613                         disc.minor = info[i].minor;
614                 } else if (mse &&  mse->pattern && i < (int)strlen(mse->pattern)) {
615                         switch(mse->pattern[i]) {
616                         case 'U': newstate = 6 /* ACTIVE/SYNC */; break;
617                         case '_': newstate = 8 /* REMOVED */; break;
618                         }
619                         disc.major = disc.minor = 0;
620                 }
621                 if (dv == NULL && st->devid[i])
622                         dv = map_dev(major(st->devid[i]),
623                                      minor(st->devid[i]), 1);
624                 change = newstate ^ st->devstate[i];
625                 if (st->utime && change && !st->err) {
626                         if (i < array.raid_disks &&
627                             (((newstate&change)&(1<<MD_DISK_FAULTY)) ||
628                              ((st->devstate[i]&change)&(1<<MD_DISK_ACTIVE)) ||
629                              ((st->devstate[i]&change)&(1<<MD_DISK_SYNC)))
630                                 )
631                                 alert("Fail", dev, dv, ainfo);
632                         else if (i >= array.raid_disks &&
633                                  (disc.major || disc.minor) &&
634                                  st->devid[i] == makedev(disc.major, disc.minor) &&
635                                  ((newstate&change)&(1<<MD_DISK_FAULTY))
636                                 )
637                                 alert("FailSpare", dev, dv, ainfo);
638                         else if (i < array.raid_disks &&
639                                  ! (newstate & (1<<MD_DISK_REMOVED)) &&
640                                  (((st->devstate[i]&change)&(1<<MD_DISK_FAULTY)) ||
641                                   ((newstate&change)&(1<<MD_DISK_ACTIVE)) ||
642                                   ((newstate&change)&(1<<MD_DISK_SYNC)))
643                                 )
644                                 alert("SpareActive", dev, dv, ainfo);
645                 }
646                 st->devstate[i] = newstate;
647                 st->devid[i] = makedev(disc.major, disc.minor);
648         }
649         st->active = array.active_disks;
650         st->working = array.working_disks;
651         st->spare = array.spare_disks;
652         st->failed = array.failed_disks;
653         st->utime = array.utime;
654         st->raid = array.raid_disks;
655         st->err = 0;
656         if ((st->active < st->raid) && st->spare == 0)
657                 return 1;
658         return 0;
659 }
660
661 static int add_new_arrays(struct mdstat_ent *mdstat, struct state **statelist,
662                           int test, struct alert_info *info)
663 {
664         struct mdstat_ent *mse;
665         int new_found = 0;
666
667         for (mse=mdstat; mse; mse=mse->next)
668                 if (mse->devnum != INT_MAX &&
669                     (!mse->level  || /* retrieve containers */
670                      (strcmp(mse->level, "raid0") != 0 &&
671                       strcmp(mse->level, "linear") != 0))
672                         ) {
673                         struct state *st = calloc(1, sizeof *st);
674                         mdu_array_info_t array;
675                         int fd;
676                         if (st == NULL)
677                                 continue;
678                         st->devname = strdup(get_md_name(mse->devnum));
679                         if ((fd = open(st->devname, O_RDONLY)) < 0 ||
680                             ioctl(fd, GET_ARRAY_INFO, &array)< 0) {
681                                 /* no such array */
682                                 if (fd >=0) close(fd);
683                                 put_md_name(st->devname);
684                                 free(st->devname);
685                                 if (st->metadata) {
686                                         st->metadata->ss->free_super(st->metadata);
687                                         free(st->metadata);
688                                 }
689                                 free(st);
690                                 continue;
691                         }
692                         close(fd);
693                         st->next = *statelist;
694                         st->err = 1;
695                         st->devnum = mse->devnum;
696                         st->percent = -2;
697                         st->expected_spares = -1;
698                         if (mse->metadata_version &&
699                             strncmp(mse->metadata_version, "external:", 9) == 0 &&
700                             is_subarray(mse->metadata_version+9))
701                                 st->parent_dev =
702                                         devname2devnum(mse->metadata_version+10);
703                         else
704                                 st->parent_dev = NoMdDev;
705                         *statelist = st;
706                         if (test)
707                                 alert("TestMessage", st->devname, NULL, info);
708                         alert("NewArray", st->devname, NULL, info);
709                         new_found = 1;
710                 }
711         return new_found;
712 }
713
714 static int get_min_spare_size_required(struct state *st, unsigned long long *sizep)
715 {
716         int fd;
717
718         if (!st->metadata ||
719             !st->metadata->ss->min_acceptable_spare_size) {
720                 *sizep = 0;
721                 return 0;
722         }
723
724         fd = open(st->devname, O_RDONLY);
725         if (fd < 0)
726                 return 1;
727         if (st->metadata->ss->external)
728                 st->metadata->ss->load_container(st->metadata, fd, st->devname);
729         else
730                 st->metadata->ss->load_super(st->metadata, fd, st->devname);
731         close(fd);
732         if (!st->metadata->sb)
733                 return 1;
734         *sizep = st->metadata->ss->min_acceptable_spare_size(st->metadata);
735         st->metadata->ss->free_super(st->metadata);
736
737         return 0;
738 }
739
740 static int check_donor(struct state *from, struct state *to)
741 {
742         struct state *sub;
743
744         if (from == to)
745                 return 0;
746         if (from->parent)
747                 /* Cannot move from a member */
748                 return 0;
749         if (from->err)
750                 return 0;
751         for (sub = from->subarray; sub; sub = sub->subarray)
752                 /* If source array has degraded subarrays, don't
753                  * remove anything
754                  */
755                 if (sub->active < sub->raid)
756                         return 0;
757         if (from->metadata->ss->external == 0)
758                 if (from->active < from->raid)
759                         return 0;
760         if (from->spare <= 0)
761                 return 0;
762         return 1;
763 }
764
765 static dev_t choose_spare(struct state *from, struct state *to,
766                         struct domainlist *domlist, unsigned long long min_size)
767 {
768         int d;
769         dev_t dev = 0;
770
771         for (d = from->raid; !dev && d < MaxDisks; d++) {
772                 if (from->devid[d] > 0 &&
773                     from->devstate[d] == 0) {
774                         struct dev_policy *pol;
775                         unsigned long long dev_size;
776
777                         if (to->metadata->ss->external &&
778                             test_partition_from_id(from->devid[d]))
779                                 continue;
780
781                         if (min_size &&
782                             dev_size_from_id(from->devid[d], &dev_size) &&
783                             dev_size < min_size)
784                                 continue;
785
786                         pol = devnum_policy(from->devid[d]);
787                         if (from->spare_group)
788                                 pol_add(&pol, pol_domain,
789                                         from->spare_group, NULL);
790                         if (domain_test(domlist, pol, to->metadata->ss->name) == 1)
791                             dev = from->devid[d];
792                         dev_policy_free(pol);
793                 }
794         }
795         return dev;
796 }
797
798 static dev_t container_choose_spare(struct state *from, struct state *to,
799                                     struct domainlist *domlist,
800                                     unsigned long long min_size, int active)
801 {
802         /* This is similar to choose_spare, but we cannot trust devstate,
803          * so we need to read the metadata instead
804          */
805         struct mdinfo *list;
806         struct supertype *st = from->metadata;
807         int fd = open(from->devname, O_RDONLY);
808         int err;
809         dev_t dev = 0;
810
811         if (fd < 0)
812                 return 0;
813         if (!st->ss->getinfo_super_disks) {
814                 close(fd);
815                 return 0;
816         }
817         
818         err = st->ss->load_container(st, fd, NULL);
819         close(fd);
820         if (err)
821                 return 0;
822         
823         if (from == to) {
824                 /* We must check if number of active disks has not increased
825                  * since ioctl in main loop. mdmon may have added spare
826                  * to subarray. If so we do not need to look for more spares
827                  * so return non zero value */
828                 int active_cnt = 0;
829                 struct mdinfo *dp;
830                 list = st->ss->getinfo_super_disks(st);
831                 if (!list) {
832                         st->ss->free_super(st);
833                         return 1;
834                 }
835                 dp = list->devs;
836                 while (dp) {
837                         if (dp->disk.state & (1<<MD_DISK_SYNC) &&
838                             !(dp->disk.state & (1<<MD_DISK_FAULTY)))
839                                 active_cnt++;
840                         dp = dp->next;
841                 }
842                 sysfs_free(list);
843                 if (active < active_cnt) {
844                         /* Spare just activated.*/
845                         st->ss->free_super(st);
846                         return 1;
847                 }
848         }
849
850         /* We only need one spare so full list not needed */
851         list = container_choose_spares(st, min_size, domlist, from->spare_group,
852                                        to->metadata->ss->name, 1);
853         if (list) {
854                 struct mdinfo *disks = list->devs;
855                 if (disks)
856                         dev = makedev(disks->disk.major, disks->disk.minor);
857                 sysfs_free(list);
858         }
859         st->ss->free_super(st);
860         return dev;
861 }
862
863
864 static void try_spare_migration(struct state *statelist, struct alert_info *info)
865 {
866         struct state *from;
867         struct state *st;
868
869         link_containers_with_subarrays(statelist);
870         for (st = statelist; st; st = st->next)
871                 if (st->active < st->raid &&
872                     st->spare == 0 && !st->err) {
873                         struct domainlist *domlist = NULL;
874                         int d;
875                         struct state *to = st;
876                         unsigned long long min_size;
877
878                         if (to->parent_dev != NoMdDev && !to->parent)
879                                 /* subarray monitored without parent container
880                                  * we can't move spares here */
881                                 continue;
882                         
883                         if (to->parent)
884                                 /* member of a container */
885                                 to = to->parent;
886
887                         if (get_min_spare_size_required(to, &min_size))
888                                 continue;
889                         if (to->metadata->ss->external) {
890                                 /* We must make sure there is
891                                  * no suitable spare in container already.
892                                  * If there is we don't add more */
893                                 dev_t devid = container_choose_spare(
894                                         to, to, NULL, min_size, st->active);
895                                 if (devid > 0)
896                                         continue;
897                         }
898                         for (d = 0; d < MaxDisks; d++)
899                                 if (to->devid[d])
900                                         domainlist_add_dev(&domlist,
901                                                            to->devid[d],
902                                                            to->metadata->ss->name);
903                         if (to->spare_group)
904                                 domain_add(&domlist, to->spare_group);
905                         /*
906                          * No spare migration if the destination
907                          * has no domain. Skip this array.
908                          */
909                         if (!domlist)
910                                 continue;
911                         for (from=statelist ; from ; from=from->next) {
912                                 dev_t devid;
913                                 if (!check_donor(from, to))
914                                         continue;
915                                 if (from->metadata->ss->external)
916                                         devid = container_choose_spare(
917                                                 from, to, domlist, min_size, 0);
918                                 else
919                                         devid = choose_spare(from, to, domlist,
920                                                              min_size);
921                                 if (devid > 0
922                                     && move_spare(from->devname, to->devname, devid)) {
923                                         alert("MoveSpare", to->devname, from->devname, info);
924                                         break;
925                                 }
926                         }
927                         domain_free(domlist);
928                 }
929 }
930
931 /* search the statelist to connect external
932  * metadata subarrays with their containers
933  * We always completely rebuild the tree from scratch as
934  * that is safest considering the possibility of entries
935  * disappearing or changing.
936  */
937 static void link_containers_with_subarrays(struct state *list)
938 {
939         struct state *st;
940         struct state *cont;
941         for (st = list; st; st = st->next) {
942                 st->parent = NULL;
943                 st->subarray = NULL;
944         }
945         for (st = list; st; st = st->next)
946                 if (st->parent_dev != NoMdDev)
947                         for (cont = list; cont; cont = cont->next)
948                                 if (!cont->err &&
949                                     cont->parent_dev == NoMdDev &&
950                                     cont->devnum == st->parent_dev) {
951                                         st->parent = cont;
952                                         st->subarray = cont->subarray;
953                                         cont->subarray = st;
954                                         break;
955                                 }
956 }
957
958 /* Not really Monitor but ... */
959 int Wait(char *dev)
960 {
961         struct stat stb;
962         int devnum;
963         int rv = 1;
964
965         if (stat(dev, &stb) != 0) {
966                 fprintf(stderr, Name ": Cannot find %s: %s\n", dev,
967                         strerror(errno));
968                 return 2;
969         }
970         devnum = stat2devnum(&stb);
971
972         while(1) {
973                 struct mdstat_ent *ms = mdstat_read(1, 0);
974                 struct mdstat_ent *e;
975
976                 for (e=ms ; e; e=e->next)
977                         if (e->devnum == devnum)
978                                 break;
979
980                 if (!e || e->percent < 0) {
981                         if (e && e->metadata_version &&
982                             strncmp(e->metadata_version, "external:", 9) == 0) {
983                                 if (is_subarray(&e->metadata_version[9]))
984                                         ping_monitor(&e->metadata_version[9]);
985                                 else
986                                         ping_monitor_by_id(devnum);
987                         }
988                         free_mdstat(ms);
989                         return rv;
990                 }
991                 free_mdstat(ms);
992                 rv = 0;
993                 mdstat_wait(5);
994         }
995 }
996
997 #ifndef MDASSEMBLE
998
999 static char *clean_states[] = {
1000         "clear", "inactive", "readonly", "read-auto", "clean", NULL };
1001
1002 int WaitClean(char *dev, int sock, int verbose)
1003 {
1004         int fd;
1005         struct mdinfo *mdi;
1006         int rv = 1;
1007         int devnum;
1008
1009         fd = open(dev, O_RDONLY);
1010         if (fd < 0) {
1011                 if (verbose)
1012                         fprintf(stderr, Name ": Couldn't open %s: %s\n", dev, strerror(errno));
1013                 return 1;
1014         }
1015
1016         devnum = fd2devnum(fd);
1017         mdi = sysfs_read(fd, devnum, GET_VERSION|GET_LEVEL|GET_SAFEMODE);
1018         if (!mdi) {
1019                 if (verbose)
1020                         fprintf(stderr, Name ": Failed to read sysfs attributes for "
1021                                 "%s\n", dev);
1022                 close(fd);
1023                 return 0;
1024         }
1025
1026         switch(mdi->array.level) {
1027         case LEVEL_LINEAR:
1028         case LEVEL_MULTIPATH:
1029         case 0:
1030                 /* safemode delay is irrelevant for these levels */
1031                 rv = 0;
1032         }
1033
1034         /* for internal metadata the kernel handles the final clean
1035          * transition, containers can never be dirty
1036          */
1037         if (!is_subarray(mdi->text_version))
1038                 rv = 0;
1039
1040         /* safemode disabled ? */
1041         if (mdi->safe_mode_delay == 0)
1042                 rv = 0;
1043
1044         if (rv) {
1045                 int state_fd = sysfs_open(fd2devnum(fd), NULL, "array_state");
1046                 char buf[20];
1047                 fd_set fds;
1048                 struct timeval tm;
1049
1050                 /* minimize the safe_mode_delay and prepare to wait up to 5s
1051                  * for writes to quiesce
1052                  */
1053                 sysfs_set_safemode(mdi, 1);
1054                 tm.tv_sec = 5;
1055                 tm.tv_usec = 0;
1056
1057                 FD_ZERO(&fds);
1058
1059                 /* wait for array_state to be clean */
1060                 while (1) {
1061                         rv = read(state_fd, buf, sizeof(buf));
1062                         if (rv < 0)
1063                                 break;
1064                         if (sysfs_match_word(buf, clean_states) <= 4)
1065                                 break;
1066                         FD_SET(state_fd, &fds);
1067                         rv = select(state_fd + 1, NULL, NULL, &fds, &tm);
1068                         if (rv < 0 && errno != EINTR)
1069                                 break;
1070                         lseek(state_fd, 0, SEEK_SET);
1071                 }
1072                 if (rv < 0)
1073                         rv = 1;
1074                 else if (fping_monitor(sock) == 0 ||
1075                          ping_monitor(mdi->text_version) == 0) {
1076                         /* we need to ping to close the window between array
1077                          * state transitioning to clean and the metadata being
1078                          * marked clean
1079                          */
1080                         rv = 0;
1081                 } else
1082                         rv = 1;
1083                 if (rv && verbose)
1084                         fprintf(stderr, Name ": Error waiting for %s to be clean\n",
1085                                 dev);
1086
1087                 /* restore the original safe_mode_delay */
1088                 sysfs_set_safemode(mdi, mdi->safe_mode_delay);
1089                 close(state_fd);
1090         }
1091
1092         sysfs_free(mdi);
1093         close(fd);
1094
1095         return rv;
1096 }
1097 #endif /* MDASSEMBLE */