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