multipathd: Implement systemd watchdog integration
[multipath-tools/.git] / multipathd / main.c
1 /*
2  * Copyright (c) 2004, 2005 Christophe Varoqui
3  * Copyright (c) 2005 Kiyoshi Ueda, NEC
4  * Copyright (c) 2005 Benjamin Marzinski, Redhat
5  * Copyright (c) 2005 Edward Goggin, EMC
6  */
7 #include <unistd.h>
8 #include <sys/stat.h>
9 #include <libdevmapper.h>
10 #include <wait.h>
11 #include <sys/mman.h>
12 #include <sys/types.h>
13 #include <fcntl.h>
14 #include <errno.h>
15 #include <sys/time.h>
16 #include <sys/resource.h>
17 #include <limits.h>
18 #include <linux/oom.h>
19 #include <libudev.h>
20 #ifdef USE_SYSTEMD
21 #include <systemd/sd-daemon.h>
22 #endif
23 #include <semaphore.h>
24 #include <mpath_persist.h>
25
26 /*
27  * libcheckers
28  */
29 #include <checkers.h>
30
31 /*
32  * libmultipath
33  */
34 #include <parser.h>
35 #include <vector.h>
36 #include <memory.h>
37 #include <config.h>
38 #include <util.h>
39 #include <hwtable.h>
40 #include <defaults.h>
41 #include <structs.h>
42 #include <blacklist.h>
43 #include <structs_vec.h>
44 #include <dmparser.h>
45 #include <devmapper.h>
46 #include <sysfs.h>
47 #include <dict.h>
48 #include <discovery.h>
49 #include <debug.h>
50 #include <propsel.h>
51 #include <uevent.h>
52 #include <switchgroup.h>
53 #include <print.h>
54 #include <configure.h>
55 #include <prio.h>
56 #include <pgpolicies.h>
57 #include <uevent.h>
58 #include <log.h>
59
60 #include "main.h"
61 #include "pidfile.h"
62 #include "uxlsnr.h"
63 #include "uxclnt.h"
64 #include "cli.h"
65 #include "cli_handlers.h"
66 #include "lock.h"
67 #include "waiter.h"
68 #include "wwids.h"
69
70 #define FILE_NAME_SIZE 256
71 #define CMDSIZE 160
72
73 #define LOG_MSG(a, b) \
74 do { \
75         if (pp->offline) \
76                 condlog(a, "%s: %s - path offline", pp->mpp->alias, pp->dev); \
77         else if (strlen(b)) \
78                 condlog(a, "%s: %s - %s", pp->mpp->alias, pp->dev, b); \
79 } while(0)
80
81 struct mpath_event_param
82 {
83         char * devname;
84         struct multipath *mpp;
85 };
86
87 unsigned int mpath_mx_alloc_len;
88
89 int logsink;
90 enum daemon_status running_state;
91 pid_t daemon_pid;
92
93 static sem_t exit_sem;
94 /*
95  * global copy of vecs for use in sig handlers
96  */
97 struct vectors * gvecs;
98
99 struct udev * udev;
100
101 static int
102 need_switch_pathgroup (struct multipath * mpp, int refresh)
103 {
104         struct pathgroup * pgp;
105         struct path * pp;
106         unsigned int i, j;
107
108         if (!mpp || mpp->pgfailback == -FAILBACK_MANUAL)
109                 return 0;
110
111         /*
112          * Refresh path priority values
113          */
114         if (refresh)
115                 vector_foreach_slot (mpp->pg, pgp, i)
116                         vector_foreach_slot (pgp->paths, pp, j)
117                                 pathinfo(pp, conf->hwtable, DI_PRIO);
118
119         mpp->bestpg = select_path_group(mpp);
120
121         if (mpp->bestpg != mpp->nextpg)
122                 return 1;
123
124         return 0;
125 }
126
127 static void
128 switch_pathgroup (struct multipath * mpp)
129 {
130         mpp->stat_switchgroup++;
131         dm_switchgroup(mpp->alias, mpp->bestpg);
132         condlog(2, "%s: switch to path group #%i",
133                  mpp->alias, mpp->bestpg);
134 }
135
136 static int
137 coalesce_maps(struct vectors *vecs, vector nmpv)
138 {
139         struct multipath * ompp;
140         vector ompv = vecs->mpvec;
141         unsigned int i;
142
143         vector_foreach_slot (ompv, ompp, i) {
144                 condlog(3, "%s: coalesce map", ompp->alias);
145                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
146                         /*
147                          * remove all current maps not allowed by the
148                          * current configuration
149                          */
150                         if (dm_flush_map(ompp->alias)) {
151                                 condlog(0, "%s: unable to flush devmap",
152                                         ompp->alias);
153                                 /*
154                                  * may be just because the device is open
155                                  */
156                                 if (setup_multipath(vecs, ompp) != 0) {
157                                         i--;
158                                         continue;
159                                 }
160                                 if (!vector_alloc_slot(nmpv))
161                                         return 1;
162
163                                 vector_set_slot(nmpv, ompp);
164
165                                 vector_del_slot(ompv, i);
166                                 i--;
167                         }
168                         else {
169                                 dm_lib_release();
170                                 condlog(2, "%s devmap removed", ompp->alias);
171                         }
172                 } else if (conf->reassign_maps) {
173                         condlog(3, "%s: Reassign existing device-mapper"
174                                 " devices", ompp->alias);
175                         dm_reassign(ompp->alias);
176                 }
177         }
178         return 0;
179 }
180
181 void
182 sync_map_state(struct multipath *mpp)
183 {
184         struct pathgroup *pgp;
185         struct path *pp;
186         unsigned int i, j;
187
188         if (!mpp->pg)
189                 return;
190
191         vector_foreach_slot (mpp->pg, pgp, i){
192                 vector_foreach_slot (pgp->paths, pp, j){
193                         if (pp->state == PATH_UNCHECKED || 
194                             pp->state == PATH_WILD)
195                                 continue;
196                         if ((pp->dmstate == PSTATE_FAILED ||
197                              pp->dmstate == PSTATE_UNDEF) &&
198                             (pp->state == PATH_UP || pp->state == PATH_GHOST))
199                                 dm_reinstate_path(mpp->alias, pp->dev_t);
200                         else if ((pp->dmstate == PSTATE_ACTIVE ||
201                                   pp->dmstate == PSTATE_UNDEF) &&
202                                  (pp->state == PATH_DOWN ||
203                                   pp->state == PATH_SHAKY))
204                                 dm_fail_path(mpp->alias, pp->dev_t);
205                 }
206         }
207 }
208
209 static void
210 sync_maps_state(vector mpvec)
211 {
212         unsigned int i;
213         struct multipath *mpp;
214
215         vector_foreach_slot (mpvec, mpp, i)
216                 sync_map_state(mpp);
217 }
218
219 static int
220 flush_map(struct multipath * mpp, struct vectors * vecs)
221 {
222         /*
223          * clear references to this map before flushing so we can ignore
224          * the spurious uevent we may generate with the dm_flush_map call below
225          */
226         if (dm_flush_map(mpp->alias)) {
227                 /*
228                  * May not really be an error -- if the map was already flushed
229                  * from the device mapper by dmsetup(8) for instance.
230                  */
231                 condlog(0, "%s: can't flush", mpp->alias);
232                 return 1;
233         }
234         else {
235                 dm_lib_release();
236                 condlog(2, "%s: map flushed", mpp->alias);
237         }
238
239         orphan_paths(vecs->pathvec, mpp);
240         remove_map_and_stop_waiter(mpp, vecs, 1);
241
242         return 0;
243 }
244
245 static int
246 uev_add_map (struct uevent * uev, struct vectors * vecs)
247 {
248         char *alias;
249         int major = -1, minor = -1, rc;
250
251         condlog(3, "%s: add map (uevent)", uev->kernel);
252         alias = uevent_get_dm_name(uev);
253         if (!alias) {
254                 condlog(3, "%s: No DM_NAME in uevent", uev->kernel);
255                 major = uevent_get_major(uev);
256                 minor = uevent_get_minor(uev);
257                 alias = dm_mapname(major, minor);
258                 if (!alias) {
259                         condlog(2, "%s: mapname not found for %d:%d",
260                                 uev->kernel, major, minor);
261                         return 1;
262                 }
263         }
264         rc = ev_add_map(uev->kernel, alias, vecs);
265         FREE(alias);
266         return rc;
267 }
268
269 int
270 ev_add_map (char * dev, char * alias, struct vectors * vecs)
271 {
272         char * refwwid;
273         struct multipath * mpp;
274         int map_present;
275         int r = 1;
276
277         map_present = dm_map_present(alias);
278
279         if (map_present && dm_type(alias, TGT_MPATH) <= 0) {
280                 condlog(4, "%s: not a multipath map", alias);
281                 return 0;
282         }
283
284         mpp = find_mp_by_alias(vecs->mpvec, alias);
285
286         if (mpp) {
287                 /*
288                  * Not really an error -- we generate our own uevent
289                  * if we create a multipath mapped device as a result
290                  * of uev_add_path
291                  */
292                 if (conf->reassign_maps) {
293                         condlog(3, "%s: Reassign existing device-mapper devices",
294                                 alias);
295                         dm_reassign(alias);
296                 }
297                 return 0;
298         }
299         condlog(2, "%s: adding map", alias);
300
301         /*
302          * now we can register the map
303          */
304         if (map_present && (mpp = add_map_without_path(vecs, alias))) {
305                 sync_map_state(mpp);
306                 condlog(2, "%s: devmap %s registered", alias, dev);
307                 return 0;
308         }
309         r = get_refwwid(dev, DEV_DEVMAP, vecs->pathvec, &refwwid);
310
311         if (refwwid) {
312                 r = coalesce_paths(vecs, NULL, refwwid, 0);
313                 dm_lib_release();
314         }
315
316         if (!r)
317                 condlog(2, "%s: devmap %s added", alias, dev);
318         else if (r == 2)
319                 condlog(2, "%s: uev_add_map %s blacklisted", alias, dev);
320         else
321                 condlog(0, "%s: uev_add_map %s failed", alias, dev);
322
323         FREE(refwwid);
324         return r;
325 }
326
327 static int
328 uev_remove_map (struct uevent * uev, struct vectors * vecs)
329 {
330         char *alias;
331         int minor;
332         struct multipath *mpp;
333
334         condlog(2, "%s: remove map (uevent)", uev->kernel);
335         alias = uevent_get_dm_name(uev);
336         if (!alias) {
337                 condlog(3, "%s: No DM_NAME in uevent, ignoring", uev->kernel);
338                 return 0;
339         }
340         minor = uevent_get_minor(uev);
341         mpp = find_mp_by_minor(vecs->mpvec, minor);
342
343         if (!mpp) {
344                 condlog(2, "%s: devmap not registered, can't remove",
345                         uev->kernel);
346                 goto out;
347         }
348         if (strcmp(mpp->alias, alias)) {
349                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
350                         mpp->alias, mpp->dmi->minor, minor);
351                 goto out;
352         }
353
354         orphan_paths(vecs->pathvec, mpp);
355         remove_map_and_stop_waiter(mpp, vecs, 1);
356 out:
357         FREE(alias);
358         return 0;
359 }
360
361 int
362 ev_remove_map (char * devname, char * alias, int minor, struct vectors * vecs)
363 {
364         struct multipath * mpp;
365
366         mpp = find_mp_by_minor(vecs->mpvec, minor);
367
368         if (!mpp) {
369                 condlog(2, "%s: devmap not registered, can't remove",
370                         devname);
371                 return 0;
372         }
373         if (strcmp(mpp->alias, alias)) {
374                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
375                         mpp->alias, mpp->dmi->minor, minor);
376                 return 0;
377         }
378         return flush_map(mpp, vecs);
379 }
380
381 static int
382 uev_add_path (struct uevent *uev, struct vectors * vecs)
383 {
384         struct path *pp;
385         int ret, i;
386
387         condlog(2, "%s: add path (uevent)", uev->kernel);
388         if (strstr(uev->kernel, "..") != NULL) {
389                 /*
390                  * Don't allow relative device names in the pathvec
391                  */
392                 condlog(0, "%s: path name is invalid", uev->kernel);
393                 return 1;
394         }
395
396         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
397         if (pp) {
398                 condlog(0, "%s: spurious uevent, path already in pathvec",
399                         uev->kernel);
400                 if (pp->mpp)
401                         return 0;
402                 if (!strlen(pp->wwid)) {
403                         udev_device_unref(pp->udev);
404                         pp->udev = udev_device_ref(uev->udev);
405                         ret = pathinfo(pp, conf->hwtable,
406                                        DI_ALL | DI_BLACKLIST);
407                         if (ret == 2) {
408                                 i = find_slot(vecs->pathvec, (void *)pp);
409                                 if (i != -1)
410                                         vector_del_slot(vecs->pathvec, i);
411                                 free_path(pp);
412                                 return 0;
413                         } else if (ret == 1) {
414                                 condlog(0, "%s: failed to reinitialize path",
415                                         uev->kernel);
416                                 return 1;
417                         }
418                 }
419         } else {
420                 /*
421                  * get path vital state
422                  */
423                 ret = store_pathinfo(vecs->pathvec, conf->hwtable,
424                                      uev->udev, DI_ALL, &pp);
425                 if (!pp) {
426                         if (ret == 2)
427                                 return 0;
428                         condlog(0, "%s: failed to store path info",
429                                 uev->kernel);
430                         return 1;
431                 }
432                 pp->checkint = conf->checkint;
433         }
434
435         return ev_add_path(pp, vecs);
436 }
437
438 /*
439  * returns:
440  * 0: added
441  * 1: error
442  */
443 int
444 ev_add_path (struct path * pp, struct vectors * vecs)
445 {
446         struct multipath * mpp;
447         char empty_buff[WWID_SIZE] = {0};
448         char params[PARAMS_SIZE] = {0};
449         int retries = 3;
450         int start_waiter = 0;
451
452         /*
453          * need path UID to go any further
454          */
455         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
456                 condlog(0, "%s: failed to get path uid", pp->dev);
457                 goto fail; /* leave path added to pathvec */
458         }
459         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
460 rescan:
461         if (mpp) {
462                 if ((!pp->size) || (mpp->size != pp->size)) {
463                         if (!pp->size)
464                                 condlog(0, "%s: failed to add new path %s, "
465                                         "device size is 0",
466                                         mpp->alias, pp->dev);
467                         else
468                                 condlog(0, "%s: failed to add new path %s, "
469                                         "device size mismatch",
470                                         mpp->alias, pp->dev);
471                         int i = find_slot(vecs->pathvec, (void *)pp);
472                         if (i != -1)
473                                 vector_del_slot(vecs->pathvec, i);
474                         free_path(pp);
475                         return 1;
476                 }
477
478                 condlog(4,"%s: adopting all paths for path %s",
479                         mpp->alias, pp->dev);
480                 if (adopt_paths(vecs->pathvec, mpp, 1))
481                         goto fail; /* leave path added to pathvec */
482
483                 verify_paths(mpp, vecs, NULL);
484                 mpp->flush_on_last_del = FLUSH_UNDEF;
485                 mpp->action = ACT_RELOAD;
486         }
487         else {
488                 if (!pp->size) {
489                         condlog(0, "%s: failed to create new map,"
490                                 " device size is 0 ", pp->dev);
491                         int i = find_slot(vecs->pathvec, (void *)pp);
492                         if (i != -1)
493                                 vector_del_slot(vecs->pathvec, i);
494                         free_path(pp);
495                         return 1;
496                 }
497
498                 condlog(4,"%s: creating new map", pp->dev);
499                 if ((mpp = add_map_with_path(vecs, pp, 1))) {
500                         mpp->action = ACT_CREATE;
501                         /*
502                          * We don't depend on ACT_CREATE, as domap will
503                          * set it to ACT_NOTHING when complete.
504                          */
505                         start_waiter = 1;
506                 }
507                 else
508                         goto fail; /* leave path added to pathvec */
509         }
510
511         /* persistent reseravtion check*/
512         mpath_pr_event_handle(pp);      
513
514         /*
515          * push the map to the device-mapper
516          */
517         if (setup_map(mpp, params, PARAMS_SIZE)) {
518                 condlog(0, "%s: failed to setup map for addition of new "
519                         "path %s", mpp->alias, pp->dev);
520                 goto fail_map;
521         }
522         /*
523          * reload the map for the multipath mapped device
524          */
525         if (domap(mpp, params) <= 0) {
526                 condlog(0, "%s: failed in domap for addition of new "
527                         "path %s", mpp->alias, pp->dev);
528                 /*
529                  * deal with asynchronous uevents :((
530                  */
531                 if (mpp->action == ACT_RELOAD && retries-- > 0) {
532                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
533                         sleep(1);
534                         update_mpp_paths(mpp, vecs->pathvec);
535                         goto rescan;
536                 }
537                 else if (mpp->action == ACT_RELOAD)
538                         condlog(0, "%s: giving up reload", mpp->alias);
539                 else
540                         goto fail_map;
541         }
542         dm_lib_release();
543
544         /*
545          * update our state from kernel regardless of create or reload
546          */
547         if (setup_multipath(vecs, mpp))
548                 goto fail; /* if setup_multipath fails, it removes the map */
549
550         sync_map_state(mpp);
551
552         if ((mpp->action == ACT_CREATE ||
553              (mpp->action == ACT_NOTHING && start_waiter && !mpp->waiter)) &&
554             start_waiter_thread(mpp, vecs))
555                         goto fail_map;
556
557         if (retries >= 0) {
558                 condlog(2, "%s [%s]: path added to devmap %s",
559                         pp->dev, pp->dev_t, mpp->alias);
560                 return 0;
561         }
562         else
563                 return 1;
564
565 fail_map:
566         remove_map(mpp, vecs, 1);
567 fail:
568         orphan_path(pp, "failed to add path");
569         return 1;
570 }
571
572 static int
573 uev_remove_path (struct uevent *uev, struct vectors * vecs)
574 {
575         struct path *pp;
576
577         condlog(2, "%s: remove path (uevent)", uev->kernel);
578         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
579
580         if (!pp) {
581                 /* Not an error; path might have been purged earlier */
582                 condlog(0, "%s: path already removed", uev->kernel);
583                 return 0;
584         }
585
586         return ev_remove_path(pp, vecs);
587 }
588
589 int
590 ev_remove_path (struct path *pp, struct vectors * vecs)
591 {
592         struct multipath * mpp;
593         int i, retval = 0;
594         char params[PARAMS_SIZE] = {0};
595
596         /*
597          * avoid referring to the map of an orphaned path
598          */
599         if ((mpp = pp->mpp)) {
600                 /*
601                  * transform the mp->pg vector of vectors of paths
602                  * into a mp->params string to feed the device-mapper
603                  */
604                 if (update_mpp_paths(mpp, vecs->pathvec)) {
605                         condlog(0, "%s: failed to update paths",
606                                 mpp->alias);
607                         goto fail;
608                 }
609                 if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
610                         vector_del_slot(mpp->paths, i);
611
612                 /*
613                  * remove the map IFF removing the last path
614                  */
615                 if (VECTOR_SIZE(mpp->paths) == 0) {
616                         char alias[WWID_SIZE];
617
618                         /*
619                          * flush_map will fail if the device is open
620                          */
621                         strncpy(alias, mpp->alias, WWID_SIZE);
622                         if (mpp->flush_on_last_del == FLUSH_ENABLED) {
623                                 condlog(2, "%s Last path deleted, disabling queueing", mpp->alias);
624                                 mpp->retry_tick = 0;
625                                 mpp->no_path_retry = NO_PATH_RETRY_FAIL;
626                                 mpp->flush_on_last_del = FLUSH_IN_PROGRESS;
627                                 dm_queue_if_no_path(mpp->alias, 0);
628                         }
629                         if (!flush_map(mpp, vecs)) {
630                                 condlog(2, "%s: removed map after"
631                                         " removing all paths",
632                                         alias);
633                                 retval = 0;
634                                 goto out;
635                         }
636                         /*
637                          * Not an error, continue
638                          */
639                 }
640
641                 if (setup_map(mpp, params, PARAMS_SIZE)) {
642                         condlog(0, "%s: failed to setup map for"
643                                 " removal of path %s", mpp->alias, pp->dev);
644                         goto fail;
645                 }
646                 /*
647                  * reload the map
648                  */
649                 mpp->action = ACT_RELOAD;
650                 if (domap(mpp, params) <= 0) {
651                         condlog(0, "%s: failed in domap for "
652                                 "removal of path %s",
653                                 mpp->alias, pp->dev);
654                         retval = 1;
655                 } else {
656                         /*
657                          * update our state from kernel
658                          */
659                         if (setup_multipath(vecs, mpp)) {
660                                 goto fail;
661                         }
662                         sync_map_state(mpp);
663
664                         condlog(2, "%s [%s]: path removed from map %s",
665                                 pp->dev, pp->dev_t, mpp->alias);
666                 }
667         }
668
669 out:
670         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
671                 vector_del_slot(vecs->pathvec, i);
672
673         free_path(pp);
674
675         return retval;
676
677 fail:
678         remove_map_and_stop_waiter(mpp, vecs, 1);
679         return 1;
680 }
681
682 static int
683 uev_update_path (struct uevent *uev, struct vectors * vecs)
684 {
685         int ro, retval = 0;
686
687         ro = uevent_get_disk_ro(uev);
688
689         if (ro >= 0) {
690                 struct path * pp;
691
692                 condlog(2, "%s: update path write_protect to '%d' (uevent)",
693                         uev->kernel, ro);
694                 pp = find_path_by_dev(vecs->pathvec, uev->kernel);
695                 if (!pp) {
696                         condlog(0, "%s: spurious uevent, path not found",
697                                 uev->kernel);
698                         return 1;
699                 }
700                 if (pp->mpp) {
701                         retval = reload_map(vecs, pp->mpp, 0);
702
703                         condlog(2, "%s: map %s reloaded (retval %d)",
704                                 uev->kernel, pp->mpp->alias, retval);
705                 }
706
707         }
708
709         return retval;
710 }
711
712 static int
713 map_discovery (struct vectors * vecs)
714 {
715         struct multipath * mpp;
716         unsigned int i;
717
718         if (dm_get_maps(vecs->mpvec))
719                 return 1;
720
721         vector_foreach_slot (vecs->mpvec, mpp, i)
722                 if (setup_multipath(vecs, mpp))
723                         return 1;
724
725         return 0;
726 }
727
728 int
729 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
730 {
731         struct vectors * vecs;
732         int r;
733
734         *reply = NULL;
735         *len = 0;
736         vecs = (struct vectors *)trigger_data;
737
738         pthread_cleanup_push(cleanup_lock, &vecs->lock);
739         lock(vecs->lock);
740         pthread_testcancel();
741
742         r = parse_cmd(str, reply, len, vecs);
743
744         if (r > 0) {
745                 *reply = STRDUP("fail\n");
746                 *len = strlen(*reply) + 1;
747                 r = 1;
748         }
749         else if (!r && *len == 0) {
750                 *reply = STRDUP("ok\n");
751                 *len = strlen(*reply) + 1;
752                 r = 0;
753         }
754         /* else if (r < 0) leave *reply alone */
755
756         lock_cleanup_pop(vecs->lock);
757         return r;
758 }
759
760 static int
761 uev_discard(char * devpath)
762 {
763         char *tmp;
764         char a[11], b[11];
765
766         /*
767          * keep only block devices, discard partitions
768          */
769         tmp = strstr(devpath, "/block/");
770         if (tmp == NULL){
771                 condlog(4, "no /block/ in '%s'", devpath);
772                 return 1;
773         }
774         if (sscanf(tmp, "/block/%10s", a) != 1 ||
775             sscanf(tmp, "/block/%10[^/]/%10s", a, b) == 2) {
776                 condlog(4, "discard event on %s", devpath);
777                 return 1;
778         }
779         return 0;
780 }
781
782 int
783 uev_trigger (struct uevent * uev, void * trigger_data)
784 {
785         int r = 0;
786         struct vectors * vecs;
787
788         vecs = (struct vectors *)trigger_data;
789
790         if (uev_discard(uev->devpath))
791                 return 0;
792
793         pthread_cleanup_push(cleanup_lock, &vecs->lock);
794         lock(vecs->lock);
795         pthread_testcancel();
796
797         /*
798          * device map event
799          * Add events are ignored here as the tables
800          * are not fully initialised then.
801          */
802         if (!strncmp(uev->kernel, "dm-", 3)) {
803                 if (!strncmp(uev->action, "change", 6)) {
804                         r = uev_add_map(uev, vecs);
805                         goto out;
806                 }
807                 if (!strncmp(uev->action, "remove", 6)) {
808                         r = uev_remove_map(uev, vecs);
809                         goto out;
810                 }
811                 goto out;
812         }
813
814         /*
815          * path add/remove event
816          */
817         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
818                            uev->kernel) > 0)
819                 goto out;
820
821         if (!strncmp(uev->action, "add", 3)) {
822                 r = uev_add_path(uev, vecs);
823                 goto out;
824         }
825         if (!strncmp(uev->action, "remove", 6)) {
826                 r = uev_remove_path(uev, vecs);
827                 goto out;
828         }
829         if (!strncmp(uev->action, "change", 6)) {
830                 r = uev_update_path(uev, vecs);
831                 goto out;
832         }
833
834 out:
835         lock_cleanup_pop(vecs->lock);
836         return r;
837 }
838
839 static void *
840 ueventloop (void * ap)
841 {
842         if (uevent_listen(udev))
843                 condlog(0, "error starting uevent listener");
844
845         return NULL;
846 }
847
848 static void *
849 uevqloop (void * ap)
850 {
851         if (uevent_dispatch(&uev_trigger, ap))
852                 condlog(0, "error starting uevent dispatcher");
853
854         return NULL;
855 }
856 static void *
857 uxlsnrloop (void * ap)
858 {
859         if (cli_init())
860                 return NULL;
861
862         set_handler_callback(LIST+PATHS, cli_list_paths);
863         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
864         set_handler_callback(LIST+MAPS, cli_list_maps);
865         set_handler_callback(LIST+STATUS, cli_list_status);
866         set_handler_callback(LIST+DAEMON, cli_list_daemon);
867         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
868         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
869         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
870         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
871         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
872         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
873         set_handler_callback(LIST+CONFIG, cli_list_config);
874         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
875         set_handler_callback(LIST+DEVICES, cli_list_devices);
876         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
877         set_handler_callback(ADD+PATH, cli_add_path);
878         set_handler_callback(DEL+PATH, cli_del_path);
879         set_handler_callback(ADD+MAP, cli_add_map);
880         set_handler_callback(DEL+MAP, cli_del_map);
881         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
882         set_handler_callback(RECONFIGURE, cli_reconfigure);
883         set_handler_callback(SUSPEND+MAP, cli_suspend);
884         set_handler_callback(RESUME+MAP, cli_resume);
885         set_handler_callback(RESIZE+MAP, cli_resize);
886         set_handler_callback(RELOAD+MAP, cli_reload);
887         set_handler_callback(RESET+MAP, cli_reassign);
888         set_handler_callback(REINSTATE+PATH, cli_reinstate);
889         set_handler_callback(FAIL+PATH, cli_fail);
890         set_handler_callback(DISABLEQ+MAP, cli_disable_queueing);
891         set_handler_callback(RESTOREQ+MAP, cli_restore_queueing);
892         set_handler_callback(DISABLEQ+MAPS, cli_disable_all_queueing);
893         set_handler_callback(RESTOREQ+MAPS, cli_restore_all_queueing);
894         set_handler_callback(QUIT, cli_quit);
895         set_handler_callback(SHUTDOWN, cli_shutdown);
896         set_handler_callback(GETPRSTATUS+MAP, cli_getprstatus);
897         set_handler_callback(SETPRSTATUS+MAP, cli_setprstatus);
898         set_handler_callback(UNSETPRSTATUS+MAP, cli_unsetprstatus);
899         set_handler_callback(FORCEQ+DAEMON, cli_force_no_daemon_q);
900         set_handler_callback(RESTOREQ+DAEMON, cli_restore_no_daemon_q);
901
902         umask(077);
903         uxsock_listen(&uxsock_trigger, ap);
904
905         return NULL;
906 }
907
908 void
909 exit_daemon (void)
910 {
911         sem_post(&exit_sem);
912 }
913
914 const char *
915 daemon_status(void)
916 {
917         switch (running_state) {
918         case DAEMON_INIT:
919                 return "init";
920         case DAEMON_START:
921                 return "startup";
922         case DAEMON_CONFIGURE:
923                 return "configure";
924         case DAEMON_RUNNING:
925                 return "running";
926         case DAEMON_SHUTDOWN:
927                 return "shutdown";
928         }
929         return NULL;
930 }
931
932 static void
933 fail_path (struct path * pp, int del_active)
934 {
935         if (!pp->mpp)
936                 return;
937
938         condlog(2, "checker failed path %s in map %s",
939                  pp->dev_t, pp->mpp->alias);
940
941         dm_fail_path(pp->mpp->alias, pp->dev_t);
942         if (del_active)
943                 update_queue_mode_del_path(pp->mpp);
944 }
945
946 /*
947  * caller must have locked the path list before calling that function
948  */
949 static void
950 reinstate_path (struct path * pp, int add_active)
951 {
952         if (!pp->mpp)
953                 return;
954
955         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
956                 condlog(0, "%s: reinstate failed", pp->dev_t);
957         else {
958                 condlog(2, "%s: reinstated", pp->dev_t);
959                 if (add_active)
960                         update_queue_mode_add_path(pp->mpp);
961         }
962 }
963
964 static void
965 enable_group(struct path * pp)
966 {
967         struct pathgroup * pgp;
968
969         /*
970          * if path is added through uev_add_path, pgindex can be unset.
971          * next update_strings() will set it, upon map reload event.
972          *
973          * we can safely return here, because upon map reload, all
974          * PG will be enabled.
975          */
976         if (!pp->mpp->pg || !pp->pgindex)
977                 return;
978
979         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
980
981         if (pgp->status == PGSTATE_DISABLED) {
982                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
983                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
984         }
985 }
986
987 static void
988 mpvec_garbage_collector (struct vectors * vecs)
989 {
990         struct multipath * mpp;
991         unsigned int i;
992
993         if (!vecs->mpvec)
994                 return;
995
996         vector_foreach_slot (vecs->mpvec, mpp, i) {
997                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
998                         condlog(2, "%s: remove dead map", mpp->alias);
999                         remove_map_and_stop_waiter(mpp, vecs, 1);
1000                         i--;
1001                 }
1002         }
1003 }
1004
1005 /* This is called after a path has started working again. It the multipath
1006  * device for this path uses the followover failback type, and this is the
1007  * best pathgroup, and this is the first path in the pathgroup to come back
1008  * up, then switch to this pathgroup */
1009 static int
1010 followover_should_failback(struct path * pp)
1011 {
1012         struct pathgroup * pgp;
1013         struct path *pp1;
1014         int i;
1015
1016         if (pp->mpp->pgfailback != -FAILBACK_FOLLOWOVER ||
1017             !pp->mpp->pg || !pp->pgindex ||
1018             pp->pgindex != pp->mpp->bestpg)
1019                 return 0;
1020
1021         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1022         vector_foreach_slot(pgp->paths, pp1, i) {
1023                 if (pp1 == pp)
1024                         continue;
1025                 if (pp1->chkrstate != PATH_DOWN && pp1->chkrstate != PATH_SHAKY)
1026                         return 0;
1027         }
1028         return 1;
1029 }
1030
1031 static void
1032 defered_failback_tick (vector mpvec)
1033 {
1034         struct multipath * mpp;
1035         unsigned int i;
1036
1037         vector_foreach_slot (mpvec, mpp, i) {
1038                 /*
1039                  * defered failback getting sooner
1040                  */
1041                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1042                         mpp->failback_tick--;
1043
1044                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1045                                 switch_pathgroup(mpp);
1046                 }
1047         }
1048 }
1049
1050 static void
1051 retry_count_tick(vector mpvec)
1052 {
1053         struct multipath *mpp;
1054         unsigned int i;
1055
1056         vector_foreach_slot (mpvec, mpp, i) {
1057                 if (mpp->retry_tick) {
1058                         mpp->stat_total_queueing_time++;
1059                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1060                         if(--mpp->retry_tick == 0) {
1061                                 dm_queue_if_no_path(mpp->alias, 0);
1062                                 condlog(2, "%s: Disable queueing", mpp->alias);
1063                         }
1064                 }
1065         }
1066 }
1067
1068 int update_prio(struct path *pp, int refresh_all)
1069 {
1070         int oldpriority;
1071         struct path *pp1;
1072         struct pathgroup * pgp;
1073         int i, j, changed = 0;
1074
1075         if (refresh_all) {
1076                 vector_foreach_slot (pp->mpp->pg, pgp, i) {
1077                         vector_foreach_slot (pgp->paths, pp1, j) {
1078                                 oldpriority = pp1->priority;
1079                                 pathinfo(pp1, conf->hwtable, DI_PRIO);
1080                                 if (pp1->priority != oldpriority)
1081                                         changed = 1;
1082                         }
1083                 }
1084                 return changed;
1085         }
1086         oldpriority = pp->priority;
1087         pathinfo(pp, conf->hwtable, DI_PRIO);
1088
1089         if (pp->priority == oldpriority)
1090                 return 0;
1091         return 1;
1092 }
1093
1094 int update_path_groups(struct multipath *mpp, struct vectors *vecs, int refresh)
1095 {
1096         if (reload_map(vecs, mpp, refresh))
1097                 return 1;
1098
1099         dm_lib_release();
1100         if (setup_multipath(vecs, mpp) != 0)
1101                 return 1;
1102         sync_map_state(mpp);
1103
1104         return 0;
1105 }
1106
1107 int
1108 check_path (struct vectors * vecs, struct path * pp)
1109 {
1110         int newstate;
1111         int new_path_up = 0;
1112         int chkr_new_path_up = 0;
1113         int oldchkrstate = pp->chkrstate;
1114
1115         if (!pp->mpp)
1116                 return 0;
1117
1118         if (pp->tick && --pp->tick)
1119                 return 0; /* don't check this path yet */
1120
1121         /*
1122          * provision a next check soonest,
1123          * in case we exit abnormaly from here
1124          */
1125         pp->tick = conf->checkint;
1126
1127         newstate = path_offline(pp);
1128         if (newstate == PATH_UP)
1129                 newstate = get_state(pp, 1);
1130
1131         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1132                 condlog(2, "%s: unusable path", pp->dev);
1133                 pathinfo(pp, conf->hwtable, 0);
1134                 return 1;
1135         }
1136         /*
1137          * Async IO in flight. Keep the previous path state
1138          * and reschedule as soon as possible
1139          */
1140         if (newstate == PATH_PENDING) {
1141                 pp->tick = 1;
1142                 return 0;
1143         }
1144         /*
1145          * Synchronize with kernel state
1146          */
1147         if (update_multipath_strings(pp->mpp, vecs->pathvec)) {
1148                 condlog(1, "%s: Could not synchronize with kernel state",
1149                         pp->dev);
1150                 pp->dmstate = PSTATE_UNDEF;
1151         }
1152         pp->chkrstate = newstate;
1153         if (newstate != pp->state) {
1154                 int oldstate = pp->state;
1155                 pp->state = newstate;
1156                 LOG_MSG(1, checker_message(&pp->checker));
1157
1158                 /*
1159                  * upon state change, reset the checkint
1160                  * to the shortest delay
1161                  */
1162                 pp->checkint = conf->checkint;
1163
1164                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY) {
1165                         /*
1166                          * proactively fail path in the DM
1167                          */
1168                         if (oldstate == PATH_UP ||
1169                             oldstate == PATH_GHOST)
1170                                 fail_path(pp, 1);
1171                         else
1172                                 fail_path(pp, 0);
1173
1174                         /*
1175                          * cancel scheduled failback
1176                          */
1177                         pp->mpp->failback_tick = 0;
1178
1179                         pp->mpp->stat_path_failures++;
1180                         return 1;
1181                 }
1182
1183                 if(newstate == PATH_UP || newstate == PATH_GHOST){
1184                         if ( pp->mpp && pp->mpp->prflag ){
1185                                 /*
1186                                  * Check Persistent Reservation.
1187                                  */
1188                         condlog(2, "%s: checking persistent reservation "
1189                                 "registration", pp->dev);
1190                         mpath_pr_event_handle(pp);
1191                         }
1192                 }
1193
1194                 /*
1195                  * reinstate this path
1196                  */
1197                 if (oldstate != PATH_UP &&
1198                     oldstate != PATH_GHOST)
1199                         reinstate_path(pp, 1);
1200                 else
1201                         reinstate_path(pp, 0);
1202
1203                 new_path_up = 1;
1204
1205                 if (oldchkrstate != PATH_UP && oldchkrstate != PATH_GHOST)
1206                         chkr_new_path_up = 1;
1207
1208                 /*
1209                  * if at least one path is up in a group, and
1210                  * the group is disabled, re-enable it
1211                  */
1212                 if (newstate == PATH_UP)
1213                         enable_group(pp);
1214         }
1215         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1216                 if (pp->dmstate == PSTATE_FAILED ||
1217                     pp->dmstate == PSTATE_UNDEF) {
1218                         /* Clear IO errors */
1219                         reinstate_path(pp, 0);
1220                 } else {
1221                         LOG_MSG(4, checker_message(&pp->checker));
1222                         if (pp->checkint != conf->max_checkint) {
1223                                 /*
1224                                  * double the next check delay.
1225                                  * max at conf->max_checkint
1226                                  */
1227                                 if (pp->checkint < (conf->max_checkint / 2))
1228                                         pp->checkint = 2 * pp->checkint;
1229                                 else
1230                                         pp->checkint = conf->max_checkint;
1231
1232                                 condlog(4, "%s: delay next check %is",
1233                                         pp->dev_t, pp->checkint);
1234                         }
1235                         pp->tick = pp->checkint;
1236                 }
1237         }
1238         else if (newstate == PATH_DOWN) {
1239                 if (conf->log_checker_err == LOG_CHKR_ERR_ONCE)
1240                         LOG_MSG(3, checker_message(&pp->checker));
1241                 else
1242                         LOG_MSG(2, checker_message(&pp->checker));
1243         }
1244
1245         pp->state = newstate;
1246
1247         /*
1248          * path prio refreshing
1249          */
1250         condlog(4, "path prio refresh");
1251
1252         if (update_prio(pp, new_path_up) &&
1253             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
1254              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1255                 update_path_groups(pp->mpp, vecs, !new_path_up);
1256         else if (need_switch_pathgroup(pp->mpp, 0)) {
1257                 if (pp->mpp->pgfailback > 0 &&
1258                     (new_path_up || pp->mpp->failback_tick <= 0))
1259                         pp->mpp->failback_tick =
1260                                 pp->mpp->pgfailback + 1;
1261                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE ||
1262                          (chkr_new_path_up && followover_should_failback(pp)))
1263                         switch_pathgroup(pp->mpp);
1264         }
1265         return 1;
1266 }
1267
1268 static void *
1269 checkerloop (void *ap)
1270 {
1271         struct vectors *vecs;
1272         struct path *pp;
1273         int count = 0;
1274         unsigned int i;
1275
1276         mlockall(MCL_CURRENT | MCL_FUTURE);
1277         vecs = (struct vectors *)ap;
1278         condlog(2, "path checkers start up");
1279
1280         /*
1281          * init the path check interval
1282          */
1283         vector_foreach_slot (vecs->pathvec, pp, i) {
1284                 pp->checkint = conf->checkint;
1285         }
1286
1287         while (1) {
1288                 struct timeval diff_time, start_time, end_time;
1289                 int num_paths = 0;
1290
1291                 if (gettimeofday(&start_time, NULL) != 0)
1292                         start_time.tv_sec = 0;
1293                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1294                 lock(vecs->lock);
1295                 pthread_testcancel();
1296                 condlog(4, "tick");
1297 #ifdef USE_SYSTEMD
1298                 if (conf->watchdog)
1299                         sd_notify(0, "WATCHDOG=1");
1300 #endif
1301                 if (vecs->pathvec) {
1302                         vector_foreach_slot (vecs->pathvec, pp, i) {
1303                                 num_paths += check_path(vecs, pp);
1304                         }
1305                 }
1306                 if (vecs->mpvec) {
1307                         defered_failback_tick(vecs->mpvec);
1308                         retry_count_tick(vecs->mpvec);
1309                 }
1310                 if (count)
1311                         count--;
1312                 else {
1313                         condlog(4, "map garbage collection");
1314                         mpvec_garbage_collector(vecs);
1315                         count = MAPGCINT;
1316                 }
1317
1318                 lock_cleanup_pop(vecs->lock);
1319                 if (start_time.tv_sec &&
1320                     gettimeofday(&end_time, NULL) == 0 &&
1321                     num_paths) {
1322                         timersub(&end_time, &start_time, &diff_time);
1323                         condlog(3, "checked %d path%s in %lu.%06lu secs",
1324                                 num_paths, num_paths > 1 ? "s" : "",
1325                                 diff_time.tv_sec, diff_time.tv_usec);
1326                 }
1327                 sleep(1);
1328         }
1329         return NULL;
1330 }
1331
1332 int
1333 configure (struct vectors * vecs, int start_waiters)
1334 {
1335         struct multipath * mpp;
1336         struct path * pp;
1337         vector mpvec;
1338         int i;
1339
1340         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1341                 return 1;
1342
1343         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1344                 return 1;
1345
1346         if (!(mpvec = vector_alloc()))
1347                 return 1;
1348
1349         /*
1350          * probe for current path (from sysfs) and map (from dm) sets
1351          */
1352         path_discovery(vecs->pathvec, conf, DI_ALL);
1353
1354         vector_foreach_slot (vecs->pathvec, pp, i){
1355                 if (filter_path(conf, pp) > 0){
1356                         vector_del_slot(vecs->pathvec, i);
1357                         free_path(pp);
1358                         i--;
1359                 }
1360                 else
1361                         pp->checkint = conf->checkint;
1362         }
1363         if (map_discovery(vecs))
1364                 return 1;
1365
1366         /*
1367          * create new set of maps & push changed ones into dm
1368          */
1369         if (coalesce_paths(vecs, mpvec, NULL, 1))
1370                 return 1;
1371
1372         /*
1373          * may need to remove some maps which are no longer relevant
1374          * e.g., due to blacklist changes in conf file
1375          */
1376         if (coalesce_maps(vecs, mpvec))
1377                 return 1;
1378
1379         dm_lib_release();
1380
1381         sync_maps_state(mpvec);
1382         vector_foreach_slot(mpvec, mpp, i){
1383                 remember_wwid(mpp->wwid);
1384                 update_map_pr(mpp);
1385         }
1386
1387         /*
1388          * purge dm of old maps
1389          */
1390         remove_maps(vecs);
1391
1392         /*
1393          * save new set of maps formed by considering current path state
1394          */
1395         vector_free(vecs->mpvec);
1396         vecs->mpvec = mpvec;
1397
1398         /*
1399          * start dm event waiter threads for these new maps
1400          */
1401         vector_foreach_slot(vecs->mpvec, mpp, i) {
1402                 if (setup_multipath(vecs, mpp))
1403                         return 1;
1404                 if (start_waiters)
1405                         if (start_waiter_thread(mpp, vecs))
1406                                 return 1;
1407         }
1408         return 0;
1409 }
1410
1411 int
1412 reconfigure (struct vectors * vecs)
1413 {
1414         struct config * old = conf;
1415         int retval = 1;
1416
1417         /*
1418          * free old map and path vectors ... they use old conf state
1419          */
1420         if (VECTOR_SIZE(vecs->mpvec))
1421                 remove_maps_and_stop_waiters(vecs);
1422
1423         if (VECTOR_SIZE(vecs->pathvec))
1424                 free_pathvec(vecs->pathvec, FREE_PATHS);
1425
1426         vecs->pathvec = NULL;
1427         conf = NULL;
1428
1429         if (!load_config(DEFAULT_CONFIGFILE, udev)) {
1430                 conf->verbosity = old->verbosity;
1431                 conf->daemon = 1;
1432                 configure(vecs, 1);
1433                 free_config(old);
1434                 retval = 0;
1435         }
1436
1437         return retval;
1438 }
1439
1440 static struct vectors *
1441 init_vecs (void)
1442 {
1443         struct vectors * vecs;
1444
1445         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1446
1447         if (!vecs)
1448                 return NULL;
1449
1450         vecs->lock.mutex =
1451                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1452
1453         if (!vecs->lock.mutex)
1454                 goto out;
1455
1456         pthread_mutex_init(vecs->lock.mutex, NULL);
1457         vecs->lock.depth = 0;
1458
1459         return vecs;
1460
1461 out:
1462         FREE(vecs);
1463         condlog(0, "failed to init paths");
1464         return NULL;
1465 }
1466
1467 static void *
1468 signal_set(int signo, void (*func) (int))
1469 {
1470         int r;
1471         struct sigaction sig;
1472         struct sigaction osig;
1473
1474         sig.sa_handler = func;
1475         sigemptyset(&sig.sa_mask);
1476         sig.sa_flags = 0;
1477
1478         r = sigaction(signo, &sig, &osig);
1479
1480         if (r < 0)
1481                 return (SIG_ERR);
1482         else
1483                 return (osig.sa_handler);
1484 }
1485
1486 void
1487 handle_signals(void)
1488 {
1489         if (reconfig_sig && running_state == DAEMON_RUNNING) {
1490                 condlog(2, "reconfigure (signal)");
1491                 pthread_cleanup_push(cleanup_lock,
1492                                 &gvecs->lock);
1493                 lock(gvecs->lock);
1494                 pthread_testcancel();
1495                 reconfigure(gvecs);
1496                 lock_cleanup_pop(gvecs->lock);
1497         }
1498         if (log_reset_sig) {
1499                 condlog(2, "reset log (signal)");
1500                 pthread_mutex_lock(&logq_lock);
1501                 log_reset("multipathd");
1502                 pthread_mutex_unlock(&logq_lock);
1503         }
1504         reconfig_sig = 0;
1505         log_reset_sig = 0;
1506 }
1507
1508 static void
1509 sighup (int sig)
1510 {
1511         reconfig_sig = 1;
1512 }
1513
1514 static void
1515 sigend (int sig)
1516 {
1517         exit_daemon();
1518 }
1519
1520 static void
1521 sigusr1 (int sig)
1522 {
1523         log_reset_sig = 1;
1524 }
1525
1526 static void
1527 sigusr2 (int sig)
1528 {
1529         condlog(3, "SIGUSR2 received");
1530 }
1531
1532 static void
1533 signal_init(void)
1534 {
1535         sigset_t set;
1536
1537         sigemptyset(&set);
1538         sigaddset(&set, SIGHUP);
1539         sigaddset(&set, SIGUSR1);
1540         sigaddset(&set, SIGUSR2);
1541         pthread_sigmask(SIG_BLOCK, &set, NULL);
1542
1543         signal_set(SIGHUP, sighup);
1544         signal_set(SIGUSR1, sigusr1);
1545         signal_set(SIGUSR2, sigusr2);
1546         signal_set(SIGINT, sigend);
1547         signal_set(SIGTERM, sigend);
1548         signal(SIGPIPE, SIG_IGN);
1549 }
1550
1551 static void
1552 setscheduler (void)
1553 {
1554         int res;
1555         static struct sched_param sched_param = {
1556                 .sched_priority = 99
1557         };
1558
1559         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1560
1561         if (res == -1)
1562                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1563         return;
1564 }
1565
1566 static void
1567 set_oom_adj (void)
1568 {
1569 #ifdef OOM_SCORE_ADJ_MIN
1570         int retry = 1;
1571         char *file = "/proc/self/oom_score_adj";
1572         int score = OOM_SCORE_ADJ_MIN;
1573 #else
1574         int retry = 0;
1575         char *file = "/proc/self/oom_adj";
1576         int score = OOM_ADJUST_MIN;
1577 #endif
1578         FILE *fp;
1579         struct stat st;
1580         char *envp;
1581
1582         envp = getenv("OOMScoreAdjust");
1583         if (envp) {
1584                 condlog(3, "Using systemd provided OOMScoreAdjust");
1585                 return;
1586         }
1587         do {
1588                 if (stat(file, &st) == 0){
1589                         fp = fopen(file, "w");
1590                         if (!fp) {
1591                                 condlog(0, "couldn't fopen %s : %s", file,
1592                                         strerror(errno));
1593                                 return;
1594                         }
1595                         fprintf(fp, "%i", score);
1596                         fclose(fp);
1597                         return;
1598                 }
1599                 if (errno != ENOENT) {
1600                         condlog(0, "couldn't stat %s : %s", file,
1601                                 strerror(errno));
1602                         return;
1603                 }
1604 #ifdef OOM_ADJUST_MIN
1605                 file = "/proc/self/oom_adj";
1606                 score = OOM_ADJUST_MIN;
1607 #else
1608                 retry = 0;
1609 #endif
1610         } while (retry--);
1611         condlog(0, "couldn't adjust oom score");
1612 }
1613
1614 static int
1615 child (void * param)
1616 {
1617         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1618         pthread_attr_t log_attr, misc_attr, uevent_attr;
1619         struct vectors * vecs;
1620         struct multipath * mpp;
1621         int i;
1622 #ifdef USE_SYSTEMD
1623         unsigned long checkint;
1624 #endif
1625         int rc, pid_rc;
1626         char *envp;
1627
1628         mlockall(MCL_CURRENT | MCL_FUTURE);
1629         sem_init(&exit_sem, 0, 0);
1630         signal_init();
1631
1632         udev = udev_new();
1633
1634         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1635         setup_thread_attr(&uevent_attr, 128 * 1024, 1);
1636         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1637
1638         if (logsink == 1) {
1639                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1640                 log_thread_start(&log_attr);
1641                 pthread_attr_destroy(&log_attr);
1642         }
1643
1644         running_state = DAEMON_START;
1645
1646 #ifdef USE_SYSTEMD
1647         sd_notify(0, "STATUS=startup");
1648 #endif
1649         condlog(2, "--------start up--------");
1650         condlog(2, "read " DEFAULT_CONFIGFILE);
1651
1652         if (load_config(DEFAULT_CONFIGFILE, udev))
1653                 goto failed;
1654
1655         if (init_checkers()) {
1656                 condlog(0, "failed to initialize checkers");
1657                 goto failed;
1658         }
1659         if (init_prio()) {
1660                 condlog(0, "failed to initialize prioritizers");
1661                 goto failed;
1662         }
1663
1664         setlogmask(LOG_UPTO(conf->verbosity + 3));
1665
1666         envp = getenv("LimitNOFILE");
1667
1668         if (envp) {
1669                 condlog(2,"Using systemd provided open fds limit of %s", envp);
1670         } else if (conf->max_fds) {
1671                 struct rlimit fd_limit;
1672
1673                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1674                         condlog(0, "can't get open fds limit: %s",
1675                                 strerror(errno));
1676                         fd_limit.rlim_cur = 0;
1677                         fd_limit.rlim_max = 0;
1678                 }
1679                 if (fd_limit.rlim_cur < conf->max_fds) {
1680                         fd_limit.rlim_cur = conf->max_fds;
1681                         if (fd_limit.rlim_max < conf->max_fds)
1682                                 fd_limit.rlim_max = conf->max_fds;
1683                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1684                                 condlog(0, "can't set open fds limit to "
1685                                         "%lu/%lu : %s",
1686                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1687                                         strerror(errno));
1688                         } else {
1689                                 condlog(3, "set open fds limit to %lu/%lu",
1690                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1691                         }
1692                 }
1693
1694         }
1695
1696         vecs = gvecs = init_vecs();
1697         if (!vecs)
1698                 goto failed;
1699
1700         setscheduler();
1701         set_oom_adj();
1702
1703         conf->daemon = 1;
1704         udev_set_sync_support(0);
1705 #ifdef USE_SYSTEMD
1706         envp = getenv("WATCHDOG_USEC");
1707         if (envp && sscanf(envp, "%lu", &checkint) == 1) {
1708                 /* Value is in microseconds */
1709                 conf->max_checkint = checkint / 1000000;
1710                 /* Rescale checkint */
1711                 if (conf->checkint > conf->max_checkint)
1712                         conf->checkint = conf->max_checkint;
1713                 else
1714                         conf->checkint = conf->max_checkint / 4;
1715                 condlog(3, "enabling watchdog, interval %d max %d",
1716                         conf->checkint, conf->max_checkint);
1717                 conf->watchdog = conf->checkint;
1718         }
1719 #endif
1720         /*
1721          * Start uevent listener early to catch events
1722          */
1723         if ((rc = pthread_create(&uevent_thr, &uevent_attr, ueventloop, udev))) {
1724                 condlog(0, "failed to create uevent thread: %d", rc);
1725                 goto failed;
1726         }
1727         pthread_attr_destroy(&uevent_attr);
1728         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1729                 condlog(0, "failed to create cli listener: %d", rc);
1730                 goto failed;
1731         }
1732         /*
1733          * fetch and configure both paths and multipaths
1734          */
1735 #ifdef USE_SYSTEMD
1736         sd_notify(0, "STATUS=configure");
1737 #endif
1738         running_state = DAEMON_CONFIGURE;
1739
1740         lock(vecs->lock);
1741         if (configure(vecs, 1)) {
1742                 unlock(vecs->lock);
1743                 condlog(0, "failure during configuration");
1744                 goto failed;
1745         }
1746         unlock(vecs->lock);
1747
1748         /*
1749          * start threads
1750          */
1751         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1752                 condlog(0,"failed to create checker loop thread: %d", rc);
1753                 goto failed;
1754         }
1755         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1756                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1757                 goto failed;
1758         }
1759         pthread_attr_destroy(&misc_attr);
1760
1761         /* Startup complete, create logfile */
1762         pid_rc = pidfile_create(DEFAULT_PIDFILE, daemon_pid);
1763         /* Ignore errors, we can live without */
1764
1765         running_state = DAEMON_RUNNING;
1766 #ifdef USE_SYSTEMD
1767         sd_notify(0, "READY=1\nSTATUS=running");
1768 #endif
1769
1770         /*
1771          * exit path
1772          */
1773         while(sem_wait(&exit_sem) != 0); /* Do nothing */
1774
1775 #ifdef USE_SYSTEMD
1776         sd_notify(0, "STATUS=shutdown");
1777 #endif
1778         running_state = DAEMON_SHUTDOWN;
1779         lock(vecs->lock);
1780         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1781                 vector_foreach_slot(vecs->mpvec, mpp, i)
1782                         dm_queue_if_no_path(mpp->alias, 0);
1783         remove_maps_and_stop_waiters(vecs);
1784         unlock(vecs->lock);
1785
1786         pthread_cancel(check_thr);
1787         pthread_cancel(uevent_thr);
1788         pthread_cancel(uxlsnr_thr);
1789         pthread_cancel(uevq_thr);
1790
1791         lock(vecs->lock);
1792         free_pathvec(vecs->pathvec, FREE_PATHS);
1793         vecs->pathvec = NULL;
1794         unlock(vecs->lock);
1795         /* Now all the waitevent threads will start rushing in. */
1796         while (vecs->lock.depth > 0) {
1797                 sleep (1); /* This is weak. */
1798                 condlog(3, "Have %d wait event checkers threads to de-alloc,"
1799                         " waiting...", vecs->lock.depth);
1800         }
1801         pthread_mutex_destroy(vecs->lock.mutex);
1802         FREE(vecs->lock.mutex);
1803         vecs->lock.depth = 0;
1804         vecs->lock.mutex = NULL;
1805         FREE(vecs);
1806         vecs = NULL;
1807
1808         cleanup_checkers();
1809         cleanup_prio();
1810
1811         dm_lib_release();
1812         dm_lib_exit();
1813
1814         /* We're done here */
1815         if (!pid_rc) {
1816                 condlog(3, "unlink pidfile");
1817                 unlink(DEFAULT_PIDFILE);
1818         }
1819
1820         condlog(2, "--------shut down-------");
1821
1822         if (logsink == 1)
1823                 log_thread_stop();
1824
1825         /*
1826          * Freeing config must be done after condlog() and dm_lib_exit(),
1827          * because logging functions like dlog() and dm_write_log()
1828          * reference the config.
1829          */
1830         free_config(conf);
1831         conf = NULL;
1832         udev_unref(udev);
1833         udev = NULL;
1834 #ifdef _DEBUG_
1835         dbg_free_final(NULL);
1836 #endif
1837
1838 #ifdef USE_SYSTEMD
1839         sd_notify(0, "ERRNO=0");
1840 #endif
1841         exit(0);
1842
1843 failed:
1844 #ifdef USE_SYSTEMD
1845         sd_notify(0, "ERRNO=1");
1846 #endif
1847         exit(1);
1848 }
1849
1850 static int
1851 daemonize(void)
1852 {
1853         int pid;
1854         int dev_null_fd;
1855
1856         if( (pid = fork()) < 0){
1857                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1858                 return -1;
1859         }
1860         else if (pid != 0)
1861                 return pid;
1862
1863         setsid();
1864
1865         if ( (pid = fork()) < 0)
1866                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1867         else if (pid != 0)
1868                 _exit(0);
1869
1870         if (chdir("/") < 0)
1871                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1872
1873         dev_null_fd = open("/dev/null", O_RDWR);
1874         if (dev_null_fd < 0){
1875                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
1876                         strerror(errno));
1877                 _exit(0);
1878         }
1879
1880         close(STDIN_FILENO);
1881         if (dup(dev_null_fd) < 0) {
1882                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
1883                         strerror(errno));
1884                 _exit(0);
1885         }
1886         close(STDOUT_FILENO);
1887         if (dup(dev_null_fd) < 0) {
1888                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
1889                         strerror(errno));
1890                 _exit(0);
1891         }
1892         close(STDERR_FILENO);
1893         if (dup(dev_null_fd) < 0) {
1894                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
1895                         strerror(errno));
1896                 _exit(0);
1897         }
1898         close(dev_null_fd);
1899         daemon_pid = getpid();
1900         return 0;
1901 }
1902
1903 int
1904 main (int argc, char *argv[])
1905 {
1906         extern char *optarg;
1907         extern int optind;
1908         int arg;
1909         int err;
1910
1911         logsink = 1;
1912         running_state = DAEMON_INIT;
1913         dm_init();
1914
1915         if (getuid() != 0) {
1916                 fprintf(stderr, "need to be root\n");
1917                 exit(1);
1918         }
1919
1920         /* make sure we don't lock any path */
1921         if (chdir("/") < 0)
1922                 fprintf(stderr, "can't chdir to root directory : %s\n",
1923                         strerror(errno));
1924         umask(umask(077) | 022);
1925
1926         conf = alloc_config();
1927
1928         if (!conf)
1929                 exit(1);
1930
1931         while ((arg = getopt(argc, argv, ":dsv:k::")) != EOF ) {
1932         switch(arg) {
1933                 case 'd':
1934                         logsink = 0;
1935                         //debug=1; /* ### comment me out ### */
1936                         break;
1937                 case 'v':
1938                         if (sizeof(optarg) > sizeof(char *) ||
1939                             !isdigit(optarg[0]))
1940                                 exit(1);
1941
1942                         conf->verbosity = atoi(optarg);
1943                         break;
1944                 case 's':
1945                         logsink = -1;
1946                         break;
1947                 case 'k':
1948                         uxclnt(optarg);
1949                         exit(0);
1950                 default:
1951                         ;
1952                 }
1953         }
1954         if (optind < argc) {
1955                 char cmd[CMDSIZE];
1956                 char * s = cmd;
1957                 char * c = s;
1958
1959                 while (optind < argc) {
1960                         if (strchr(argv[optind], ' '))
1961                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1962                         else
1963                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1964                         optind++;
1965                 }
1966                 c += snprintf(c, s + CMDSIZE - c, "\n");
1967                 uxclnt(s);
1968                 exit(0);
1969         }
1970
1971         if (logsink < 1)
1972                 err = 0;
1973         else
1974                 err = daemonize();
1975
1976         if (err < 0)
1977                 /* error */
1978                 exit(1);
1979         else if (err > 0)
1980                 /* parent dies */
1981                 exit(0);
1982         else
1983                 /* child lives */
1984                 return (child(NULL));
1985 }
1986
1987 void *  mpath_pr_event_handler_fn (void * pathp )
1988 {
1989         struct multipath * mpp;
1990         int i,j, ret, isFound;
1991         struct path * pp = (struct path *)pathp;
1992         unsigned char *keyp;
1993         uint64_t prkey;
1994         struct prout_param_descriptor *param;
1995         struct prin_resp *resp;
1996
1997         mpp = pp->mpp;
1998
1999         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
2000         if (!resp){
2001                 condlog(0,"%s Alloc failed for prin response", pp->dev);
2002                 return NULL;
2003         }
2004
2005         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
2006         if (ret != MPATH_PR_SUCCESS )
2007         {
2008                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
2009                 goto out;
2010         }
2011
2012         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
2013                         resp->prin_descriptor.prin_readkeys.additional_length );
2014
2015         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
2016         {
2017                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
2018                 ret = MPATH_PR_SUCCESS;
2019                 goto out;
2020         }
2021         prkey = 0;
2022         keyp = (unsigned char *)mpp->reservation_key;
2023         for (j = 0; j < 8; ++j) {
2024                 if (j > 0)
2025                         prkey <<= 8;
2026                 prkey |= *keyp;
2027                 ++keyp;
2028         }
2029         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ", prkey);
2030
2031         isFound =0;
2032         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
2033         {
2034                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
2035                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
2036                 if (!memcmp(mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
2037                 {
2038                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
2039                         isFound =1;
2040                         break;
2041                 }
2042         }
2043         if (!isFound)
2044         {
2045                 condlog(0, "%s: Either device not registered or ", pp->dev);
2046                 condlog(0, "host is not authorised for registration. Skip path");
2047                 ret = MPATH_PR_OTHER;
2048                 goto out;
2049         }
2050
2051         param= malloc(sizeof(struct prout_param_descriptor));
2052         memset(param, 0 , sizeof(struct prout_param_descriptor));
2053
2054         for (j = 7; j >= 0; --j) {
2055                 param->sa_key[j] = (prkey & 0xff);
2056                 prkey >>= 8;
2057         }
2058         param->num_transportid = 0;
2059
2060         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
2061
2062         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
2063         if (ret != MPATH_PR_SUCCESS )
2064         {
2065                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
2066         }
2067         mpp->prflag = 1;
2068
2069         free(param);
2070 out:
2071         free(resp);
2072         return NULL;
2073 }
2074
2075 int mpath_pr_event_handle(struct path *pp)
2076 {
2077         pthread_t thread;
2078         int rc;
2079         pthread_attr_t attr;
2080         struct multipath * mpp;
2081
2082         mpp = pp->mpp;
2083
2084         if (!mpp->reservation_key)
2085                 return -1;
2086
2087         pthread_attr_init(&attr);
2088         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
2089
2090         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
2091         if (rc) {
2092                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
2093                 return -1;
2094         }
2095         pthread_attr_destroy(&attr);
2096         rc = pthread_join(thread, NULL);
2097         return 0;
2098 }
2099