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