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