multipathd: add path when transitioned from 'blocked' state
[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         struct udev *udev = ap;
843
844         if (uevent_listen(udev))
845                 condlog(0, "error starting uevent listener");
846
847         return NULL;
848 }
849
850 static void *
851 uevqloop (void * ap)
852 {
853         if (uevent_dispatch(&uev_trigger, ap))
854                 condlog(0, "error starting uevent dispatcher");
855
856         return NULL;
857 }
858 static void *
859 uxlsnrloop (void * ap)
860 {
861         if (cli_init())
862                 return NULL;
863
864         set_handler_callback(LIST+PATHS, cli_list_paths);
865         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
866         set_handler_callback(LIST+MAPS, cli_list_maps);
867         set_handler_callback(LIST+STATUS, cli_list_status);
868         set_handler_callback(LIST+DAEMON, cli_list_daemon);
869         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
870         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
871         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
872         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
873         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
874         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
875         set_handler_callback(LIST+CONFIG, cli_list_config);
876         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
877         set_handler_callback(LIST+DEVICES, cli_list_devices);
878         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
879         set_handler_callback(ADD+PATH, cli_add_path);
880         set_handler_callback(DEL+PATH, cli_del_path);
881         set_handler_callback(ADD+MAP, cli_add_map);
882         set_handler_callback(DEL+MAP, cli_del_map);
883         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
884         set_handler_callback(RECONFIGURE, cli_reconfigure);
885         set_handler_callback(SUSPEND+MAP, cli_suspend);
886         set_handler_callback(RESUME+MAP, cli_resume);
887         set_handler_callback(RESIZE+MAP, cli_resize);
888         set_handler_callback(RELOAD+MAP, cli_reload);
889         set_handler_callback(RESET+MAP, cli_reassign);
890         set_handler_callback(REINSTATE+PATH, cli_reinstate);
891         set_handler_callback(FAIL+PATH, cli_fail);
892         set_handler_callback(DISABLEQ+MAP, cli_disable_queueing);
893         set_handler_callback(RESTOREQ+MAP, cli_restore_queueing);
894         set_handler_callback(DISABLEQ+MAPS, cli_disable_all_queueing);
895         set_handler_callback(RESTOREQ+MAPS, cli_restore_all_queueing);
896         set_handler_callback(QUIT, cli_quit);
897         set_handler_callback(SHUTDOWN, cli_shutdown);
898         set_handler_callback(GETPRSTATUS+MAP, cli_getprstatus);
899         set_handler_callback(SETPRSTATUS+MAP, cli_setprstatus);
900         set_handler_callback(UNSETPRSTATUS+MAP, cli_unsetprstatus);
901         set_handler_callback(FORCEQ+DAEMON, cli_force_no_daemon_q);
902         set_handler_callback(RESTOREQ+DAEMON, cli_restore_no_daemon_q);
903
904         umask(077);
905         uxsock_listen(&uxsock_trigger, ap);
906
907         return NULL;
908 }
909
910 void
911 exit_daemon (void)
912 {
913         sem_post(&exit_sem);
914 }
915
916 const char *
917 daemon_status(void)
918 {
919         switch (running_state) {
920         case DAEMON_INIT:
921                 return "init";
922         case DAEMON_START:
923                 return "startup";
924         case DAEMON_CONFIGURE:
925                 return "configure";
926         case DAEMON_RUNNING:
927                 return "running";
928         case DAEMON_SHUTDOWN:
929                 return "shutdown";
930         }
931         return NULL;
932 }
933
934 static void
935 fail_path (struct path * pp, int del_active)
936 {
937         if (!pp->mpp)
938                 return;
939
940         condlog(2, "checker failed path %s in map %s",
941                  pp->dev_t, pp->mpp->alias);
942
943         dm_fail_path(pp->mpp->alias, pp->dev_t);
944         if (del_active)
945                 update_queue_mode_del_path(pp->mpp);
946 }
947
948 /*
949  * caller must have locked the path list before calling that function
950  */
951 static void
952 reinstate_path (struct path * pp, int add_active)
953 {
954         if (!pp->mpp)
955                 return;
956
957         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
958                 condlog(0, "%s: reinstate failed", pp->dev_t);
959         else {
960                 condlog(2, "%s: reinstated", pp->dev_t);
961                 if (add_active)
962                         update_queue_mode_add_path(pp->mpp);
963         }
964 }
965
966 static void
967 enable_group(struct path * pp)
968 {
969         struct pathgroup * pgp;
970
971         /*
972          * if path is added through uev_add_path, pgindex can be unset.
973          * next update_strings() will set it, upon map reload event.
974          *
975          * we can safely return here, because upon map reload, all
976          * PG will be enabled.
977          */
978         if (!pp->mpp->pg || !pp->pgindex)
979                 return;
980
981         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
982
983         if (pgp->status == PGSTATE_DISABLED) {
984                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
985                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
986         }
987 }
988
989 static void
990 mpvec_garbage_collector (struct vectors * vecs)
991 {
992         struct multipath * mpp;
993         unsigned int i;
994
995         if (!vecs->mpvec)
996                 return;
997
998         vector_foreach_slot (vecs->mpvec, mpp, i) {
999                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
1000                         condlog(2, "%s: remove dead map", mpp->alias);
1001                         remove_map_and_stop_waiter(mpp, vecs, 1);
1002                         i--;
1003                 }
1004         }
1005 }
1006
1007 /* This is called after a path has started working again. It the multipath
1008  * device for this path uses the followover failback type, and this is the
1009  * best pathgroup, and this is the first path in the pathgroup to come back
1010  * up, then switch to this pathgroup */
1011 static int
1012 followover_should_failback(struct path * pp)
1013 {
1014         struct pathgroup * pgp;
1015         struct path *pp1;
1016         int i;
1017
1018         if (pp->mpp->pgfailback != -FAILBACK_FOLLOWOVER ||
1019             !pp->mpp->pg || !pp->pgindex ||
1020             pp->pgindex != pp->mpp->bestpg)
1021                 return 0;
1022
1023         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1024         vector_foreach_slot(pgp->paths, pp1, i) {
1025                 if (pp1 == pp)
1026                         continue;
1027                 if (pp1->chkrstate != PATH_DOWN && pp1->chkrstate != PATH_SHAKY)
1028                         return 0;
1029         }
1030         return 1;
1031 }
1032
1033 static void
1034 defered_failback_tick (vector mpvec)
1035 {
1036         struct multipath * mpp;
1037         unsigned int i;
1038
1039         vector_foreach_slot (mpvec, mpp, i) {
1040                 /*
1041                  * defered failback getting sooner
1042                  */
1043                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1044                         mpp->failback_tick--;
1045
1046                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1047                                 switch_pathgroup(mpp);
1048                 }
1049         }
1050 }
1051
1052 static void
1053 retry_count_tick(vector mpvec)
1054 {
1055         struct multipath *mpp;
1056         unsigned int i;
1057
1058         vector_foreach_slot (mpvec, mpp, i) {
1059                 if (mpp->retry_tick) {
1060                         mpp->stat_total_queueing_time++;
1061                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1062                         if(--mpp->retry_tick == 0) {
1063                                 dm_queue_if_no_path(mpp->alias, 0);
1064                                 condlog(2, "%s: Disable queueing", mpp->alias);
1065                         }
1066                 }
1067         }
1068 }
1069
1070 int update_prio(struct path *pp, int refresh_all)
1071 {
1072         int oldpriority;
1073         struct path *pp1;
1074         struct pathgroup * pgp;
1075         int i, j, changed = 0;
1076
1077         if (refresh_all) {
1078                 vector_foreach_slot (pp->mpp->pg, pgp, i) {
1079                         vector_foreach_slot (pgp->paths, pp1, j) {
1080                                 oldpriority = pp1->priority;
1081                                 pathinfo(pp1, conf->hwtable, DI_PRIO);
1082                                 if (pp1->priority != oldpriority)
1083                                         changed = 1;
1084                         }
1085                 }
1086                 return changed;
1087         }
1088         oldpriority = pp->priority;
1089         pathinfo(pp, conf->hwtable, DI_PRIO);
1090
1091         if (pp->priority == oldpriority)
1092                 return 0;
1093         return 1;
1094 }
1095
1096 int update_path_groups(struct multipath *mpp, struct vectors *vecs, int refresh)
1097 {
1098         if (reload_map(vecs, mpp, refresh))
1099                 return 1;
1100
1101         dm_lib_release();
1102         if (setup_multipath(vecs, mpp) != 0)
1103                 return 1;
1104         sync_map_state(mpp);
1105
1106         return 0;
1107 }
1108
1109 int
1110 check_path (struct vectors * vecs, struct path * pp)
1111 {
1112         int newstate;
1113         int new_path_up = 0;
1114         int chkr_new_path_up = 0;
1115         int oldchkrstate = pp->chkrstate;
1116
1117         if (!pp->mpp)
1118                 return 0;
1119
1120         if (pp->tick && --pp->tick)
1121                 return 0; /* don't check this path yet */
1122
1123         /*
1124          * provision a next check soonest,
1125          * in case we exit abnormaly from here
1126          */
1127         pp->tick = conf->checkint;
1128
1129         newstate = path_offline(pp);
1130         if (newstate == PATH_REMOVED) {
1131                 condlog(2, "%s: remove path (checker)", pp->dev);
1132                 ev_remove_path(pp, vecs);
1133                 return;
1134         }
1135         if (newstate == PATH_UP)
1136                 newstate = get_state(pp, 1);
1137         else
1138                 checker_clear_message(&pp->checker);
1139
1140         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1141                 condlog(2, "%s: unusable path", pp->dev);
1142                 pathinfo(pp, conf->hwtable, 0);
1143                 return 1;
1144         }
1145         if (!pp->mpp) {
1146                 if (!strlen(pp->wwid) &&
1147                     (newstate == PATH_UP || newstate == PATH_GHOST)) {
1148                         condlog(2, "%s: add missing path", pp->dev);
1149                         if (pathinfo(pp, conf->hwtable, DI_ALL) == 0) {
1150                                 ev_add_path(pp, vecs);
1151                                 pp->tick = 1;
1152                         }
1153                 }
1154                 return;
1155         }
1156         /*
1157          * Async IO in flight. Keep the previous path state
1158          * and reschedule as soon as possible
1159          */
1160         if (newstate == PATH_PENDING) {
1161                 pp->tick = 1;
1162                 return 0;
1163         }
1164         /*
1165          * Synchronize with kernel state
1166          */
1167         if (update_multipath_strings(pp->mpp, vecs->pathvec)) {
1168                 condlog(1, "%s: Could not synchronize with kernel state",
1169                         pp->dev);
1170                 pp->dmstate = PSTATE_UNDEF;
1171         }
1172         pp->chkrstate = newstate;
1173         if (newstate != pp->state) {
1174                 int oldstate = pp->state;
1175                 pp->state = newstate;
1176
1177                 if (strlen(checker_message(&pp->checker)))
1178                         LOG_MSG(1, checker_message(&pp->checker));
1179
1180                 /*
1181                  * upon state change, reset the checkint
1182                  * to the shortest delay
1183                  */
1184                 pp->checkint = conf->checkint;
1185
1186                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY) {
1187                         /*
1188                          * proactively fail path in the DM
1189                          */
1190                         if (oldstate == PATH_UP ||
1191                             oldstate == PATH_GHOST)
1192                                 fail_path(pp, 1);
1193                         else
1194                                 fail_path(pp, 0);
1195
1196                         /*
1197                          * cancel scheduled failback
1198                          */
1199                         pp->mpp->failback_tick = 0;
1200
1201                         pp->mpp->stat_path_failures++;
1202                         return 1;
1203                 }
1204
1205                 if(newstate == PATH_UP || newstate == PATH_GHOST){
1206                         if ( pp->mpp && pp->mpp->prflag ){
1207                                 /*
1208                                  * Check Persistent Reservation.
1209                                  */
1210                         condlog(2, "%s: checking persistent reservation "
1211                                 "registration", pp->dev);
1212                         mpath_pr_event_handle(pp);
1213                         }
1214                 }
1215
1216                 /*
1217                  * reinstate this path
1218                  */
1219                 if (oldstate != PATH_UP &&
1220                     oldstate != PATH_GHOST)
1221                         reinstate_path(pp, 1);
1222                 else
1223                         reinstate_path(pp, 0);
1224
1225                 new_path_up = 1;
1226
1227                 if (oldchkrstate != PATH_UP && oldchkrstate != PATH_GHOST)
1228                         chkr_new_path_up = 1;
1229
1230                 /*
1231                  * if at least one path is up in a group, and
1232                  * the group is disabled, re-enable it
1233                  */
1234                 if (newstate == PATH_UP)
1235                         enable_group(pp);
1236         }
1237         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1238                 if (pp->dmstate == PSTATE_FAILED ||
1239                     pp->dmstate == PSTATE_UNDEF) {
1240                         /* Clear IO errors */
1241                         reinstate_path(pp, 0);
1242                 } else {
1243                         LOG_MSG(4, checker_message(&pp->checker));
1244                         if (pp->checkint != conf->max_checkint) {
1245                                 /*
1246                                  * double the next check delay.
1247                                  * max at conf->max_checkint
1248                                  */
1249                                 if (pp->checkint < (conf->max_checkint / 2))
1250                                         pp->checkint = 2 * pp->checkint;
1251                                 else
1252                                         pp->checkint = conf->max_checkint;
1253
1254                                 condlog(4, "%s: delay next check %is",
1255                                         pp->dev_t, pp->checkint);
1256                         }
1257                         pp->tick = pp->checkint;
1258                 }
1259         }
1260         else if (newstate == PATH_DOWN &&
1261                  strlen(checker_message(&pp->checker))) {
1262                 if (conf->log_checker_err == LOG_CHKR_ERR_ONCE)
1263                         LOG_MSG(3, checker_message(&pp->checker));
1264                 else
1265                         LOG_MSG(2, checker_message(&pp->checker));
1266         }
1267
1268         pp->state = newstate;
1269
1270         /*
1271          * path prio refreshing
1272          */
1273         condlog(4, "path prio refresh");
1274
1275         if (update_prio(pp, new_path_up) &&
1276             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
1277              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1278                 update_path_groups(pp->mpp, vecs, !new_path_up);
1279         else if (need_switch_pathgroup(pp->mpp, 0)) {
1280                 if (pp->mpp->pgfailback > 0 &&
1281                     (new_path_up || pp->mpp->failback_tick <= 0))
1282                         pp->mpp->failback_tick =
1283                                 pp->mpp->pgfailback + 1;
1284                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE ||
1285                          (chkr_new_path_up && followover_should_failback(pp)))
1286                         switch_pathgroup(pp->mpp);
1287         }
1288         return 1;
1289 }
1290
1291 static void *
1292 checkerloop (void *ap)
1293 {
1294         struct vectors *vecs;
1295         struct path *pp;
1296         int count = 0;
1297         unsigned int i;
1298
1299         mlockall(MCL_CURRENT | MCL_FUTURE);
1300         vecs = (struct vectors *)ap;
1301         condlog(2, "path checkers start up");
1302
1303         /*
1304          * init the path check interval
1305          */
1306         vector_foreach_slot (vecs->pathvec, pp, i) {
1307                 pp->checkint = conf->checkint;
1308         }
1309
1310         while (1) {
1311                 struct timeval diff_time, start_time, end_time;
1312                 int num_paths = 0;
1313
1314                 if (gettimeofday(&start_time, NULL) != 0)
1315                         start_time.tv_sec = 0;
1316                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1317                 lock(vecs->lock);
1318                 pthread_testcancel();
1319                 condlog(4, "tick");
1320 #ifdef USE_SYSTEMD
1321                 if (conf->watchdog)
1322                         sd_notify(0, "WATCHDOG=1");
1323 #endif
1324                 if (vecs->pathvec) {
1325                         vector_foreach_slot (vecs->pathvec, pp, i) {
1326                                 num_paths += check_path(vecs, pp);
1327                         }
1328                 }
1329                 if (vecs->mpvec) {
1330                         defered_failback_tick(vecs->mpvec);
1331                         retry_count_tick(vecs->mpvec);
1332                 }
1333                 if (count)
1334                         count--;
1335                 else {
1336                         condlog(4, "map garbage collection");
1337                         mpvec_garbage_collector(vecs);
1338                         count = MAPGCINT;
1339                 }
1340
1341                 lock_cleanup_pop(vecs->lock);
1342                 if (start_time.tv_sec &&
1343                     gettimeofday(&end_time, NULL) == 0 &&
1344                     num_paths) {
1345                         timersub(&end_time, &start_time, &diff_time);
1346                         condlog(3, "checked %d path%s in %lu.%06lu secs",
1347                                 num_paths, num_paths > 1 ? "s" : "",
1348                                 diff_time.tv_sec, diff_time.tv_usec);
1349                 }
1350                 sleep(1);
1351         }
1352         return NULL;
1353 }
1354
1355 int
1356 configure (struct vectors * vecs, int start_waiters)
1357 {
1358         struct multipath * mpp;
1359         struct path * pp;
1360         vector mpvec;
1361         int i;
1362
1363         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1364                 return 1;
1365
1366         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1367                 return 1;
1368
1369         if (!(mpvec = vector_alloc()))
1370                 return 1;
1371
1372         /*
1373          * probe for current path (from sysfs) and map (from dm) sets
1374          */
1375         path_discovery(vecs->pathvec, conf, DI_ALL);
1376
1377         vector_foreach_slot (vecs->pathvec, pp, i){
1378                 if (filter_path(conf, pp) > 0){
1379                         vector_del_slot(vecs->pathvec, i);
1380                         free_path(pp);
1381                         i--;
1382                 }
1383                 else
1384                         pp->checkint = conf->checkint;
1385         }
1386         if (map_discovery(vecs))
1387                 return 1;
1388
1389         /*
1390          * create new set of maps & push changed ones into dm
1391          */
1392         if (coalesce_paths(vecs, mpvec, NULL, 1))
1393                 return 1;
1394
1395         /*
1396          * may need to remove some maps which are no longer relevant
1397          * e.g., due to blacklist changes in conf file
1398          */
1399         if (coalesce_maps(vecs, mpvec))
1400                 return 1;
1401
1402         dm_lib_release();
1403
1404         sync_maps_state(mpvec);
1405         vector_foreach_slot(mpvec, mpp, i){
1406                 remember_wwid(mpp->wwid);
1407                 update_map_pr(mpp);
1408         }
1409
1410         /*
1411          * purge dm of old maps
1412          */
1413         remove_maps(vecs);
1414
1415         /*
1416          * save new set of maps formed by considering current path state
1417          */
1418         vector_free(vecs->mpvec);
1419         vecs->mpvec = mpvec;
1420
1421         /*
1422          * start dm event waiter threads for these new maps
1423          */
1424         vector_foreach_slot(vecs->mpvec, mpp, i) {
1425                 if (setup_multipath(vecs, mpp))
1426                         return 1;
1427                 if (start_waiters)
1428                         if (start_waiter_thread(mpp, vecs))
1429                                 return 1;
1430         }
1431         return 0;
1432 }
1433
1434 int
1435 reconfigure (struct vectors * vecs)
1436 {
1437         struct config * old = conf;
1438         int retval = 1;
1439
1440         /*
1441          * free old map and path vectors ... they use old conf state
1442          */
1443         if (VECTOR_SIZE(vecs->mpvec))
1444                 remove_maps_and_stop_waiters(vecs);
1445
1446         if (VECTOR_SIZE(vecs->pathvec))
1447                 free_pathvec(vecs->pathvec, FREE_PATHS);
1448
1449         vecs->pathvec = NULL;
1450         conf = NULL;
1451
1452         /* Re-read any timezone changes */
1453         tzset();
1454
1455         if (!load_config(DEFAULT_CONFIGFILE, udev)) {
1456                 conf->verbosity = old->verbosity;
1457                 conf->daemon = 1;
1458                 configure(vecs, 1);
1459                 free_config(old);
1460                 retval = 0;
1461         }
1462
1463         return retval;
1464 }
1465
1466 static struct vectors *
1467 init_vecs (void)
1468 {
1469         struct vectors * vecs;
1470
1471         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1472
1473         if (!vecs)
1474                 return NULL;
1475
1476         vecs->lock.mutex =
1477                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1478
1479         if (!vecs->lock.mutex)
1480                 goto out;
1481
1482         pthread_mutex_init(vecs->lock.mutex, NULL);
1483         vecs->lock.depth = 0;
1484
1485         return vecs;
1486
1487 out:
1488         FREE(vecs);
1489         condlog(0, "failed to init paths");
1490         return NULL;
1491 }
1492
1493 static void *
1494 signal_set(int signo, void (*func) (int))
1495 {
1496         int r;
1497         struct sigaction sig;
1498         struct sigaction osig;
1499
1500         sig.sa_handler = func;
1501         sigemptyset(&sig.sa_mask);
1502         sig.sa_flags = 0;
1503
1504         r = sigaction(signo, &sig, &osig);
1505
1506         if (r < 0)
1507                 return (SIG_ERR);
1508         else
1509                 return (osig.sa_handler);
1510 }
1511
1512 void
1513 handle_signals(void)
1514 {
1515         if (reconfig_sig && running_state == DAEMON_RUNNING) {
1516                 condlog(2, "reconfigure (signal)");
1517                 pthread_cleanup_push(cleanup_lock,
1518                                 &gvecs->lock);
1519                 lock(gvecs->lock);
1520                 pthread_testcancel();
1521                 reconfigure(gvecs);
1522                 lock_cleanup_pop(gvecs->lock);
1523         }
1524         if (log_reset_sig) {
1525                 condlog(2, "reset log (signal)");
1526                 pthread_mutex_lock(&logq_lock);
1527                 log_reset("multipathd");
1528                 pthread_mutex_unlock(&logq_lock);
1529         }
1530         reconfig_sig = 0;
1531         log_reset_sig = 0;
1532 }
1533
1534 static void
1535 sighup (int sig)
1536 {
1537         reconfig_sig = 1;
1538 }
1539
1540 static void
1541 sigend (int sig)
1542 {
1543         exit_daemon();
1544 }
1545
1546 static void
1547 sigusr1 (int sig)
1548 {
1549         log_reset_sig = 1;
1550 }
1551
1552 static void
1553 sigusr2 (int sig)
1554 {
1555         condlog(3, "SIGUSR2 received");
1556 }
1557
1558 static void
1559 signal_init(void)
1560 {
1561         sigset_t set;
1562
1563         sigemptyset(&set);
1564         sigaddset(&set, SIGHUP);
1565         sigaddset(&set, SIGUSR1);
1566         sigaddset(&set, SIGUSR2);
1567         pthread_sigmask(SIG_BLOCK, &set, NULL);
1568
1569         signal_set(SIGHUP, sighup);
1570         signal_set(SIGUSR1, sigusr1);
1571         signal_set(SIGUSR2, sigusr2);
1572         signal_set(SIGINT, sigend);
1573         signal_set(SIGTERM, sigend);
1574         signal(SIGPIPE, SIG_IGN);
1575 }
1576
1577 static void
1578 setscheduler (void)
1579 {
1580         int res;
1581         static struct sched_param sched_param = {
1582                 .sched_priority = 99
1583         };
1584
1585         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1586
1587         if (res == -1)
1588                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1589         return;
1590 }
1591
1592 static void
1593 set_oom_adj (void)
1594 {
1595 #ifdef OOM_SCORE_ADJ_MIN
1596         int retry = 1;
1597         char *file = "/proc/self/oom_score_adj";
1598         int score = OOM_SCORE_ADJ_MIN;
1599 #else
1600         int retry = 0;
1601         char *file = "/proc/self/oom_adj";
1602         int score = OOM_ADJUST_MIN;
1603 #endif
1604         FILE *fp;
1605         struct stat st;
1606         char *envp;
1607
1608         envp = getenv("OOMScoreAdjust");
1609         if (envp) {
1610                 condlog(3, "Using systemd provided OOMScoreAdjust");
1611                 return;
1612         }
1613         do {
1614                 if (stat(file, &st) == 0){
1615                         fp = fopen(file, "w");
1616                         if (!fp) {
1617                                 condlog(0, "couldn't fopen %s : %s", file,
1618                                         strerror(errno));
1619                                 return;
1620                         }
1621                         fprintf(fp, "%i", score);
1622                         fclose(fp);
1623                         return;
1624                 }
1625                 if (errno != ENOENT) {
1626                         condlog(0, "couldn't stat %s : %s", file,
1627                                 strerror(errno));
1628                         return;
1629                 }
1630 #ifdef OOM_ADJUST_MIN
1631                 file = "/proc/self/oom_adj";
1632                 score = OOM_ADJUST_MIN;
1633 #else
1634                 retry = 0;
1635 #endif
1636         } while (retry--);
1637         condlog(0, "couldn't adjust oom score");
1638 }
1639
1640 static int
1641 child (void * param)
1642 {
1643         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1644         pthread_attr_t log_attr, misc_attr, uevent_attr;
1645         struct vectors * vecs;
1646         struct multipath * mpp;
1647         int i;
1648 #ifdef USE_SYSTEMD
1649         unsigned long checkint;
1650 #endif
1651         int rc, pid_rc;
1652         char *envp;
1653
1654         mlockall(MCL_CURRENT | MCL_FUTURE);
1655         sem_init(&exit_sem, 0, 0);
1656         signal_init();
1657
1658         udev = udev_new();
1659
1660         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1661         setup_thread_attr(&uevent_attr, 128 * 1024, 1);
1662         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1663
1664         if (logsink == 1) {
1665                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1666                 log_thread_start(&log_attr);
1667                 pthread_attr_destroy(&log_attr);
1668         }
1669
1670         running_state = DAEMON_START;
1671
1672 #ifdef USE_SYSTEMD
1673         sd_notify(0, "STATUS=startup");
1674 #endif
1675         condlog(2, "--------start up--------");
1676         condlog(2, "read " DEFAULT_CONFIGFILE);
1677
1678         if (load_config(DEFAULT_CONFIGFILE, udev))
1679                 goto failed;
1680
1681         if (init_checkers()) {
1682                 condlog(0, "failed to initialize checkers");
1683                 goto failed;
1684         }
1685         if (init_prio()) {
1686                 condlog(0, "failed to initialize prioritizers");
1687                 goto failed;
1688         }
1689
1690         setlogmask(LOG_UPTO(conf->verbosity + 3));
1691
1692         envp = getenv("LimitNOFILE");
1693
1694         if (envp) {
1695                 condlog(2,"Using systemd provided open fds limit of %s", envp);
1696         } else if (conf->max_fds) {
1697                 struct rlimit fd_limit;
1698
1699                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1700                         condlog(0, "can't get open fds limit: %s",
1701                                 strerror(errno));
1702                         fd_limit.rlim_cur = 0;
1703                         fd_limit.rlim_max = 0;
1704                 }
1705                 if (fd_limit.rlim_cur < conf->max_fds) {
1706                         fd_limit.rlim_cur = conf->max_fds;
1707                         if (fd_limit.rlim_max < conf->max_fds)
1708                                 fd_limit.rlim_max = conf->max_fds;
1709                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1710                                 condlog(0, "can't set open fds limit to "
1711                                         "%lu/%lu : %s",
1712                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1713                                         strerror(errno));
1714                         } else {
1715                                 condlog(3, "set open fds limit to %lu/%lu",
1716                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1717                         }
1718                 }
1719
1720         }
1721
1722         vecs = gvecs = init_vecs();
1723         if (!vecs)
1724                 goto failed;
1725
1726         setscheduler();
1727         set_oom_adj();
1728
1729         conf->daemon = 1;
1730         udev_set_sync_support(0);
1731 #ifdef USE_SYSTEMD
1732         envp = getenv("WATCHDOG_USEC");
1733         if (envp && sscanf(envp, "%lu", &checkint) == 1) {
1734                 /* Value is in microseconds */
1735                 conf->max_checkint = checkint / 1000000;
1736                 /* Rescale checkint */
1737                 if (conf->checkint > conf->max_checkint)
1738                         conf->checkint = conf->max_checkint;
1739                 else
1740                         conf->checkint = conf->max_checkint / 4;
1741                 condlog(3, "enabling watchdog, interval %d max %d",
1742                         conf->checkint, conf->max_checkint);
1743                 conf->watchdog = conf->checkint;
1744         }
1745 #endif
1746         /*
1747          * Start uevent listener early to catch events
1748          */
1749         if ((rc = pthread_create(&uevent_thr, &uevent_attr, ueventloop, udev))) {
1750                 condlog(0, "failed to create uevent thread: %d", rc);
1751                 goto failed;
1752         }
1753         pthread_attr_destroy(&uevent_attr);
1754         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1755                 condlog(0, "failed to create cli listener: %d", rc);
1756                 goto failed;
1757         }
1758         /*
1759          * fetch and configure both paths and multipaths
1760          */
1761 #ifdef USE_SYSTEMD
1762         sd_notify(0, "STATUS=configure");
1763 #endif
1764         running_state = DAEMON_CONFIGURE;
1765
1766         lock(vecs->lock);
1767         if (configure(vecs, 1)) {
1768                 unlock(vecs->lock);
1769                 condlog(0, "failure during configuration");
1770                 goto failed;
1771         }
1772         unlock(vecs->lock);
1773
1774         /*
1775          * start threads
1776          */
1777         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1778                 condlog(0,"failed to create checker loop thread: %d", rc);
1779                 goto failed;
1780         }
1781         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1782                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1783                 goto failed;
1784         }
1785         pthread_attr_destroy(&misc_attr);
1786
1787         /* Startup complete, create logfile */
1788         pid_rc = pidfile_create(DEFAULT_PIDFILE, daemon_pid);
1789         /* Ignore errors, we can live without */
1790
1791         running_state = DAEMON_RUNNING;
1792 #ifdef USE_SYSTEMD
1793         sd_notify(0, "READY=1\nSTATUS=running");
1794 #endif
1795
1796         /*
1797          * exit path
1798          */
1799         while(sem_wait(&exit_sem) != 0); /* Do nothing */
1800
1801 #ifdef USE_SYSTEMD
1802         sd_notify(0, "STATUS=shutdown");
1803 #endif
1804         running_state = DAEMON_SHUTDOWN;
1805         lock(vecs->lock);
1806         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1807                 vector_foreach_slot(vecs->mpvec, mpp, i)
1808                         dm_queue_if_no_path(mpp->alias, 0);
1809         remove_maps_and_stop_waiters(vecs);
1810         unlock(vecs->lock);
1811
1812         pthread_cancel(check_thr);
1813         pthread_cancel(uevent_thr);
1814         pthread_cancel(uxlsnr_thr);
1815         pthread_cancel(uevq_thr);
1816
1817         lock(vecs->lock);
1818         free_pathvec(vecs->pathvec, FREE_PATHS);
1819         vecs->pathvec = NULL;
1820         unlock(vecs->lock);
1821         /* Now all the waitevent threads will start rushing in. */
1822         while (vecs->lock.depth > 0) {
1823                 sleep (1); /* This is weak. */
1824                 condlog(3, "Have %d wait event checkers threads to de-alloc,"
1825                         " waiting...", vecs->lock.depth);
1826         }
1827         pthread_mutex_destroy(vecs->lock.mutex);
1828         FREE(vecs->lock.mutex);
1829         vecs->lock.depth = 0;
1830         vecs->lock.mutex = NULL;
1831         FREE(vecs);
1832         vecs = NULL;
1833
1834         cleanup_checkers();
1835         cleanup_prio();
1836
1837         dm_lib_release();
1838         dm_lib_exit();
1839
1840         /* We're done here */
1841         if (!pid_rc) {
1842                 condlog(3, "unlink pidfile");
1843                 unlink(DEFAULT_PIDFILE);
1844         }
1845
1846         condlog(2, "--------shut down-------");
1847
1848         if (logsink == 1)
1849                 log_thread_stop();
1850
1851         /*
1852          * Freeing config must be done after condlog() and dm_lib_exit(),
1853          * because logging functions like dlog() and dm_write_log()
1854          * reference the config.
1855          */
1856         free_config(conf);
1857         conf = NULL;
1858         udev_unref(udev);
1859         udev = NULL;
1860 #ifdef _DEBUG_
1861         dbg_free_final(NULL);
1862 #endif
1863
1864 #ifdef USE_SYSTEMD
1865         sd_notify(0, "ERRNO=0");
1866 #endif
1867         exit(0);
1868
1869 failed:
1870 #ifdef USE_SYSTEMD
1871         sd_notify(0, "ERRNO=1");
1872 #endif
1873         exit(1);
1874 }
1875
1876 static int
1877 daemonize(void)
1878 {
1879         int pid;
1880         int dev_null_fd;
1881
1882         if( (pid = fork()) < 0){
1883                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1884                 return -1;
1885         }
1886         else if (pid != 0)
1887                 return pid;
1888
1889         setsid();
1890
1891         if ( (pid = fork()) < 0)
1892                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1893         else if (pid != 0)
1894                 _exit(0);
1895
1896         if (chdir("/") < 0)
1897                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1898
1899         dev_null_fd = open("/dev/null", O_RDWR);
1900         if (dev_null_fd < 0){
1901                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
1902                         strerror(errno));
1903                 _exit(0);
1904         }
1905
1906         close(STDIN_FILENO);
1907         if (dup(dev_null_fd) < 0) {
1908                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
1909                         strerror(errno));
1910                 _exit(0);
1911         }
1912         close(STDOUT_FILENO);
1913         if (dup(dev_null_fd) < 0) {
1914                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
1915                         strerror(errno));
1916                 _exit(0);
1917         }
1918         close(STDERR_FILENO);
1919         if (dup(dev_null_fd) < 0) {
1920                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
1921                         strerror(errno));
1922                 _exit(0);
1923         }
1924         close(dev_null_fd);
1925         daemon_pid = getpid();
1926         return 0;
1927 }
1928
1929 int
1930 main (int argc, char *argv[])
1931 {
1932         extern char *optarg;
1933         extern int optind;
1934         int arg;
1935         int err;
1936
1937         logsink = 1;
1938         running_state = DAEMON_INIT;
1939         dm_init();
1940
1941         if (getuid() != 0) {
1942                 fprintf(stderr, "need to be root\n");
1943                 exit(1);
1944         }
1945
1946         /* make sure we don't lock any path */
1947         if (chdir("/") < 0)
1948                 fprintf(stderr, "can't chdir to root directory : %s\n",
1949                         strerror(errno));
1950         umask(umask(077) | 022);
1951
1952         conf = alloc_config();
1953
1954         if (!conf)
1955                 exit(1);
1956
1957         while ((arg = getopt(argc, argv, ":dsv:k::")) != EOF ) {
1958         switch(arg) {
1959                 case 'd':
1960                         logsink = 0;
1961                         //debug=1; /* ### comment me out ### */
1962                         break;
1963                 case 'v':
1964                         if (sizeof(optarg) > sizeof(char *) ||
1965                             !isdigit(optarg[0]))
1966                                 exit(1);
1967
1968                         conf->verbosity = atoi(optarg);
1969                         break;
1970                 case 's':
1971                         logsink = -1;
1972                         break;
1973                 case 'k':
1974                         uxclnt(optarg);
1975                         exit(0);
1976                 default:
1977                         ;
1978                 }
1979         }
1980         if (optind < argc) {
1981                 char cmd[CMDSIZE];
1982                 char * s = cmd;
1983                 char * c = s;
1984
1985                 while (optind < argc) {
1986                         if (strchr(argv[optind], ' '))
1987                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1988                         else
1989                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1990                         optind++;
1991                 }
1992                 c += snprintf(c, s + CMDSIZE - c, "\n");
1993                 uxclnt(s);
1994                 exit(0);
1995         }
1996
1997         if (logsink < 1)
1998                 err = 0;
1999         else
2000                 err = daemonize();
2001
2002         if (err < 0)
2003                 /* error */
2004                 exit(1);
2005         else if (err > 0)
2006                 /* parent dies */
2007                 exit(0);
2008         else
2009                 /* child lives */
2010                 return (child(NULL));
2011 }
2012
2013 void *  mpath_pr_event_handler_fn (void * pathp )
2014 {
2015         struct multipath * mpp;
2016         int i,j, ret, isFound;
2017         struct path * pp = (struct path *)pathp;
2018         unsigned char *keyp;
2019         uint64_t prkey;
2020         struct prout_param_descriptor *param;
2021         struct prin_resp *resp;
2022
2023         mpp = pp->mpp;
2024
2025         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
2026         if (!resp){
2027                 condlog(0,"%s Alloc failed for prin response", pp->dev);
2028                 return NULL;
2029         }
2030
2031         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
2032         if (ret != MPATH_PR_SUCCESS )
2033         {
2034                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
2035                 goto out;
2036         }
2037
2038         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
2039                         resp->prin_descriptor.prin_readkeys.additional_length );
2040
2041         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
2042         {
2043                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
2044                 ret = MPATH_PR_SUCCESS;
2045                 goto out;
2046         }
2047         prkey = 0;
2048         keyp = (unsigned char *)mpp->reservation_key;
2049         for (j = 0; j < 8; ++j) {
2050                 if (j > 0)
2051                         prkey <<= 8;
2052                 prkey |= *keyp;
2053                 ++keyp;
2054         }
2055         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ", prkey);
2056
2057         isFound =0;
2058         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
2059         {
2060                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
2061                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
2062                 if (!memcmp(mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
2063                 {
2064                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
2065                         isFound =1;
2066                         break;
2067                 }
2068         }
2069         if (!isFound)
2070         {
2071                 condlog(0, "%s: Either device not registered or ", pp->dev);
2072                 condlog(0, "host is not authorised for registration. Skip path");
2073                 ret = MPATH_PR_OTHER;
2074                 goto out;
2075         }
2076
2077         param= malloc(sizeof(struct prout_param_descriptor));
2078         memset(param, 0 , sizeof(struct prout_param_descriptor));
2079
2080         for (j = 7; j >= 0; --j) {
2081                 param->sa_key[j] = (prkey & 0xff);
2082                 prkey >>= 8;
2083         }
2084         param->num_transportid = 0;
2085
2086         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
2087
2088         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
2089         if (ret != MPATH_PR_SUCCESS )
2090         {
2091                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
2092         }
2093         mpp->prflag = 1;
2094
2095         free(param);
2096 out:
2097         free(resp);
2098         return NULL;
2099 }
2100
2101 int mpath_pr_event_handle(struct path *pp)
2102 {
2103         pthread_t thread;
2104         int rc;
2105         pthread_attr_t attr;
2106         struct multipath * mpp;
2107
2108         mpp = pp->mpp;
2109
2110         if (!mpp->reservation_key)
2111                 return -1;
2112
2113         pthread_attr_init(&attr);
2114         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
2115
2116         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
2117         if (rc) {
2118                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
2119                 return -1;
2120         }
2121         pthread_attr_destroy(&attr);
2122         rc = pthread_join(thread, NULL);
2123         return 0;
2124 }
2125