18b225ab64b79ebfdd54839c0f8e0e8c6e608163
[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 > 0) {
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         } else {
1700                 conf = old;
1701         }
1702
1703         running_state = DAEMON_RUNNING;
1704
1705         return retval;
1706 }
1707
1708 static struct vectors *
1709 init_vecs (void)
1710 {
1711         struct vectors * vecs;
1712
1713         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1714
1715         if (!vecs)
1716                 return NULL;
1717
1718         vecs->lock.mutex =
1719                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1720
1721         if (!vecs->lock.mutex)
1722                 goto out;
1723
1724         pthread_mutex_init(vecs->lock.mutex, NULL);
1725         vecs->lock.depth = 0;
1726
1727         return vecs;
1728
1729 out:
1730         FREE(vecs);
1731         condlog(0, "failed to init paths");
1732         return NULL;
1733 }
1734
1735 static void *
1736 signal_set(int signo, void (*func) (int))
1737 {
1738         int r;
1739         struct sigaction sig;
1740         struct sigaction osig;
1741
1742         sig.sa_handler = func;
1743         sigemptyset(&sig.sa_mask);
1744         sig.sa_flags = 0;
1745
1746         r = sigaction(signo, &sig, &osig);
1747
1748         if (r < 0)
1749                 return (SIG_ERR);
1750         else
1751                 return (osig.sa_handler);
1752 }
1753
1754 void
1755 handle_signals(void)
1756 {
1757         if (reconfig_sig && running_state == DAEMON_RUNNING) {
1758                 pthread_cleanup_push(cleanup_lock,
1759                                 &gvecs->lock);
1760                 lock(gvecs->lock);
1761                 pthread_testcancel();
1762                 if (need_to_delay_reconfig(gvecs)) {
1763                         conf->delayed_reconfig = 1;
1764                         condlog(2, "delaying reconfigure (signal)");
1765                 }
1766                 else {
1767                         condlog(2, "reconfigure (signal)");
1768                         reconfigure(gvecs);
1769                 }
1770                 lock_cleanup_pop(gvecs->lock);
1771         }
1772         if (log_reset_sig) {
1773                 condlog(2, "reset log (signal)");
1774                 pthread_mutex_lock(&logq_lock);
1775                 log_reset("multipathd");
1776                 pthread_mutex_unlock(&logq_lock);
1777         }
1778         reconfig_sig = 0;
1779         log_reset_sig = 0;
1780 }
1781
1782 static void
1783 sighup (int sig)
1784 {
1785         reconfig_sig = 1;
1786 }
1787
1788 static void
1789 sigend (int sig)
1790 {
1791         exit_daemon();
1792 }
1793
1794 static void
1795 sigusr1 (int sig)
1796 {
1797         log_reset_sig = 1;
1798 }
1799
1800 static void
1801 sigusr2 (int sig)
1802 {
1803         condlog(3, "SIGUSR2 received");
1804 }
1805
1806 static void
1807 signal_init(void)
1808 {
1809         sigset_t set;
1810
1811         sigemptyset(&set);
1812         sigaddset(&set, SIGHUP);
1813         sigaddset(&set, SIGUSR1);
1814         sigaddset(&set, SIGUSR2);
1815         pthread_sigmask(SIG_BLOCK, &set, NULL);
1816
1817         signal_set(SIGHUP, sighup);
1818         signal_set(SIGUSR1, sigusr1);
1819         signal_set(SIGUSR2, sigusr2);
1820         signal_set(SIGINT, sigend);
1821         signal_set(SIGTERM, sigend);
1822         signal(SIGPIPE, SIG_IGN);
1823 }
1824
1825 static void
1826 setscheduler (void)
1827 {
1828         int res;
1829         static struct sched_param sched_param = {
1830                 .sched_priority = 99
1831         };
1832
1833         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1834
1835         if (res == -1)
1836                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1837         return;
1838 }
1839
1840 static void
1841 set_oom_adj (void)
1842 {
1843 #ifdef OOM_SCORE_ADJ_MIN
1844         int retry = 1;
1845         char *file = "/proc/self/oom_score_adj";
1846         int score = OOM_SCORE_ADJ_MIN;
1847 #else
1848         int retry = 0;
1849         char *file = "/proc/self/oom_adj";
1850         int score = OOM_ADJUST_MIN;
1851 #endif
1852         FILE *fp;
1853         struct stat st;
1854         char *envp;
1855
1856         envp = getenv("OOMScoreAdjust");
1857         if (envp) {
1858                 condlog(3, "Using systemd provided OOMScoreAdjust");
1859                 return;
1860         }
1861         do {
1862                 if (stat(file, &st) == 0){
1863                         fp = fopen(file, "w");
1864                         if (!fp) {
1865                                 condlog(0, "couldn't fopen %s : %s", file,
1866                                         strerror(errno));
1867                                 return;
1868                         }
1869                         fprintf(fp, "%i", score);
1870                         fclose(fp);
1871                         return;
1872                 }
1873                 if (errno != ENOENT) {
1874                         condlog(0, "couldn't stat %s : %s", file,
1875                                 strerror(errno));
1876                         return;
1877                 }
1878 #ifdef OOM_ADJUST_MIN
1879                 file = "/proc/self/oom_adj";
1880                 score = OOM_ADJUST_MIN;
1881 #else
1882                 retry = 0;
1883 #endif
1884         } while (retry--);
1885         condlog(0, "couldn't adjust oom score");
1886 }
1887
1888 static int
1889 child (void * param)
1890 {
1891         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1892         pthread_attr_t log_attr, misc_attr, uevent_attr;
1893         struct vectors * vecs;
1894         struct multipath * mpp;
1895         int i;
1896 #ifdef USE_SYSTEMD
1897         unsigned long checkint;
1898 #endif
1899         int rc;
1900         char *envp;
1901
1902         mlockall(MCL_CURRENT | MCL_FUTURE);
1903         sem_init(&exit_sem, 0, 0);
1904         signal_init();
1905
1906         udev = udev_new();
1907
1908         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1909         setup_thread_attr(&uevent_attr, DEFAULT_UEVENT_STACKSIZE * 1024, 1);
1910         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1911
1912         if (logsink == 1) {
1913                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1914                 log_thread_start(&log_attr);
1915                 pthread_attr_destroy(&log_attr);
1916         }
1917         if (pidfile_create(DEFAULT_PIDFILE, daemon_pid)) {
1918                 condlog(1, "failed to create pidfile");
1919                 if (logsink == 1)
1920                         log_thread_stop();
1921                 exit(1);
1922         }
1923
1924         running_state = DAEMON_START;
1925
1926 #ifdef USE_SYSTEMD
1927         sd_notify(0, "STATUS=startup");
1928 #endif
1929         condlog(2, "--------start up--------");
1930         condlog(2, "read " DEFAULT_CONFIGFILE);
1931
1932         if (load_config(DEFAULT_CONFIGFILE, udev))
1933                 goto failed;
1934
1935         dm_drv_version(conf->version, TGT_MPATH);
1936         if (init_checkers()) {
1937                 condlog(0, "failed to initialize checkers");
1938                 goto failed;
1939         }
1940         if (init_prio()) {
1941                 condlog(0, "failed to initialize prioritizers");
1942                 goto failed;
1943         }
1944
1945         setlogmask(LOG_UPTO(conf->verbosity + 3));
1946
1947         envp = getenv("LimitNOFILE");
1948
1949         if (envp) {
1950                 condlog(2,"Using systemd provided open fds limit of %s", envp);
1951         } else if (conf->max_fds) {
1952                 struct rlimit fd_limit;
1953
1954                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1955                         condlog(0, "can't get open fds limit: %s",
1956                                 strerror(errno));
1957                         fd_limit.rlim_cur = 0;
1958                         fd_limit.rlim_max = 0;
1959                 }
1960                 if (fd_limit.rlim_cur < conf->max_fds) {
1961                         fd_limit.rlim_cur = conf->max_fds;
1962                         if (fd_limit.rlim_max < conf->max_fds)
1963                                 fd_limit.rlim_max = conf->max_fds;
1964                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1965                                 condlog(0, "can't set open fds limit to "
1966                                         "%lu/%lu : %s",
1967                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1968                                         strerror(errno));
1969                         } else {
1970                                 condlog(3, "set open fds limit to %lu/%lu",
1971                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1972                         }
1973                 }
1974
1975         }
1976
1977         vecs = gvecs = init_vecs();
1978         if (!vecs)
1979                 goto failed;
1980
1981         setscheduler();
1982         set_oom_adj();
1983
1984         conf->daemon = 1;
1985         dm_udev_set_sync_support(0);
1986 #ifdef USE_SYSTEMD
1987         envp = getenv("WATCHDOG_USEC");
1988         if (envp && sscanf(envp, "%lu", &checkint) == 1) {
1989                 /* Value is in microseconds */
1990                 conf->max_checkint = checkint / 1000000;
1991                 /* Rescale checkint */
1992                 if (conf->checkint > conf->max_checkint)
1993                         conf->checkint = conf->max_checkint;
1994                 else
1995                         conf->checkint = conf->max_checkint / 4;
1996                 condlog(3, "enabling watchdog, interval %d max %d",
1997                         conf->checkint, conf->max_checkint);
1998                 use_watchdog = conf->checkint;
1999         }
2000 #endif
2001         /*
2002          * Start uevent listener early to catch events
2003          */
2004         if ((rc = pthread_create(&uevent_thr, &uevent_attr, ueventloop, udev))) {
2005                 condlog(0, "failed to create uevent thread: %d", rc);
2006                 goto failed;
2007         }
2008         pthread_attr_destroy(&uevent_attr);
2009         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
2010                 condlog(0, "failed to create cli listener: %d", rc);
2011                 goto failed;
2012         }
2013         /*
2014          * fetch and configure both paths and multipaths
2015          */
2016 #ifdef USE_SYSTEMD
2017         sd_notify(0, "STATUS=configure");
2018 #endif
2019         running_state = DAEMON_CONFIGURE;
2020
2021         lock(vecs->lock);
2022         if (configure(vecs, 1)) {
2023                 unlock(vecs->lock);
2024                 condlog(0, "failure during configuration");
2025                 goto failed;
2026         }
2027         unlock(vecs->lock);
2028
2029         /*
2030          * start threads
2031          */
2032         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
2033                 condlog(0,"failed to create checker loop thread: %d", rc);
2034                 goto failed;
2035         }
2036         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
2037                 condlog(0, "failed to create uevent dispatcher: %d", rc);
2038                 goto failed;
2039         }
2040         pthread_attr_destroy(&misc_attr);
2041
2042         running_state = DAEMON_RUNNING;
2043 #ifdef USE_SYSTEMD
2044         sd_notify(0, "READY=1\nSTATUS=running");
2045 #endif
2046
2047         /*
2048          * exit path
2049          */
2050         while(sem_wait(&exit_sem) != 0); /* Do nothing */
2051
2052 #ifdef USE_SYSTEMD
2053         sd_notify(0, "STATUS=shutdown");
2054 #endif
2055         running_state = DAEMON_SHUTDOWN;
2056         lock(vecs->lock);
2057         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
2058                 vector_foreach_slot(vecs->mpvec, mpp, i)
2059                         dm_queue_if_no_path(mpp->alias, 0);
2060         remove_maps_and_stop_waiters(vecs);
2061         unlock(vecs->lock);
2062
2063         pthread_cancel(check_thr);
2064         pthread_cancel(uevent_thr);
2065         pthread_cancel(uxlsnr_thr);
2066         pthread_cancel(uevq_thr);
2067
2068         lock(vecs->lock);
2069         free_pathvec(vecs->pathvec, FREE_PATHS);
2070         vecs->pathvec = NULL;
2071         unlock(vecs->lock);
2072         /* Now all the waitevent threads will start rushing in. */
2073         while (vecs->lock.depth > 0) {
2074                 sleep (1); /* This is weak. */
2075                 condlog(3, "Have %d wait event checkers threads to de-alloc,"
2076                         " waiting...", vecs->lock.depth);
2077         }
2078         pthread_mutex_destroy(vecs->lock.mutex);
2079         FREE(vecs->lock.mutex);
2080         vecs->lock.depth = 0;
2081         vecs->lock.mutex = NULL;
2082         FREE(vecs);
2083         vecs = NULL;
2084
2085         cleanup_checkers();
2086         cleanup_prio();
2087
2088         dm_lib_release();
2089         dm_lib_exit();
2090
2091         /* We're done here */
2092         condlog(3, "unlink pidfile");
2093         unlink(DEFAULT_PIDFILE);
2094
2095         condlog(2, "--------shut down-------");
2096
2097         if (logsink == 1)
2098                 log_thread_stop();
2099
2100         /*
2101          * Freeing config must be done after condlog() and dm_lib_exit(),
2102          * because logging functions like dlog() and dm_write_log()
2103          * reference the config.
2104          */
2105         free_config(conf);
2106         conf = NULL;
2107         udev_unref(udev);
2108         udev = NULL;
2109 #ifdef _DEBUG_
2110         dbg_free_final(NULL);
2111 #endif
2112
2113 #ifdef USE_SYSTEMD
2114         sd_notify(0, "ERRNO=0");
2115 #endif
2116         exit(0);
2117
2118 failed:
2119 #ifdef USE_SYSTEMD
2120         sd_notify(0, "ERRNO=1");
2121 #endif
2122         exit(1);
2123 }
2124
2125 static int
2126 daemonize(void)
2127 {
2128         int pid;
2129         int dev_null_fd;
2130
2131         if( (pid = fork()) < 0){
2132                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
2133                 return -1;
2134         }
2135         else if (pid != 0)
2136                 return pid;
2137
2138         setsid();
2139
2140         if ( (pid = fork()) < 0)
2141                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
2142         else if (pid != 0)
2143                 _exit(0);
2144
2145         if (chdir("/") < 0)
2146                 fprintf(stderr, "cannot chdir to '/', continuing\n");
2147
2148         dev_null_fd = open("/dev/null", O_RDWR);
2149         if (dev_null_fd < 0){
2150                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
2151                         strerror(errno));
2152                 _exit(0);
2153         }
2154
2155         close(STDIN_FILENO);
2156         if (dup(dev_null_fd) < 0) {
2157                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
2158                         strerror(errno));
2159                 _exit(0);
2160         }
2161         close(STDOUT_FILENO);
2162         if (dup(dev_null_fd) < 0) {
2163                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
2164                         strerror(errno));
2165                 _exit(0);
2166         }
2167         close(STDERR_FILENO);
2168         if (dup(dev_null_fd) < 0) {
2169                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
2170                         strerror(errno));
2171                 _exit(0);
2172         }
2173         close(dev_null_fd);
2174         daemon_pid = getpid();
2175         return 0;
2176 }
2177
2178 int
2179 main (int argc, char *argv[])
2180 {
2181         extern char *optarg;
2182         extern int optind;
2183         int arg;
2184         int err;
2185         int foreground = 0;
2186
2187         logsink = 1;
2188         running_state = DAEMON_INIT;
2189         dm_init();
2190
2191         if (getuid() != 0) {
2192                 fprintf(stderr, "need to be root\n");
2193                 exit(1);
2194         }
2195
2196         /* make sure we don't lock any path */
2197         if (chdir("/") < 0)
2198                 fprintf(stderr, "can't chdir to root directory : %s\n",
2199                         strerror(errno));
2200         umask(umask(077) | 022);
2201
2202         conf = alloc_config();
2203
2204         if (!conf)
2205                 exit(1);
2206
2207         while ((arg = getopt(argc, argv, ":dsv:k::Bn")) != EOF ) {
2208         switch(arg) {
2209                 case 'd':
2210                         foreground = 1;
2211                         if (logsink > 0)
2212                                 logsink = 0;
2213                         //debug=1; /* ### comment me out ### */
2214                         break;
2215                 case 'v':
2216                         if (sizeof(optarg) > sizeof(char *) ||
2217                             !isdigit(optarg[0]))
2218                                 exit(1);
2219
2220                         conf->verbosity = atoi(optarg);
2221                         break;
2222                 case 's':
2223                         logsink = -1;
2224                         break;
2225                 case 'k':
2226                         if (load_config(DEFAULT_CONFIGFILE, udev_new()))
2227                                 exit(1);
2228                         uxclnt(optarg, conf->uxsock_timeout);
2229                         exit(0);
2230                 case 'B':
2231                         conf->bindings_read_only = 1;
2232                         break;
2233                 case 'n':
2234                         conf->ignore_new_devs = 1;
2235                         break;
2236                 default:
2237                         ;
2238                 }
2239         }
2240         if (optind < argc) {
2241                 char cmd[CMDSIZE];
2242                 char * s = cmd;
2243                 char * c = s;
2244
2245                 if (load_config(DEFAULT_CONFIGFILE, udev_new()))
2246                         exit(1);
2247                 memset(cmd, 0x0, CMDSIZE);
2248                 while (optind < argc) {
2249                         if (strchr(argv[optind], ' '))
2250                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
2251                         else
2252                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
2253                         optind++;
2254                 }
2255                 c += snprintf(c, s + CMDSIZE - c, "\n");
2256                 uxclnt(s, conf->uxsock_timeout);
2257                 exit(0);
2258         }
2259
2260         if (foreground) {
2261                 if (!isatty(fileno(stdout)))
2262                         setbuf(stdout, NULL);
2263                 err = 0;
2264                 daemon_pid = getpid();
2265         } else
2266                 err = daemonize();
2267
2268         if (err < 0)
2269                 /* error */
2270                 exit(1);
2271         else if (err > 0)
2272                 /* parent dies */
2273                 exit(0);
2274         else
2275                 /* child lives */
2276                 return (child(NULL));
2277 }
2278
2279 void *  mpath_pr_event_handler_fn (void * pathp )
2280 {
2281         struct multipath * mpp;
2282         int i,j, ret, isFound;
2283         struct path * pp = (struct path *)pathp;
2284         unsigned char *keyp;
2285         uint64_t prkey;
2286         struct prout_param_descriptor *param;
2287         struct prin_resp *resp;
2288
2289         mpp = pp->mpp;
2290
2291         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
2292         if (!resp){
2293                 condlog(0,"%s Alloc failed for prin response", pp->dev);
2294                 return NULL;
2295         }
2296
2297         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
2298         if (ret != MPATH_PR_SUCCESS )
2299         {
2300                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
2301                 goto out;
2302         }
2303
2304         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
2305                         resp->prin_descriptor.prin_readkeys.additional_length );
2306
2307         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
2308         {
2309                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
2310                 ret = MPATH_PR_SUCCESS;
2311                 goto out;
2312         }
2313         prkey = 0;
2314         keyp = (unsigned char *)mpp->reservation_key;
2315         for (j = 0; j < 8; ++j) {
2316                 if (j > 0)
2317                         prkey <<= 8;
2318                 prkey |= *keyp;
2319                 ++keyp;
2320         }
2321         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ", prkey);
2322
2323         isFound =0;
2324         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
2325         {
2326                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
2327                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
2328                 if (!memcmp(mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
2329                 {
2330                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
2331                         isFound =1;
2332                         break;
2333                 }
2334         }
2335         if (!isFound)
2336         {
2337                 condlog(0, "%s: Either device not registered or ", pp->dev);
2338                 condlog(0, "host is not authorised for registration. Skip path");
2339                 ret = MPATH_PR_OTHER;
2340                 goto out;
2341         }
2342
2343         param= malloc(sizeof(struct prout_param_descriptor));
2344         memset(param, 0 , sizeof(struct prout_param_descriptor));
2345
2346         for (j = 7; j >= 0; --j) {
2347                 param->sa_key[j] = (prkey & 0xff);
2348                 prkey >>= 8;
2349         }
2350         param->num_transportid = 0;
2351
2352         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
2353
2354         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
2355         if (ret != MPATH_PR_SUCCESS )
2356         {
2357                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
2358         }
2359         mpp->prflag = 1;
2360
2361         free(param);
2362 out:
2363         free(resp);
2364         return NULL;
2365 }
2366
2367 int mpath_pr_event_handle(struct path *pp)
2368 {
2369         pthread_t thread;
2370         int rc;
2371         pthread_attr_t attr;
2372         struct multipath * mpp;
2373
2374         mpp = pp->mpp;
2375
2376         if (!mpp->reservation_key)
2377                 return -1;
2378
2379         pthread_attr_init(&attr);
2380         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
2381
2382         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
2383         if (rc) {
2384                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
2385                 return -1;
2386         }
2387         pthread_attr_destroy(&attr);
2388         rc = pthread_join(thread, NULL);
2389         return 0;
2390 }
2391