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