04f02d99e4af7b9528d7d8a6a458ea4abb756b4e
[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 <sys/wait.h>
11 #include <sys/mman.h>
12 #include <sys/types.h>
13 #include <fcntl.h>
14 #include <errno.h>
15 #include <limits.h>
16 #include <linux/oom.h>
17 #include <libudev.h>
18 #include <urcu.h>
19 #ifdef USE_SYSTEMD
20 #include <systemd/sd-daemon.h>
21 #endif
22 #include <semaphore.h>
23 #include <time.h>
24 #include <stdbool.h>
25
26 /*
27  * libmultipath
28  */
29 #include "time-util.h"
30
31 /*
32  * libcheckers
33  */
34 #include "checkers.h"
35
36 #ifdef USE_SYSTEMD
37 static int use_watchdog;
38 #endif
39
40 /*
41  * libmultipath
42  */
43 #include "parser.h"
44 #include "vector.h"
45 #include "memory.h"
46 #include "config.h"
47 #include "util.h"
48 #include "hwtable.h"
49 #include "defaults.h"
50 #include "structs.h"
51 #include "blacklist.h"
52 #include "structs_vec.h"
53 #include "dmparser.h"
54 #include "devmapper.h"
55 #include "sysfs.h"
56 #include "dict.h"
57 #include "discovery.h"
58 #include "debug.h"
59 #include "propsel.h"
60 #include "uevent.h"
61 #include "switchgroup.h"
62 #include "print.h"
63 #include "configure.h"
64 #include "prio.h"
65 #include "wwids.h"
66 #include "pgpolicies.h"
67 #include "uevent.h"
68 #include "log.h"
69 #include "uxsock.h"
70
71 #include "mpath_cmd.h"
72 #include "mpath_persist.h"
73
74 #include "prioritizers/alua_rtpg.h"
75
76 #include "main.h"
77 #include "pidfile.h"
78 #include "uxlsnr.h"
79 #include "uxclnt.h"
80 #include "cli.h"
81 #include "cli_handlers.h"
82 #include "lock.h"
83 #include "waiter.h"
84 #include "dmevents.h"
85 #include "io_err_stat.h"
86 #include "wwids.h"
87 #include "foreign.h"
88 #include "../third-party/valgrind/drd.h"
89
90 #define FILE_NAME_SIZE 256
91 #define CMDSIZE 160
92
93 #define LOG_MSG(lvl, verb, pp)                                  \
94 do {                                                            \
95         if (lvl <= verb) {                                      \
96                 if (pp->offline)                                \
97                         condlog(lvl, "%s: %s - path offline",   \
98                                 pp->mpp->alias, pp->dev);       \
99                 else  {                                         \
100                         const char *__m =                       \
101                                 checker_message(&pp->checker);  \
102                                                                 \
103                         if (strlen(__m))                              \
104                                 condlog(lvl, "%s: %s - %s checker%s", \
105                                         pp->mpp->alias,               \
106                                         pp->dev,                      \
107                                         checker_name(&pp->checker),   \
108                                         __m);                         \
109                 }                                                     \
110         }                                                             \
111 } while(0)
112
113 struct mpath_event_param
114 {
115         char * devname;
116         struct multipath *mpp;
117 };
118
119 int logsink;
120 int uxsock_timeout;
121 int verbosity;
122 int bindings_read_only;
123 int ignore_new_devs;
124 #ifdef NO_DMEVENTS_POLL
125 int poll_dmevents = 0;
126 #else
127 int poll_dmevents = 1;
128 #endif
129 enum daemon_status running_state = DAEMON_INIT;
130 pid_t daemon_pid;
131 pthread_mutex_t config_lock = PTHREAD_MUTEX_INITIALIZER;
132 pthread_cond_t config_cond;
133
134 /*
135  * global copy of vecs for use in sig handlers
136  */
137 struct vectors * gvecs;
138
139 struct udev * udev;
140
141 struct config *multipath_conf;
142
143 /* Local variables */
144 static volatile sig_atomic_t exit_sig;
145 static volatile sig_atomic_t reconfig_sig;
146 static volatile sig_atomic_t log_reset_sig;
147
148 const char *
149 daemon_status(void)
150 {
151         switch (running_state) {
152         case DAEMON_INIT:
153                 return "init";
154         case DAEMON_START:
155                 return "startup";
156         case DAEMON_CONFIGURE:
157                 return "configure";
158         case DAEMON_IDLE:
159                 return "idle";
160         case DAEMON_RUNNING:
161                 return "running";
162         case DAEMON_SHUTDOWN:
163                 return "shutdown";
164         }
165         return NULL;
166 }
167
168 /*
169  * I love you too, systemd ...
170  */
171 const char *
172 sd_notify_status(void)
173 {
174         switch (running_state) {
175         case DAEMON_INIT:
176                 return "STATUS=init";
177         case DAEMON_START:
178                 return "STATUS=startup";
179         case DAEMON_CONFIGURE:
180                 return "STATUS=configure";
181         case DAEMON_IDLE:
182         case DAEMON_RUNNING:
183                 return "STATUS=up";
184         case DAEMON_SHUTDOWN:
185                 return "STATUS=shutdown";
186         }
187         return NULL;
188 }
189
190 #ifdef USE_SYSTEMD
191 static void do_sd_notify(enum daemon_status old_state)
192 {
193         /*
194          * Checkerloop switches back and forth between idle and running state.
195          * No need to tell systemd each time.
196          * These notifications cause a lot of overhead on dbus.
197          */
198         if ((running_state == DAEMON_IDLE || running_state == DAEMON_RUNNING) &&
199             (old_state == DAEMON_IDLE || old_state == DAEMON_RUNNING))
200                 return;
201         sd_notify(0, sd_notify_status());
202 }
203 #endif
204
205 static void config_cleanup(void *arg)
206 {
207         pthread_mutex_unlock(&config_lock);
208 }
209
210 static void __post_config_state(enum daemon_status state)
211 {
212         if (state != running_state && running_state != DAEMON_SHUTDOWN) {
213                 enum daemon_status old_state = running_state;
214
215                 running_state = state;
216                 pthread_cond_broadcast(&config_cond);
217 #ifdef USE_SYSTEMD
218                 do_sd_notify(old_state);
219 #endif
220         }
221 }
222
223 void post_config_state(enum daemon_status state)
224 {
225         pthread_mutex_lock(&config_lock);
226         pthread_cleanup_push(config_cleanup, NULL);
227         __post_config_state(state);
228         pthread_cleanup_pop(1);
229 }
230
231 int set_config_state(enum daemon_status state)
232 {
233         int rc = 0;
234
235         pthread_cleanup_push(config_cleanup, NULL);
236         pthread_mutex_lock(&config_lock);
237         if (running_state != state) {
238                 enum daemon_status old_state = running_state;
239
240                 if (running_state == DAEMON_SHUTDOWN)
241                         rc = EINVAL;
242                 else if (running_state != DAEMON_IDLE) {
243                         struct timespec ts;
244
245                         clock_gettime(CLOCK_MONOTONIC, &ts);
246                         ts.tv_sec += 1;
247                         rc = pthread_cond_timedwait(&config_cond,
248                                                     &config_lock, &ts);
249                 }
250                 if (!rc) {
251                         running_state = state;
252                         pthread_cond_broadcast(&config_cond);
253 #ifdef USE_SYSTEMD
254                         do_sd_notify(old_state);
255 #endif
256                 }
257         }
258         pthread_cleanup_pop(1);
259         return rc;
260 }
261
262 struct config *get_multipath_config(void)
263 {
264         rcu_read_lock();
265         return rcu_dereference(multipath_conf);
266 }
267
268 void put_multipath_config(void *arg)
269 {
270         rcu_read_unlock();
271 }
272
273 static int
274 need_switch_pathgroup (struct multipath * mpp, int refresh)
275 {
276         struct pathgroup * pgp;
277         struct path * pp;
278         unsigned int i, j;
279         struct config *conf;
280         int bestpg;
281
282         if (!mpp)
283                 return 0;
284
285         /*
286          * Refresh path priority values
287          */
288         if (refresh) {
289                 vector_foreach_slot (mpp->pg, pgp, i) {
290                         vector_foreach_slot (pgp->paths, pp, j) {
291                                 conf = get_multipath_config();
292                                 pthread_cleanup_push(put_multipath_config,
293                                                      conf);
294                                 pathinfo(pp, conf, DI_PRIO);
295                                 pthread_cleanup_pop(1);
296                         }
297                 }
298         }
299
300         if (!mpp->pg || VECTOR_SIZE(mpp->paths) == 0)
301                 return 0;
302
303         bestpg = select_path_group(mpp);
304         if (mpp->pgfailback == -FAILBACK_MANUAL)
305                 return 0;
306
307         mpp->bestpg = bestpg;
308         if (mpp->bestpg != mpp->nextpg)
309                 return 1;
310
311         return 0;
312 }
313
314 static void
315 switch_pathgroup (struct multipath * mpp)
316 {
317         mpp->stat_switchgroup++;
318         dm_switchgroup(mpp->alias, mpp->bestpg);
319         condlog(2, "%s: switch to path group #%i",
320                  mpp->alias, mpp->bestpg);
321 }
322
323 static int
324 wait_for_events(struct multipath *mpp, struct vectors *vecs)
325 {
326         if (poll_dmevents)
327                 return watch_dmevents(mpp->alias);
328         else
329                 return start_waiter_thread(mpp, vecs);
330 }
331
332 static void
333 remove_map_and_stop_waiter(struct multipath *mpp, struct vectors *vecs)
334 {
335         /* devices are automatically removed by the dmevent polling code,
336          * so they don't need to be manually removed here */
337         condlog(3, "%s: removing map from internal tables", mpp->alias);
338         if (!poll_dmevents)
339                 stop_waiter_thread(mpp, vecs);
340         remove_map(mpp, vecs, PURGE_VEC);
341 }
342
343 static void
344 remove_maps_and_stop_waiters(struct vectors *vecs)
345 {
346         int i;
347         struct multipath * mpp;
348
349         if (!vecs)
350                 return;
351
352         if (!poll_dmevents) {
353                 vector_foreach_slot(vecs->mpvec, mpp, i)
354                         stop_waiter_thread(mpp, vecs);
355         }
356         else
357                 unwatch_all_dmevents();
358
359         remove_maps(vecs);
360 }
361
362 static void
363 set_multipath_wwid (struct multipath * mpp)
364 {
365         if (strlen(mpp->wwid))
366                 return;
367
368         dm_get_uuid(mpp->alias, mpp->wwid);
369 }
370
371 static void set_no_path_retry(struct multipath *mpp)
372 {
373         char is_queueing = 0;
374
375         mpp->nr_active = pathcount(mpp, PATH_UP) + pathcount(mpp, PATH_GHOST);
376         if (mpp->features && strstr(mpp->features, "queue_if_no_path"))
377                 is_queueing = 1;
378
379         switch (mpp->no_path_retry) {
380         case NO_PATH_RETRY_UNDEF:
381                 break;
382         case NO_PATH_RETRY_FAIL:
383                 if (is_queueing)
384                         dm_queue_if_no_path(mpp->alias, 0);
385                 break;
386         case NO_PATH_RETRY_QUEUE:
387                 if (!is_queueing)
388                         dm_queue_if_no_path(mpp->alias, 1);
389                 break;
390         default:
391                 if (mpp->nr_active > 0) {
392                         mpp->retry_tick = 0;
393                         dm_queue_if_no_path(mpp->alias, 1);
394                 } else if (is_queueing && mpp->retry_tick == 0)
395                         enter_recovery_mode(mpp);
396                 break;
397         }
398 }
399
400 int __setup_multipath(struct vectors *vecs, struct multipath *mpp,
401                       int reset)
402 {
403         if (dm_get_info(mpp->alias, &mpp->dmi)) {
404                 /* Error accessing table */
405                 condlog(3, "%s: cannot access table", mpp->alias);
406                 goto out;
407         }
408
409         if (update_multipath_strings(mpp, vecs->pathvec, 1)) {
410                 condlog(0, "%s: failed to setup multipath", mpp->alias);
411                 goto out;
412         }
413
414         if (reset) {
415                 set_no_path_retry(mpp);
416                 if (VECTOR_SIZE(mpp->paths) != 0)
417                         dm_cancel_deferred_remove(mpp);
418         }
419
420         return 0;
421 out:
422         remove_map_and_stop_waiter(mpp, vecs);
423         return 1;
424 }
425
426 int update_multipath (struct vectors *vecs, char *mapname, int reset)
427 {
428         struct multipath *mpp;
429         struct pathgroup  *pgp;
430         struct path *pp;
431         int i, j;
432
433         mpp = find_mp_by_alias(vecs->mpvec, mapname);
434
435         if (!mpp) {
436                 condlog(3, "%s: multipath map not found", mapname);
437                 return 2;
438         }
439
440         if (__setup_multipath(vecs, mpp, reset))
441                 return 1; /* mpp freed in setup_multipath */
442
443         /*
444          * compare checkers states with DM states
445          */
446         vector_foreach_slot (mpp->pg, pgp, i) {
447                 vector_foreach_slot (pgp->paths, pp, j) {
448                         if (pp->dmstate != PSTATE_FAILED)
449                                 continue;
450
451                         if (pp->state != PATH_DOWN) {
452                                 struct config *conf;
453                                 int oldstate = pp->state;
454                                 int checkint;
455
456                                 conf = get_multipath_config();
457                                 checkint = conf->checkint;
458                                 put_multipath_config(conf);
459                                 condlog(2, "%s: mark as failed", pp->dev);
460                                 mpp->stat_path_failures++;
461                                 pp->state = PATH_DOWN;
462                                 if (oldstate == PATH_UP ||
463                                     oldstate == PATH_GHOST)
464                                         update_queue_mode_del_path(mpp);
465
466                                 /*
467                                  * if opportune,
468                                  * schedule the next check earlier
469                                  */
470                                 if (pp->tick > checkint)
471                                         pp->tick = checkint;
472                         }
473                 }
474         }
475         return 0;
476 }
477
478 static int
479 update_map (struct multipath *mpp, struct vectors *vecs, int new_map)
480 {
481         int retries = 3;
482         char params[PARAMS_SIZE] = {0};
483
484 retry:
485         condlog(4, "%s: updating new map", mpp->alias);
486         if (adopt_paths(vecs->pathvec, mpp)) {
487                 condlog(0, "%s: failed to adopt paths for new map update",
488                         mpp->alias);
489                 retries = -1;
490                 goto fail;
491         }
492         verify_paths(mpp, vecs);
493         mpp->action = ACT_RELOAD;
494
495         if (setup_map(mpp, params, PARAMS_SIZE, vecs)) {
496                 condlog(0, "%s: failed to setup new map in update", mpp->alias);
497                 retries = -1;
498                 goto fail;
499         }
500         if (domap(mpp, params, 1) <= 0 && retries-- > 0) {
501                 condlog(0, "%s: map_udate sleep", mpp->alias);
502                 sleep(1);
503                 goto retry;
504         }
505         dm_lib_release();
506
507 fail:
508         if (new_map && (retries < 0 || wait_for_events(mpp, vecs))) {
509                 condlog(0, "%s: failed to create new map", mpp->alias);
510                 remove_map(mpp, vecs, 1);
511                 return 1;
512         }
513
514         if (setup_multipath(vecs, mpp))
515                 return 1;
516
517         sync_map_state(mpp);
518
519         if (retries < 0)
520                 condlog(0, "%s: failed reload in new map update", mpp->alias);
521         return 0;
522 }
523
524 static struct multipath *
525 add_map_without_path (struct vectors *vecs, const char *alias)
526 {
527         struct multipath * mpp = alloc_multipath();
528         struct config *conf;
529
530         if (!mpp)
531                 return NULL;
532         if (!alias) {
533                 FREE(mpp);
534                 return NULL;
535         }
536
537         mpp->alias = STRDUP(alias);
538
539         if (dm_get_info(mpp->alias, &mpp->dmi)) {
540                 condlog(3, "%s: cannot access table", mpp->alias);
541                 goto out;
542         }
543         set_multipath_wwid(mpp);
544         conf = get_multipath_config();
545         mpp->mpe = find_mpe(conf->mptable, mpp->wwid);
546         put_multipath_config(conf);
547
548         if (update_multipath_table(mpp, vecs->pathvec, 1))
549                 goto out;
550         if (update_multipath_status(mpp))
551                 goto out;
552
553         if (!vector_alloc_slot(vecs->mpvec))
554                 goto out;
555
556         vector_set_slot(vecs->mpvec, mpp);
557
558         if (update_map(mpp, vecs, 1) != 0) /* map removed */
559                 return NULL;
560
561         return mpp;
562 out:
563         remove_map(mpp, vecs, PURGE_VEC);
564         return NULL;
565 }
566
567 static int
568 coalesce_maps(struct vectors *vecs, vector nmpv)
569 {
570         struct multipath * ompp;
571         vector ompv = vecs->mpvec;
572         unsigned int i, reassign_maps;
573         struct config *conf;
574
575         conf = get_multipath_config();
576         reassign_maps = conf->reassign_maps;
577         put_multipath_config(conf);
578         vector_foreach_slot (ompv, ompp, i) {
579                 condlog(3, "%s: coalesce map", ompp->alias);
580                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
581                         /*
582                          * remove all current maps not allowed by the
583                          * current configuration
584                          */
585                         if (dm_flush_map(ompp->alias)) {
586                                 condlog(0, "%s: unable to flush devmap",
587                                         ompp->alias);
588                                 /*
589                                  * may be just because the device is open
590                                  */
591                                 if (setup_multipath(vecs, ompp) != 0) {
592                                         i--;
593                                         continue;
594                                 }
595                                 if (!vector_alloc_slot(nmpv))
596                                         return 1;
597
598                                 vector_set_slot(nmpv, ompp);
599
600                                 vector_del_slot(ompv, i);
601                                 i--;
602                         }
603                         else {
604                                 dm_lib_release();
605                                 condlog(2, "%s devmap removed", ompp->alias);
606                         }
607                 } else if (reassign_maps) {
608                         condlog(3, "%s: Reassign existing device-mapper"
609                                 " devices", ompp->alias);
610                         dm_reassign(ompp->alias);
611                 }
612         }
613         return 0;
614 }
615
616 static void
617 sync_maps_state(vector mpvec)
618 {
619         unsigned int i;
620         struct multipath *mpp;
621
622         vector_foreach_slot (mpvec, mpp, i)
623                 sync_map_state(mpp);
624 }
625
626 static int
627 flush_map(struct multipath * mpp, struct vectors * vecs, int nopaths)
628 {
629         int r;
630
631         if (nopaths)
632                 r = dm_flush_map_nopaths(mpp->alias, mpp->deferred_remove);
633         else
634                 r = dm_flush_map(mpp->alias);
635         /*
636          * clear references to this map before flushing so we can ignore
637          * the spurious uevent we may generate with the dm_flush_map call below
638          */
639         if (r) {
640                 /*
641                  * May not really be an error -- if the map was already flushed
642                  * from the device mapper by dmsetup(8) for instance.
643                  */
644                 if (r == 1)
645                         condlog(0, "%s: can't flush", mpp->alias);
646                 else {
647                         condlog(2, "%s: devmap deferred remove", mpp->alias);
648                         mpp->deferred_remove = DEFERRED_REMOVE_IN_PROGRESS;
649                 }
650                 return r;
651         }
652         else {
653                 dm_lib_release();
654                 condlog(2, "%s: map flushed", mpp->alias);
655         }
656
657         orphan_paths(vecs->pathvec, mpp, "map flushed");
658         remove_map_and_stop_waiter(mpp, vecs);
659
660         return 0;
661 }
662
663 static int
664 uev_add_map (struct uevent * uev, struct vectors * vecs)
665 {
666         char *alias;
667         int major = -1, minor = -1, rc;
668
669         condlog(3, "%s: add map (uevent)", uev->kernel);
670         alias = uevent_get_dm_name(uev);
671         if (!alias) {
672                 condlog(3, "%s: No DM_NAME in uevent", uev->kernel);
673                 major = uevent_get_major(uev);
674                 minor = uevent_get_minor(uev);
675                 alias = dm_mapname(major, minor);
676                 if (!alias) {
677                         condlog(2, "%s: mapname not found for %d:%d",
678                                 uev->kernel, major, minor);
679                         return 1;
680                 }
681         }
682         pthread_cleanup_push(cleanup_lock, &vecs->lock);
683         lock(&vecs->lock);
684         pthread_testcancel();
685         rc = ev_add_map(uev->kernel, alias, vecs);
686         lock_cleanup_pop(vecs->lock);
687         FREE(alias);
688         return rc;
689 }
690
691 /*
692  * ev_add_map expects that the multipath device already exists in kernel
693  * before it is called. It just adds a device to multipathd or updates an
694  * existing device.
695  */
696 int
697 ev_add_map (char * dev, const char * alias, struct vectors * vecs)
698 {
699         struct multipath * mpp;
700         int delayed_reconfig, reassign_maps;
701         struct config *conf;
702
703         if (dm_is_mpath(alias) != 1) {
704                 condlog(4, "%s: not a multipath map", alias);
705                 return 0;
706         }
707
708         mpp = find_mp_by_alias(vecs->mpvec, alias);
709
710         if (mpp) {
711                 if (mpp->wait_for_udev > 1) {
712                         condlog(2, "%s: performing delayed actions",
713                                 mpp->alias);
714                         if (update_map(mpp, vecs, 0))
715                                 /* setup multipathd removed the map */
716                                 return 1;
717                 }
718                 conf = get_multipath_config();
719                 delayed_reconfig = conf->delayed_reconfig;
720                 reassign_maps = conf->reassign_maps;
721                 put_multipath_config(conf);
722                 if (mpp->wait_for_udev) {
723                         mpp->wait_for_udev = 0;
724                         if (delayed_reconfig &&
725                             !need_to_delay_reconfig(vecs)) {
726                                 condlog(2, "reconfigure (delayed)");
727                                 set_config_state(DAEMON_CONFIGURE);
728                                 return 0;
729                         }
730                 }
731                 /*
732                  * Not really an error -- we generate our own uevent
733                  * if we create a multipath mapped device as a result
734                  * of uev_add_path
735                  */
736                 if (reassign_maps) {
737                         condlog(3, "%s: Reassign existing device-mapper devices",
738                                 alias);
739                         dm_reassign(alias);
740                 }
741                 return 0;
742         }
743         condlog(2, "%s: adding map", alias);
744
745         /*
746          * now we can register the map
747          */
748         if ((mpp = add_map_without_path(vecs, alias))) {
749                 sync_map_state(mpp);
750                 condlog(2, "%s: devmap %s registered", alias, dev);
751                 return 0;
752         } else {
753                 condlog(2, "%s: ev_add_map failed", dev);
754                 return 1;
755         }
756 }
757
758 static int
759 uev_remove_map (struct uevent * uev, struct vectors * vecs)
760 {
761         char *alias;
762         int minor;
763         struct multipath *mpp;
764
765         condlog(3, "%s: remove map (uevent)", uev->kernel);
766         alias = uevent_get_dm_name(uev);
767         if (!alias) {
768                 condlog(3, "%s: No DM_NAME in uevent, ignoring", uev->kernel);
769                 return 0;
770         }
771         minor = uevent_get_minor(uev);
772
773         pthread_cleanup_push(cleanup_lock, &vecs->lock);
774         lock(&vecs->lock);
775         pthread_testcancel();
776         mpp = find_mp_by_minor(vecs->mpvec, minor);
777
778         if (!mpp) {
779                 condlog(2, "%s: devmap not registered, can't remove",
780                         uev->kernel);
781                 goto out;
782         }
783         if (strcmp(mpp->alias, alias)) {
784                 condlog(2, "%s: map alias mismatch: have \"%s\", got \"%s\")",
785                         uev->kernel, mpp->alias, alias);
786                 goto out;
787         }
788
789         remove_map_and_stop_waiter(mpp, vecs);
790 out:
791         lock_cleanup_pop(vecs->lock);
792         FREE(alias);
793         return 0;
794 }
795
796 /* Called from CLI handler */
797 int
798 ev_remove_map (char * devname, char * alias, int minor, struct vectors * vecs)
799 {
800         struct multipath * mpp;
801
802         mpp = find_mp_by_minor(vecs->mpvec, minor);
803
804         if (!mpp) {
805                 condlog(2, "%s: devmap not registered, can't remove",
806                         devname);
807                 return 1;
808         }
809         if (strcmp(mpp->alias, alias)) {
810                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
811                         mpp->alias, mpp->dmi->minor, minor);
812                 return 1;
813         }
814         return flush_map(mpp, vecs, 0);
815 }
816
817 static int
818 uev_add_path (struct uevent *uev, struct vectors * vecs, int need_do_map)
819 {
820         struct path *pp;
821         int ret = 0, i;
822         struct config *conf;
823
824         condlog(3, "%s: add path (uevent)", uev->kernel);
825         if (strstr(uev->kernel, "..") != NULL) {
826                 /*
827                  * Don't allow relative device names in the pathvec
828                  */
829                 condlog(0, "%s: path name is invalid", uev->kernel);
830                 return 1;
831         }
832
833         pthread_cleanup_push(cleanup_lock, &vecs->lock);
834         lock(&vecs->lock);
835         pthread_testcancel();
836         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
837         if (pp) {
838                 int r;
839
840                 condlog(3, "%s: spurious uevent, path already in pathvec",
841                         uev->kernel);
842                 if (!pp->mpp && !strlen(pp->wwid)) {
843                         condlog(3, "%s: reinitialize path", uev->kernel);
844                         udev_device_unref(pp->udev);
845                         pp->udev = udev_device_ref(uev->udev);
846                         conf = get_multipath_config();
847                         pthread_cleanup_push(put_multipath_config, conf);
848                         r = pathinfo(pp, conf,
849                                      DI_ALL | DI_BLACKLIST);
850                         pthread_cleanup_pop(1);
851                         if (r == PATHINFO_OK)
852                                 ret = ev_add_path(pp, vecs, need_do_map);
853                         else if (r == PATHINFO_SKIPPED) {
854                                 condlog(3, "%s: remove blacklisted path",
855                                         uev->kernel);
856                                 i = find_slot(vecs->pathvec, (void *)pp);
857                                 if (i != -1)
858                                         vector_del_slot(vecs->pathvec, i);
859                                 free_path(pp);
860                         } else {
861                                 condlog(0, "%s: failed to reinitialize path",
862                                         uev->kernel);
863                                 ret = 1;
864                         }
865                 }
866         }
867         lock_cleanup_pop(vecs->lock);
868         if (pp)
869                 return ret;
870
871         /*
872          * get path vital state
873          */
874         conf = get_multipath_config();
875         pthread_cleanup_push(put_multipath_config, conf);
876         ret = alloc_path_with_pathinfo(conf, uev->udev,
877                                        uev->wwid, DI_ALL, &pp);
878         pthread_cleanup_pop(1);
879         if (!pp) {
880                 if (ret == PATHINFO_SKIPPED)
881                         return 0;
882                 condlog(3, "%s: failed to get path info", uev->kernel);
883                 return 1;
884         }
885         pthread_cleanup_push(cleanup_lock, &vecs->lock);
886         lock(&vecs->lock);
887         pthread_testcancel();
888         ret = store_path(vecs->pathvec, pp);
889         if (!ret) {
890                 conf = get_multipath_config();
891                 pp->checkint = conf->checkint;
892                 put_multipath_config(conf);
893                 ret = ev_add_path(pp, vecs, need_do_map);
894         } else {
895                 condlog(0, "%s: failed to store path info, "
896                         "dropping event",
897                         uev->kernel);
898                 free_path(pp);
899                 ret = 1;
900         }
901         lock_cleanup_pop(vecs->lock);
902         return ret;
903 }
904
905 /*
906  * returns:
907  * 0: added
908  * 1: error
909  */
910 int
911 ev_add_path (struct path * pp, struct vectors * vecs, int need_do_map)
912 {
913         struct multipath * mpp;
914         char params[PARAMS_SIZE] = {0};
915         int retries = 3;
916         int start_waiter = 0;
917         int ret;
918
919         /*
920          * need path UID to go any further
921          */
922         if (strlen(pp->wwid) == 0) {
923                 condlog(0, "%s: failed to get path uid", pp->dev);
924                 goto fail; /* leave path added to pathvec */
925         }
926         mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
927         if (mpp && pp->size && mpp->size != pp->size) {
928                 condlog(0, "%s: failed to add new path %s, device size mismatch", mpp->alias, pp->dev);
929                 int i = find_slot(vecs->pathvec, (void *)pp);
930                 if (i != -1)
931                         vector_del_slot(vecs->pathvec, i);
932                 free_path(pp);
933                 return 1;
934         }
935         if (mpp && mpp->wait_for_udev &&
936             (pathcount(mpp, PATH_UP) > 0 ||
937              (pathcount(mpp, PATH_GHOST) > 0 && pp->tpgs != TPGS_IMPLICIT &&
938               mpp->ghost_delay_tick <= 0))) {
939                 /* if wait_for_udev is set and valid paths exist */
940                 condlog(3, "%s: delaying path addition until %s is fully initialized",
941                         pp->dev, mpp->alias);
942                 mpp->wait_for_udev = 2;
943                 orphan_path(pp, "waiting for create to complete");
944                 return 0;
945         }
946
947         pp->mpp = mpp;
948 rescan:
949         if (mpp) {
950                 condlog(4,"%s: adopting all paths for path %s",
951                         mpp->alias, pp->dev);
952                 if (adopt_paths(vecs->pathvec, mpp))
953                         goto fail; /* leave path added to pathvec */
954
955                 verify_paths(mpp, vecs);
956                 mpp->action = ACT_RELOAD;
957         } else {
958                 if (!should_multipath(pp, vecs->pathvec, vecs->mpvec)) {
959                         orphan_path(pp, "only one path");
960                         return 0;
961                 }
962                 condlog(4,"%s: creating new map", pp->dev);
963                 if ((mpp = add_map_with_path(vecs, pp, 1))) {
964                         mpp->action = ACT_CREATE;
965                         /*
966                          * We don't depend on ACT_CREATE, as domap will
967                          * set it to ACT_NOTHING when complete.
968                          */
969                         start_waiter = 1;
970                 }
971                 if (!start_waiter)
972                         goto fail; /* leave path added to pathvec */
973         }
974
975         /* persistent reservation check*/
976         mpath_pr_event_handle(pp);
977
978         if (!need_do_map)
979                 return 0;
980
981         if (!dm_map_present(mpp->alias)) {
982                 mpp->action = ACT_CREATE;
983                 start_waiter = 1;
984         }
985         /*
986          * push the map to the device-mapper
987          */
988         if (setup_map(mpp, params, PARAMS_SIZE, vecs)) {
989                 condlog(0, "%s: failed to setup map for addition of new "
990                         "path %s", mpp->alias, pp->dev);
991                 goto fail_map;
992         }
993         /*
994          * reload the map for the multipath mapped device
995          */
996 retry:
997         ret = domap(mpp, params, 1);
998         if (ret <= 0) {
999                 if (ret < 0 && retries-- > 0) {
1000                         condlog(0, "%s: retry domap for addition of new "
1001                                 "path %s", mpp->alias, pp->dev);
1002                         sleep(1);
1003                         goto retry;
1004                 }
1005                 condlog(0, "%s: failed in domap for addition of new "
1006                         "path %s", mpp->alias, pp->dev);
1007                 /*
1008                  * deal with asynchronous uevents :((
1009                  */
1010                 if (mpp->action == ACT_RELOAD && retries-- > 0) {
1011                         condlog(0, "%s: ev_add_path sleep", mpp->alias);
1012                         sleep(1);
1013                         update_mpp_paths(mpp, vecs->pathvec);
1014                         goto rescan;
1015                 }
1016                 else if (mpp->action == ACT_RELOAD)
1017                         condlog(0, "%s: giving up reload", mpp->alias);
1018                 else
1019                         goto fail_map;
1020         }
1021         dm_lib_release();
1022
1023         if ((mpp->action == ACT_CREATE ||
1024              (mpp->action == ACT_NOTHING && start_waiter && !mpp->waiter)) &&
1025             wait_for_events(mpp, vecs))
1026                         goto fail_map;
1027
1028         /*
1029          * update our state from kernel regardless of create or reload
1030          */
1031         if (setup_multipath(vecs, mpp))
1032                 goto fail; /* if setup_multipath fails, it removes the map */
1033
1034         sync_map_state(mpp);
1035
1036         if (retries >= 0) {
1037                 condlog(2, "%s [%s]: path added to devmap %s",
1038                         pp->dev, pp->dev_t, mpp->alias);
1039                 return 0;
1040         } else
1041                 goto fail;
1042
1043 fail_map:
1044         remove_map(mpp, vecs, 1);
1045 fail:
1046         orphan_path(pp, "failed to add path");
1047         return 1;
1048 }
1049
1050 static int
1051 uev_remove_path (struct uevent *uev, struct vectors * vecs, int need_do_map)
1052 {
1053         struct path *pp;
1054         int ret;
1055
1056         condlog(3, "%s: remove path (uevent)", uev->kernel);
1057         delete_foreign(uev->udev);
1058
1059         pthread_cleanup_push(cleanup_lock, &vecs->lock);
1060         lock(&vecs->lock);
1061         pthread_testcancel();
1062         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
1063         if (pp)
1064                 ret = ev_remove_path(pp, vecs, need_do_map);
1065         lock_cleanup_pop(vecs->lock);
1066         if (!pp) {
1067                 /* Not an error; path might have been purged earlier */
1068                 condlog(0, "%s: path already removed", uev->kernel);
1069                 return 0;
1070         }
1071         return ret;
1072 }
1073
1074 int
1075 ev_remove_path (struct path *pp, struct vectors * vecs, int need_do_map)
1076 {
1077         struct multipath * mpp;
1078         int i, retval = 0;
1079         char params[PARAMS_SIZE] = {0};
1080
1081         /*
1082          * avoid referring to the map of an orphaned path
1083          */
1084         if ((mpp = pp->mpp)) {
1085                 /*
1086                  * transform the mp->pg vector of vectors of paths
1087                  * into a mp->params string to feed the device-mapper
1088                  */
1089                 if (update_mpp_paths(mpp, vecs->pathvec)) {
1090                         condlog(0, "%s: failed to update paths",
1091                                 mpp->alias);
1092                         goto fail;
1093                 }
1094
1095                 /*
1096                  * Make sure mpp->hwe doesn't point to freed memory
1097                  * We call extract_hwe_from_path() below to restore mpp->hwe
1098                  */
1099                 if (mpp->hwe == pp->hwe)
1100                         mpp->hwe = NULL;
1101
1102                 if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
1103                         vector_del_slot(mpp->paths, i);
1104
1105                 /*
1106                  * remove the map IF removing the last path
1107                  */
1108                 if (VECTOR_SIZE(mpp->paths) == 0) {
1109                         char alias[WWID_SIZE];
1110
1111                         /*
1112                          * flush_map will fail if the device is open
1113                          */
1114                         strlcpy(alias, mpp->alias, WWID_SIZE);
1115                         if (mpp->flush_on_last_del == FLUSH_ENABLED) {
1116                                 condlog(2, "%s Last path deleted, disabling queueing", mpp->alias);
1117                                 mpp->retry_tick = 0;
1118                                 mpp->no_path_retry = NO_PATH_RETRY_FAIL;
1119                                 mpp->disable_queueing = 1;
1120                                 mpp->stat_map_failures++;
1121                                 dm_queue_if_no_path(mpp->alias, 0);
1122                         }
1123                         if (!flush_map(mpp, vecs, 1)) {
1124                                 condlog(2, "%s: removed map after"
1125                                         " removing all paths",
1126                                         alias);
1127                                 retval = 0;
1128                                 goto out;
1129                         }
1130                         /*
1131                          * Not an error, continue
1132                          */
1133                 }
1134
1135                 if (mpp->hwe == NULL)
1136                         extract_hwe_from_path(mpp);
1137
1138                 if (setup_map(mpp, params, PARAMS_SIZE, vecs)) {
1139                         condlog(0, "%s: failed to setup map for"
1140                                 " removal of path %s", mpp->alias, pp->dev);
1141                         goto fail;
1142                 }
1143
1144                 if (mpp->wait_for_udev) {
1145                         mpp->wait_for_udev = 2;
1146                         goto out;
1147                 }
1148
1149                 if (!need_do_map)
1150                         goto out;
1151                 /*
1152                  * reload the map
1153                  */
1154                 mpp->action = ACT_RELOAD;
1155                 if (domap(mpp, params, 1) <= 0) {
1156                         condlog(0, "%s: failed in domap for "
1157                                 "removal of path %s",
1158                                 mpp->alias, pp->dev);
1159                         retval = 1;
1160                 } else {
1161                         /*
1162                          * update our state from kernel
1163                          */
1164                         if (setup_multipath(vecs, mpp))
1165                                 return 1;
1166                         sync_map_state(mpp);
1167
1168                         condlog(2, "%s [%s]: path removed from map %s",
1169                                 pp->dev, pp->dev_t, mpp->alias);
1170                 }
1171         }
1172
1173 out:
1174         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
1175                 vector_del_slot(vecs->pathvec, i);
1176
1177         free_path(pp);
1178
1179         return retval;
1180
1181 fail:
1182         remove_map_and_stop_waiter(mpp, vecs);
1183         return 1;
1184 }
1185
1186 static int
1187 uev_update_path (struct uevent *uev, struct vectors * vecs)
1188 {
1189         int ro, retval = 0, rc;
1190         struct path * pp;
1191         struct config *conf;
1192         int disable_changed_wwids;
1193         int needs_reinit = 0;
1194
1195         switch ((rc = change_foreign(uev->udev))) {
1196         case FOREIGN_OK:
1197                 /* known foreign path, ignore event */
1198                 return 0;
1199         case FOREIGN_IGNORED:
1200                 break;
1201         case FOREIGN_ERR:
1202                 condlog(3, "%s: error in change_foreign", __func__);
1203                 break;
1204         default:
1205                 condlog(1, "%s: return code %d of change_forein is unsupported",
1206                         __func__, rc);
1207                 break;
1208         }
1209
1210         conf = get_multipath_config();
1211         disable_changed_wwids = conf->disable_changed_wwids;
1212         put_multipath_config(conf);
1213
1214         ro = uevent_get_disk_ro(uev);
1215
1216         pthread_cleanup_push(cleanup_lock, &vecs->lock);
1217         lock(&vecs->lock);
1218         pthread_testcancel();
1219
1220         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
1221         if (pp) {
1222                 struct multipath *mpp = pp->mpp;
1223                 char wwid[WWID_SIZE];
1224
1225                 if (pp->initialized == INIT_REQUESTED_UDEV) {
1226                         needs_reinit = 1;
1227                         goto out;
1228                 }
1229                 /* Don't deal with other types of failed initialization
1230                  * now. check_path will handle it */
1231                 if (!strlen(pp->wwid))
1232                         goto out;
1233
1234                 strcpy(wwid, pp->wwid);
1235                 get_uid(pp, pp->state, uev->udev);
1236
1237                 if (strncmp(wwid, pp->wwid, WWID_SIZE) != 0) {
1238                         condlog(0, "%s: path wwid changed from '%s' to '%s'. %s",
1239                                 uev->kernel, wwid, pp->wwid,
1240                                 (disable_changed_wwids ? "disallowing" :
1241                                  "continuing"));
1242                         strcpy(pp->wwid, wwid);
1243                         if (disable_changed_wwids) {
1244                                 if (!pp->wwid_changed) {
1245                                         pp->wwid_changed = 1;
1246                                         pp->tick = 1;
1247                                         if (pp->mpp)
1248                                                 dm_fail_path(pp->mpp->alias, pp->dev_t);
1249                                 }
1250                                 goto out;
1251                         }
1252                 } else {
1253                         pp->wwid_changed = 0;
1254                         udev_device_unref(pp->udev);
1255                         pp->udev = udev_device_ref(uev->udev);
1256                         conf = get_multipath_config();
1257                         pthread_cleanup_push(put_multipath_config, conf);
1258                         if (pathinfo(pp, conf, DI_SYSFS|DI_NOIO) != PATHINFO_OK)
1259                                 condlog(1, "%s: pathinfo failed after change uevent",
1260                                         uev->kernel);
1261                         pthread_cleanup_pop(1);
1262                 }
1263
1264                 if (mpp && ro >= 0) {
1265                         condlog(2, "%s: update path write_protect to '%d' (uevent)", uev->kernel, ro);
1266
1267                         if (mpp->wait_for_udev)
1268                                 mpp->wait_for_udev = 2;
1269                         else {
1270                                 if (ro == 1)
1271                                         pp->mpp->force_readonly = 1;
1272                                 retval = reload_map(vecs, mpp, 0, 1);
1273                                 pp->mpp->force_readonly = 0;
1274                                 condlog(2, "%s: map %s reloaded (retval %d)",
1275                                         uev->kernel, mpp->alias, retval);
1276                         }
1277                 }
1278         }
1279 out:
1280         lock_cleanup_pop(vecs->lock);
1281         if (!pp) {
1282                 /* If the path is blacklisted, print a debug/non-default verbosity message. */
1283                 if (uev->udev) {
1284                         int flag = DI_SYSFS | DI_WWID;
1285
1286                         conf = get_multipath_config();
1287                         pthread_cleanup_push(put_multipath_config, conf);
1288                         retval = alloc_path_with_pathinfo(conf, uev->udev, uev->wwid, flag, NULL);
1289                         pthread_cleanup_pop(1);
1290
1291                         if (retval == PATHINFO_SKIPPED) {
1292                                 condlog(3, "%s: spurious uevent, path is blacklisted", uev->kernel);
1293                                 return 0;
1294                         }
1295                 }
1296
1297                 condlog(0, "%s: spurious uevent, path not found", uev->kernel);
1298         }
1299         if (needs_reinit)
1300                 retval = uev_add_path(uev, vecs, 1);
1301         return retval;
1302 }
1303
1304 static int
1305 uev_pathfail_check(struct uevent *uev, struct vectors *vecs)
1306 {
1307         char *action = NULL, *devt = NULL;
1308         struct path *pp;
1309         int r = 1;
1310
1311         action = uevent_get_dm_action(uev);
1312         if (!action)
1313                 return 1;
1314         if (strncmp(action, "PATH_FAILED", 11))
1315                 goto out;
1316         devt = uevent_get_dm_path(uev);
1317         if (!devt) {
1318                 condlog(3, "%s: No DM_PATH in uevent", uev->kernel);
1319                 goto out;
1320         }
1321
1322         pthread_cleanup_push(cleanup_lock, &vecs->lock);
1323         lock(&vecs->lock);
1324         pthread_testcancel();
1325         pp = find_path_by_devt(vecs->pathvec, devt);
1326         if (!pp)
1327                 goto out_lock;
1328         r = io_err_stat_handle_pathfail(pp);
1329         if (r)
1330                 condlog(3, "io_err_stat: %s: cannot handle pathfail uevent",
1331                                 pp->dev);
1332 out_lock:
1333         lock_cleanup_pop(vecs->lock);
1334         FREE(devt);
1335         FREE(action);
1336         return r;
1337 out:
1338         FREE(action);
1339         return 1;
1340 }
1341
1342 static int
1343 map_discovery (struct vectors * vecs)
1344 {
1345         struct multipath * mpp;
1346         unsigned int i;
1347
1348         if (dm_get_maps(vecs->mpvec))
1349                 return 1;
1350
1351         vector_foreach_slot (vecs->mpvec, mpp, i)
1352                 if (update_multipath_table(mpp, vecs->pathvec, 1) ||
1353                     update_multipath_status(mpp)) {
1354                         remove_map(mpp, vecs, 1);
1355                         i--;
1356                 }
1357
1358         return 0;
1359 }
1360
1361 int
1362 uxsock_trigger (char * str, char ** reply, int * len, bool is_root,
1363                 void * trigger_data)
1364 {
1365         struct vectors * vecs;
1366         int r;
1367
1368         *reply = NULL;
1369         *len = 0;
1370         vecs = (struct vectors *)trigger_data;
1371
1372         if ((str != NULL) && (is_root == false) &&
1373             (strncmp(str, "list", strlen("list")) != 0) &&
1374             (strncmp(str, "show", strlen("show")) != 0)) {
1375                 *reply = STRDUP("permission deny: need to be root");
1376                 if (*reply)
1377                         *len = strlen(*reply) + 1;
1378                 return 1;
1379         }
1380
1381         r = parse_cmd(str, reply, len, vecs, uxsock_timeout / 1000);
1382
1383         if (r > 0) {
1384                 if (r == ETIMEDOUT)
1385                         *reply = STRDUP("timeout\n");
1386                 else
1387                         *reply = STRDUP("fail\n");
1388                 if (*reply)
1389                         *len = strlen(*reply) + 1;
1390                 r = 1;
1391         }
1392         else if (!r && *len == 0) {
1393                 *reply = STRDUP("ok\n");
1394                 if (*reply)
1395                         *len = strlen(*reply) + 1;
1396                 r = 0;
1397         }
1398         /* else if (r < 0) leave *reply alone */
1399
1400         return r;
1401 }
1402
1403 int
1404 uev_trigger (struct uevent * uev, void * trigger_data)
1405 {
1406         int r = 0;
1407         struct vectors * vecs;
1408         struct uevent *merge_uev, *tmp;
1409
1410         vecs = (struct vectors *)trigger_data;
1411
1412         pthread_cleanup_push(config_cleanup, NULL);
1413         pthread_mutex_lock(&config_lock);
1414         if (running_state != DAEMON_IDLE &&
1415             running_state != DAEMON_RUNNING)
1416                 pthread_cond_wait(&config_cond, &config_lock);
1417         pthread_cleanup_pop(1);
1418
1419         if (running_state == DAEMON_SHUTDOWN)
1420                 return 0;
1421
1422         /*
1423          * device map event
1424          * Add events are ignored here as the tables
1425          * are not fully initialised then.
1426          */
1427         if (!strncmp(uev->kernel, "dm-", 3)) {
1428                 if (!uevent_is_mpath(uev)) {
1429                         if (!strncmp(uev->action, "change", 6))
1430                                 (void)add_foreign(uev->udev);
1431                         else if (!strncmp(uev->action, "remove", 6))
1432                                 (void)delete_foreign(uev->udev);
1433                         goto out;
1434                 }
1435                 if (!strncmp(uev->action, "change", 6)) {
1436                         r = uev_add_map(uev, vecs);
1437
1438                         /*
1439                          * the kernel-side dm-mpath issues a PATH_FAILED event
1440                          * when it encounters a path IO error. It is reason-
1441                          * able be the entry of path IO error accounting pro-
1442                          * cess.
1443                          */
1444                         uev_pathfail_check(uev, vecs);
1445                 } else if (!strncmp(uev->action, "remove", 6)) {
1446                         r = uev_remove_map(uev, vecs);
1447                 }
1448                 goto out;
1449         }
1450
1451         /*
1452          * path add/remove/change event, add/remove maybe merged
1453          */
1454         list_for_each_entry_safe(merge_uev, tmp, &uev->merge_node, node) {
1455                 if (!strncmp(merge_uev->action, "add", 3))
1456                         r += uev_add_path(merge_uev, vecs, 0);
1457                 if (!strncmp(merge_uev->action, "remove", 6))
1458                         r += uev_remove_path(merge_uev, vecs, 0);
1459         }
1460
1461         if (!strncmp(uev->action, "add", 3))
1462                 r += uev_add_path(uev, vecs, 1);
1463         if (!strncmp(uev->action, "remove", 6))
1464                 r += uev_remove_path(uev, vecs, 1);
1465         if (!strncmp(uev->action, "change", 6))
1466                 r += uev_update_path(uev, vecs);
1467
1468 out:
1469         return r;
1470 }
1471
1472 static void rcu_unregister(void *param)
1473 {
1474         rcu_unregister_thread();
1475 }
1476
1477 static void *
1478 ueventloop (void * ap)
1479 {
1480         struct udev *udev = ap;
1481
1482         pthread_cleanup_push(rcu_unregister, NULL);
1483         rcu_register_thread();
1484         if (uevent_listen(udev))
1485                 condlog(0, "error starting uevent listener");
1486         pthread_cleanup_pop(1);
1487         return NULL;
1488 }
1489
1490 static void *
1491 uevqloop (void * ap)
1492 {
1493         pthread_cleanup_push(rcu_unregister, NULL);
1494         rcu_register_thread();
1495         if (uevent_dispatch(&uev_trigger, ap))
1496                 condlog(0, "error starting uevent dispatcher");
1497         pthread_cleanup_pop(1);
1498         return NULL;
1499 }
1500 static void *
1501 uxlsnrloop (void * ap)
1502 {
1503         long ux_sock;
1504
1505         pthread_cleanup_push(rcu_unregister, NULL);
1506         rcu_register_thread();
1507
1508         ux_sock = ux_socket_listen(DEFAULT_SOCKET);
1509         if (ux_sock == -1) {
1510                 condlog(1, "could not create uxsock: %d", errno);
1511                 exit_daemon();
1512                 goto out;
1513         }
1514         pthread_cleanup_push(uxsock_cleanup, (void *)ux_sock);
1515
1516         if (cli_init()) {
1517                 condlog(1, "Failed to init uxsock listener");
1518                 exit_daemon();
1519                 goto out_sock;
1520         }
1521
1522         /* Tell main thread that thread has started */
1523         post_config_state(DAEMON_CONFIGURE);
1524
1525         set_handler_callback(LIST+PATHS, cli_list_paths);
1526         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
1527         set_handler_callback(LIST+PATHS+RAW+FMT, cli_list_paths_raw);
1528         set_handler_callback(LIST+PATH, cli_list_path);
1529         set_handler_callback(LIST+MAPS, cli_list_maps);
1530         set_handler_callback(LIST+STATUS, cli_list_status);
1531         set_unlocked_handler_callback(LIST+DAEMON, cli_list_daemon);
1532         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
1533         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
1534         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
1535         set_handler_callback(LIST+MAPS+RAW+FMT, cli_list_maps_raw);
1536         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
1537         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
1538         set_handler_callback(LIST+MAPS+JSON, cli_list_maps_json);
1539         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
1540         set_handler_callback(LIST+MAP+FMT, cli_list_map_fmt);
1541         set_handler_callback(LIST+MAP+RAW+FMT, cli_list_map_fmt);
1542         set_handler_callback(LIST+MAP+JSON, cli_list_map_json);
1543         set_handler_callback(LIST+CONFIG+LOCAL, cli_list_config_local);
1544         set_handler_callback(LIST+CONFIG, cli_list_config);
1545         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
1546         set_handler_callback(LIST+DEVICES, cli_list_devices);
1547         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
1548         set_handler_callback(RESET+MAPS+STATS, cli_reset_maps_stats);
1549         set_handler_callback(RESET+MAP+STATS, cli_reset_map_stats);
1550         set_handler_callback(ADD+PATH, cli_add_path);
1551         set_handler_callback(DEL+PATH, cli_del_path);
1552         set_handler_callback(ADD+MAP, cli_add_map);
1553         set_handler_callback(DEL+MAP, cli_del_map);
1554         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
1555         set_unlocked_handler_callback(RECONFIGURE, cli_reconfigure);
1556         set_handler_callback(SUSPEND+MAP, cli_suspend);
1557         set_handler_callback(RESUME+MAP, cli_resume);
1558         set_handler_callback(RESIZE+MAP, cli_resize);
1559         set_handler_callback(RELOAD+MAP, cli_reload);
1560         set_handler_callback(RESET+MAP, cli_reassign);
1561         set_handler_callback(REINSTATE+PATH, cli_reinstate);
1562         set_handler_callback(FAIL+PATH, cli_fail);
1563         set_handler_callback(DISABLEQ+MAP, cli_disable_queueing);
1564         set_handler_callback(RESTOREQ+MAP, cli_restore_queueing);
1565         set_handler_callback(DISABLEQ+MAPS, cli_disable_all_queueing);
1566         set_handler_callback(RESTOREQ+MAPS, cli_restore_all_queueing);
1567         set_unlocked_handler_callback(QUIT, cli_quit);
1568         set_unlocked_handler_callback(SHUTDOWN, cli_shutdown);
1569         set_handler_callback(GETPRSTATUS+MAP, cli_getprstatus);
1570         set_handler_callback(SETPRSTATUS+MAP, cli_setprstatus);
1571         set_handler_callback(UNSETPRSTATUS+MAP, cli_unsetprstatus);
1572         set_handler_callback(FORCEQ+DAEMON, cli_force_no_daemon_q);
1573         set_handler_callback(RESTOREQ+DAEMON, cli_restore_no_daemon_q);
1574         set_handler_callback(GETPRKEY+MAP, cli_getprkey);
1575         set_handler_callback(SETPRKEY+MAP+KEY, cli_setprkey);
1576         set_handler_callback(UNSETPRKEY+MAP, cli_unsetprkey);
1577
1578         umask(077);
1579         uxsock_listen(&uxsock_trigger, ux_sock, ap);
1580
1581 out_sock:
1582         pthread_cleanup_pop(1); /* uxsock_cleanup */
1583 out:
1584         pthread_cleanup_pop(1); /* rcu_unregister */
1585         return NULL;
1586 }
1587
1588 void
1589 exit_daemon (void)
1590 {
1591         post_config_state(DAEMON_SHUTDOWN);
1592 }
1593
1594 static void
1595 fail_path (struct path * pp, int del_active)
1596 {
1597         if (!pp->mpp)
1598                 return;
1599
1600         condlog(2, "checker failed path %s in map %s",
1601                  pp->dev_t, pp->mpp->alias);
1602
1603         dm_fail_path(pp->mpp->alias, pp->dev_t);
1604         if (del_active)
1605                 update_queue_mode_del_path(pp->mpp);
1606 }
1607
1608 /*
1609  * caller must have locked the path list before calling that function
1610  */
1611 static int
1612 reinstate_path (struct path * pp, int add_active)
1613 {
1614         int ret = 0;
1615
1616         if (!pp->mpp)
1617                 return 0;
1618
1619         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t)) {
1620                 condlog(0, "%s: reinstate failed", pp->dev_t);
1621                 ret = 1;
1622         } else {
1623                 condlog(2, "%s: reinstated", pp->dev_t);
1624                 if (add_active)
1625                         update_queue_mode_add_path(pp->mpp);
1626         }
1627         return ret;
1628 }
1629
1630 static void
1631 enable_group(struct path * pp)
1632 {
1633         struct pathgroup * pgp;
1634
1635         /*
1636          * if path is added through uev_add_path, pgindex can be unset.
1637          * next update_strings() will set it, upon map reload event.
1638          *
1639          * we can safely return here, because upon map reload, all
1640          * PG will be enabled.
1641          */
1642         if (!pp->mpp->pg || !pp->pgindex)
1643                 return;
1644
1645         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1646
1647         if (pgp->status == PGSTATE_DISABLED) {
1648                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
1649                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
1650         }
1651 }
1652
1653 static void
1654 mpvec_garbage_collector (struct vectors * vecs)
1655 {
1656         struct multipath * mpp;
1657         unsigned int i;
1658
1659         if (!vecs->mpvec)
1660                 return;
1661
1662         vector_foreach_slot (vecs->mpvec, mpp, i) {
1663                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
1664                         condlog(2, "%s: remove dead map", mpp->alias);
1665                         remove_map_and_stop_waiter(mpp, vecs);
1666                         i--;
1667                 }
1668         }
1669 }
1670
1671 /* This is called after a path has started working again. It the multipath
1672  * device for this path uses the followover failback type, and this is the
1673  * best pathgroup, and this is the first path in the pathgroup to come back
1674  * up, then switch to this pathgroup */
1675 static int
1676 followover_should_failback(struct path * pp)
1677 {
1678         struct pathgroup * pgp;
1679         struct path *pp1;
1680         int i;
1681
1682         if (pp->mpp->pgfailback != -FAILBACK_FOLLOWOVER ||
1683             !pp->mpp->pg || !pp->pgindex ||
1684             pp->pgindex != pp->mpp->bestpg)
1685                 return 0;
1686
1687         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1688         vector_foreach_slot(pgp->paths, pp1, i) {
1689                 if (pp1 == pp)
1690                         continue;
1691                 if (pp1->chkrstate != PATH_DOWN && pp1->chkrstate != PATH_SHAKY)
1692                         return 0;
1693         }
1694         return 1;
1695 }
1696
1697 static void
1698 missing_uev_wait_tick(struct vectors *vecs)
1699 {
1700         struct multipath * mpp;
1701         unsigned int i;
1702         int timed_out = 0, delayed_reconfig;
1703         struct config *conf;
1704
1705         vector_foreach_slot (vecs->mpvec, mpp, i) {
1706                 if (mpp->wait_for_udev && --mpp->uev_wait_tick <= 0) {
1707                         timed_out = 1;
1708                         condlog(0, "%s: timeout waiting on creation uevent. enabling reloads", mpp->alias);
1709                         if (mpp->wait_for_udev > 1 &&
1710                             update_map(mpp, vecs, 0)) {
1711                                 /* update_map removed map */
1712                                 i--;
1713                                 continue;
1714                         }
1715                         mpp->wait_for_udev = 0;
1716                 }
1717         }
1718
1719         conf = get_multipath_config();
1720         delayed_reconfig = conf->delayed_reconfig;
1721         put_multipath_config(conf);
1722         if (timed_out && delayed_reconfig &&
1723             !need_to_delay_reconfig(vecs)) {
1724                 condlog(2, "reconfigure (delayed)");
1725                 set_config_state(DAEMON_CONFIGURE);
1726         }
1727 }
1728
1729 static void
1730 ghost_delay_tick(struct vectors *vecs)
1731 {
1732         struct multipath * mpp;
1733         unsigned int i;
1734
1735         vector_foreach_slot (vecs->mpvec, mpp, i) {
1736                 if (mpp->ghost_delay_tick <= 0)
1737                         continue;
1738                 if (--mpp->ghost_delay_tick <= 0) {
1739                         condlog(0, "%s: timed out waiting for active path",
1740                                 mpp->alias);
1741                         mpp->force_udev_reload = 1;
1742                         if (update_map(mpp, vecs, 0) != 0) {
1743                                 /* update_map removed map */
1744                                 i--;
1745                                 continue;
1746                         }
1747                 }
1748         }
1749 }
1750
1751 static void
1752 defered_failback_tick (vector mpvec)
1753 {
1754         struct multipath * mpp;
1755         unsigned int i;
1756
1757         vector_foreach_slot (mpvec, mpp, i) {
1758                 /*
1759                  * deferred failback getting sooner
1760                  */
1761                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1762                         mpp->failback_tick--;
1763
1764                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1765                                 switch_pathgroup(mpp);
1766                 }
1767         }
1768 }
1769
1770 static void
1771 retry_count_tick(vector mpvec)
1772 {
1773         struct multipath *mpp;
1774         unsigned int i;
1775
1776         vector_foreach_slot (mpvec, mpp, i) {
1777                 if (mpp->retry_tick > 0) {
1778                         mpp->stat_total_queueing_time++;
1779                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1780                         if(--mpp->retry_tick == 0) {
1781                                 mpp->stat_map_failures++;
1782                                 dm_queue_if_no_path(mpp->alias, 0);
1783                                 condlog(2, "%s: Disable queueing", mpp->alias);
1784                         }
1785                 }
1786         }
1787 }
1788
1789 int update_prio(struct path *pp, int refresh_all)
1790 {
1791         int oldpriority;
1792         struct path *pp1;
1793         struct pathgroup * pgp;
1794         int i, j, changed = 0;
1795         struct config *conf;
1796
1797         if (refresh_all) {
1798                 vector_foreach_slot (pp->mpp->pg, pgp, i) {
1799                         vector_foreach_slot (pgp->paths, pp1, j) {
1800                                 oldpriority = pp1->priority;
1801                                 conf = get_multipath_config();
1802                                 pthread_cleanup_push(put_multipath_config,
1803                                                      conf);
1804                                 pathinfo(pp1, conf, DI_PRIO);
1805                                 pthread_cleanup_pop(1);
1806                                 if (pp1->priority != oldpriority)
1807                                         changed = 1;
1808                         }
1809                 }
1810                 return changed;
1811         }
1812         oldpriority = pp->priority;
1813         conf = get_multipath_config();
1814         pthread_cleanup_push(put_multipath_config, conf);
1815         if (pp->state != PATH_DOWN)
1816                 pathinfo(pp, conf, DI_PRIO);
1817         pthread_cleanup_pop(1);
1818
1819         if (pp->priority == oldpriority)
1820                 return 0;
1821         return 1;
1822 }
1823
1824 int update_path_groups(struct multipath *mpp, struct vectors *vecs, int refresh)
1825 {
1826         if (reload_map(vecs, mpp, refresh, 1))
1827                 return 1;
1828
1829         dm_lib_release();
1830         if (setup_multipath(vecs, mpp) != 0)
1831                 return 1;
1832         sync_map_state(mpp);
1833
1834         return 0;
1835 }
1836
1837 /*
1838  * Returns '1' if the path has been checked, '-1' if it was blacklisted
1839  * and '0' otherwise
1840  */
1841 int
1842 check_path (struct vectors * vecs, struct path * pp, int ticks)
1843 {
1844         int newstate;
1845         int new_path_up = 0;
1846         int chkr_new_path_up = 0;
1847         int add_active;
1848         int disable_reinstate = 0;
1849         int oldchkrstate = pp->chkrstate;
1850         int retrigger_tries, checkint, max_checkint, verbosity;
1851         struct config *conf;
1852         int ret;
1853
1854         if ((pp->initialized == INIT_OK ||
1855              pp->initialized == INIT_REQUESTED_UDEV) && !pp->mpp)
1856                 return 0;
1857
1858         if (pp->tick)
1859                 pp->tick -= (pp->tick > ticks) ? ticks : pp->tick;
1860         if (pp->tick)
1861                 return 0; /* don't check this path yet */
1862
1863         conf = get_multipath_config();
1864         retrigger_tries = conf->retrigger_tries;
1865         checkint = conf->checkint;
1866         max_checkint = conf->max_checkint;
1867         verbosity = conf->verbosity;
1868         put_multipath_config(conf);
1869
1870         if (pp->checkint == CHECKINT_UNDEF) {
1871                 condlog(0, "%s: BUG: checkint is not set", pp->dev);
1872                 pp->checkint = checkint;
1873         };
1874
1875         if (!pp->mpp && pp->initialized == INIT_MISSING_UDEV) {
1876                 if (pp->retriggers < retrigger_tries) {
1877                         condlog(2, "%s: triggering change event to reinitialize",
1878                                 pp->dev);
1879                         pp->initialized = INIT_REQUESTED_UDEV;
1880                         pp->retriggers++;
1881                         sysfs_attr_set_value(pp->udev, "uevent", "change",
1882                                              strlen("change"));
1883                         return 0;
1884                 } else {
1885                         condlog(1, "%s: not initialized after %d udev retriggers",
1886                                 pp->dev, retrigger_tries);
1887                         /*
1888                          * Make sure that the "add missing path" code path
1889                          * below may reinstate the path later, if it ever
1890                          * comes up again.
1891                          * The WWID needs not be cleared; if it was set, the
1892                          * state hadn't been INIT_MISSING_UDEV in the first
1893                          * place.
1894                          */
1895                         pp->initialized = INIT_FAILED;
1896                         return 0;
1897                 }
1898         }
1899
1900         /*
1901          * provision a next check soonest,
1902          * in case we exit abnormaly from here
1903          */
1904         pp->tick = checkint;
1905
1906         newstate = path_offline(pp);
1907         if (newstate == PATH_UP) {
1908                 conf = get_multipath_config();
1909                 pthread_cleanup_push(put_multipath_config, conf);
1910                 newstate = get_state(pp, conf, 1, newstate);
1911                 pthread_cleanup_pop(1);
1912         } else {
1913                 checker_clear_message(&pp->checker);
1914                 condlog(3, "%s: state %s, checker not called",
1915                         pp->dev, checker_state_name(newstate));
1916         }
1917         /*
1918          * Wait for uevent for removed paths;
1919          * some LLDDs like zfcp keep paths unavailable
1920          * without sending uevents.
1921          */
1922         if (newstate == PATH_REMOVED)
1923                 newstate = PATH_DOWN;
1924
1925         if (pp->wwid_changed) {
1926                 condlog(2, "%s: path wwid has changed. Refusing to use",
1927                         pp->dev);
1928                 newstate = PATH_DOWN;
1929         }
1930
1931         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1932                 condlog(2, "%s: unusable path - checker failed", pp->dev);
1933                 LOG_MSG(2, verbosity, pp);
1934                 conf = get_multipath_config();
1935                 pthread_cleanup_push(put_multipath_config, conf);
1936                 pathinfo(pp, conf, 0);
1937                 pthread_cleanup_pop(1);
1938                 return 1;
1939         }
1940         if (!pp->mpp) {
1941                 if (!strlen(pp->wwid) && pp->initialized == INIT_FAILED &&
1942                     (newstate == PATH_UP || newstate == PATH_GHOST)) {
1943                         condlog(2, "%s: add missing path", pp->dev);
1944                         conf = get_multipath_config();
1945                         pthread_cleanup_push(put_multipath_config, conf);
1946                         ret = pathinfo(pp, conf, DI_ALL | DI_BLACKLIST);
1947                         pthread_cleanup_pop(1);
1948                         /* INIT_OK implies ret == PATHINFO_OK */
1949                         if (pp->initialized == INIT_OK) {
1950                                 ev_add_path(pp, vecs, 1);
1951                                 pp->tick = 1;
1952                         } else {
1953                                 /*
1954                                  * We failed multiple times to initialize this
1955                                  * path properly. Don't re-check too often.
1956                                  */
1957                                 pp->checkint = max_checkint;
1958                                 if (ret == PATHINFO_SKIPPED)
1959                                         return -1;
1960                         }
1961                 }
1962                 return 0;
1963         }
1964         /*
1965          * Async IO in flight. Keep the previous path state
1966          * and reschedule as soon as possible
1967          */
1968         if (newstate == PATH_PENDING) {
1969                 pp->tick = 1;
1970                 return 0;
1971         }
1972         /*
1973          * Synchronize with kernel state
1974          */
1975         if (update_multipath_strings(pp->mpp, vecs->pathvec, 1)) {
1976                 condlog(1, "%s: Could not synchronize with kernel state",
1977                         pp->dev);
1978                 pp->dmstate = PSTATE_UNDEF;
1979         }
1980         /* if update_multipath_strings orphaned the path, quit early */
1981         if (!pp->mpp)
1982                 return 0;
1983
1984         if (pp->io_err_disable_reinstate && hit_io_err_recheck_time(pp)) {
1985                 pp->state = PATH_SHAKY;
1986                 /*
1987                  * to reschedule as soon as possible,so that this path can
1988                  * be recoverd in time
1989                  */
1990                 pp->tick = 1;
1991                 return 1;
1992         }
1993
1994         if ((newstate == PATH_UP || newstate == PATH_GHOST) &&
1995              pp->wait_checks > 0) {
1996                 if (pp->mpp->nr_active > 0) {
1997                         pp->state = PATH_DELAYED;
1998                         pp->wait_checks--;
1999                         return 1;
2000                 } else
2001                         pp->wait_checks = 0;
2002         }
2003
2004         /*
2005          * don't reinstate failed path, if its in stand-by
2006          * and if target supports only implicit tpgs mode.
2007          * this will prevent unnecessary i/o by dm on stand-by
2008          * paths if there are no other active paths in map.
2009          */
2010         disable_reinstate = (newstate == PATH_GHOST &&
2011                             pp->mpp->nr_active == 0 &&
2012                             pp->tpgs == TPGS_IMPLICIT) ? 1 : 0;
2013
2014         pp->chkrstate = newstate;
2015         if (newstate != pp->state) {
2016                 int oldstate = pp->state;
2017                 pp->state = newstate;
2018
2019                 LOG_MSG(1, verbosity, pp);
2020
2021                 /*
2022                  * upon state change, reset the checkint
2023                  * to the shortest delay
2024                  */
2025                 conf = get_multipath_config();
2026                 pp->checkint = conf->checkint;
2027                 put_multipath_config(conf);
2028
2029                 if (newstate != PATH_UP && newstate != PATH_GHOST) {
2030                         /*
2031                          * proactively fail path in the DM
2032                          */
2033                         if (oldstate == PATH_UP ||
2034                             oldstate == PATH_GHOST) {
2035                                 fail_path(pp, 1);
2036                                 if (pp->mpp->delay_wait_checks > 0 &&
2037                                     pp->watch_checks > 0) {
2038                                         pp->wait_checks = pp->mpp->delay_wait_checks;
2039                                         pp->watch_checks = 0;
2040                                 }
2041                         } else {
2042                                 fail_path(pp, 0);
2043                                 if (pp->wait_checks > 0)
2044                                         pp->wait_checks =
2045                                                 pp->mpp->delay_wait_checks;
2046                         }
2047
2048                         /*
2049                          * cancel scheduled failback
2050                          */
2051                         pp->mpp->failback_tick = 0;
2052
2053                         pp->mpp->stat_path_failures++;
2054                         return 1;
2055                 }
2056
2057                 if (newstate == PATH_UP || newstate == PATH_GHOST) {
2058                         if (pp->mpp->prflag) {
2059                                 /*
2060                                  * Check Persistent Reservation.
2061                                  */
2062                                 condlog(2, "%s: checking persistent "
2063                                         "reservation registration", pp->dev);
2064                                 mpath_pr_event_handle(pp);
2065                         }
2066                 }
2067
2068                 /*
2069                  * reinstate this path
2070                  */
2071                 if (oldstate != PATH_UP &&
2072                     oldstate != PATH_GHOST) {
2073                         if (pp->mpp->delay_watch_checks > 0)
2074                                 pp->watch_checks = pp->mpp->delay_watch_checks;
2075                         add_active = 1;
2076                 } else {
2077                         if (pp->watch_checks > 0)
2078                                 pp->watch_checks--;
2079                         add_active = 0;
2080                 }
2081                 if (!disable_reinstate && reinstate_path(pp, add_active)) {
2082                         condlog(3, "%s: reload map", pp->dev);
2083                         ev_add_path(pp, vecs, 1);
2084                         pp->tick = 1;
2085                         return 0;
2086                 }
2087                 new_path_up = 1;
2088
2089                 if (oldchkrstate != PATH_UP && oldchkrstate != PATH_GHOST)
2090                         chkr_new_path_up = 1;
2091
2092                 /*
2093                  * if at least one path is up in a group, and
2094                  * the group is disabled, re-enable it
2095                  */
2096                 if (newstate == PATH_UP)
2097                         enable_group(pp);
2098         }
2099         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
2100                 if ((pp->dmstate == PSTATE_FAILED ||
2101                     pp->dmstate == PSTATE_UNDEF) &&
2102                     !disable_reinstate) {
2103                         /* Clear IO errors */
2104                         if (reinstate_path(pp, 0)) {
2105                                 condlog(3, "%s: reload map", pp->dev);
2106                                 ev_add_path(pp, vecs, 1);
2107                                 pp->tick = 1;
2108                                 return 0;
2109                         }
2110                 } else {
2111                         LOG_MSG(4, verbosity, pp);
2112                         if (pp->checkint != max_checkint) {
2113                                 /*
2114                                  * double the next check delay.
2115                                  * max at conf->max_checkint
2116                                  */
2117                                 if (pp->checkint < (max_checkint / 2))
2118                                         pp->checkint = 2 * pp->checkint;
2119                                 else
2120                                         pp->checkint = max_checkint;
2121
2122                                 condlog(4, "%s: delay next check %is",
2123                                         pp->dev_t, pp->checkint);
2124                         }
2125                         if (pp->watch_checks > 0)
2126                                 pp->watch_checks--;
2127                         pp->tick = pp->checkint;
2128                 }
2129         }
2130         else if (newstate != PATH_UP && newstate != PATH_GHOST) {
2131                 if (pp->dmstate == PSTATE_ACTIVE ||
2132                     pp->dmstate == PSTATE_UNDEF)
2133                         fail_path(pp, 0);
2134                 if (newstate == PATH_DOWN) {
2135                         int log_checker_err;
2136
2137                         conf = get_multipath_config();
2138                         log_checker_err = conf->log_checker_err;
2139                         put_multipath_config(conf);
2140                         if (log_checker_err == LOG_CHKR_ERR_ONCE)
2141                                 LOG_MSG(3, verbosity, pp);
2142                         else
2143                                 LOG_MSG(2, verbosity, pp);
2144                 }
2145         }
2146
2147         pp->state = newstate;
2148
2149         if (pp->mpp->wait_for_udev)
2150                 return 1;
2151         /*
2152          * path prio refreshing
2153          */
2154         condlog(4, "path prio refresh");
2155
2156         if (update_prio(pp, new_path_up) &&
2157             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
2158              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
2159                 update_path_groups(pp->mpp, vecs, !new_path_up);
2160         else if (need_switch_pathgroup(pp->mpp, 0)) {
2161                 if (pp->mpp->pgfailback > 0 &&
2162                     (new_path_up || pp->mpp->failback_tick <= 0))
2163                         pp->mpp->failback_tick =
2164                                 pp->mpp->pgfailback + 1;
2165                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE ||
2166                          (chkr_new_path_up && followover_should_failback(pp)))
2167                         switch_pathgroup(pp->mpp);
2168         }
2169         return 1;
2170 }
2171
2172 static void *
2173 checkerloop (void *ap)
2174 {
2175         struct vectors *vecs;
2176         struct path *pp;
2177         int count = 0;
2178         unsigned int i;
2179         struct timespec last_time;
2180         struct config *conf;
2181
2182         pthread_cleanup_push(rcu_unregister, NULL);
2183         rcu_register_thread();
2184         mlockall(MCL_CURRENT | MCL_FUTURE);
2185         vecs = (struct vectors *)ap;
2186         condlog(2, "path checkers start up");
2187
2188         /* Tweak start time for initial path check */
2189         if (clock_gettime(CLOCK_MONOTONIC, &last_time) != 0)
2190                 last_time.tv_sec = 0;
2191         else
2192                 last_time.tv_sec -= 1;
2193
2194         while (1) {
2195                 struct timespec diff_time, start_time, end_time;
2196                 int num_paths = 0, ticks = 0, strict_timing, rc = 0;
2197
2198                 if (clock_gettime(CLOCK_MONOTONIC, &start_time) != 0)
2199                         start_time.tv_sec = 0;
2200                 if (start_time.tv_sec && last_time.tv_sec) {
2201                         timespecsub(&start_time, &last_time, &diff_time);
2202                         condlog(4, "tick (%lu.%06lu secs)",
2203                                 diff_time.tv_sec, diff_time.tv_nsec / 1000);
2204                         last_time = start_time;
2205                         ticks = diff_time.tv_sec;
2206                 } else {
2207                         ticks = 1;
2208                         condlog(4, "tick (%d ticks)", ticks);
2209                 }
2210 #ifdef USE_SYSTEMD
2211                 if (use_watchdog)
2212                         sd_notify(0, "WATCHDOG=1");
2213 #endif
2214                 rc = set_config_state(DAEMON_RUNNING);
2215                 if (rc == ETIMEDOUT) {
2216                         condlog(4, "timeout waiting for DAEMON_IDLE");
2217                         continue;
2218                 } else if (rc == EINVAL)
2219                         /* daemon shutdown */
2220                         break;
2221
2222                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
2223                 lock(&vecs->lock);
2224                 pthread_testcancel();
2225                 vector_foreach_slot (vecs->pathvec, pp, i) {
2226                         rc = check_path(vecs, pp, ticks);
2227                         if (rc < 0) {
2228                                 vector_del_slot(vecs->pathvec, i);
2229                                 free_path(pp);
2230                                 i--;
2231                         } else
2232                                 num_paths += rc;
2233                 }
2234                 lock_cleanup_pop(vecs->lock);
2235
2236                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
2237                 lock(&vecs->lock);
2238                 pthread_testcancel();
2239                 defered_failback_tick(vecs->mpvec);
2240                 retry_count_tick(vecs->mpvec);
2241                 missing_uev_wait_tick(vecs);
2242                 ghost_delay_tick(vecs);
2243                 lock_cleanup_pop(vecs->lock);
2244
2245                 if (count)
2246                         count--;
2247                 else {
2248                         pthread_cleanup_push(cleanup_lock, &vecs->lock);
2249                         lock(&vecs->lock);
2250                         pthread_testcancel();
2251                         condlog(4, "map garbage collection");
2252                         mpvec_garbage_collector(vecs);
2253                         count = MAPGCINT;
2254                         lock_cleanup_pop(vecs->lock);
2255                 }
2256
2257                 diff_time.tv_nsec = 0;
2258                 if (start_time.tv_sec &&
2259                     clock_gettime(CLOCK_MONOTONIC, &end_time) == 0) {
2260                         timespecsub(&end_time, &start_time, &diff_time);
2261                         if (num_paths) {
2262                                 unsigned int max_checkint;
2263
2264                                 condlog(4, "checked %d path%s in %lu.%06lu secs",
2265                                         num_paths, num_paths > 1 ? "s" : "",
2266                                         diff_time.tv_sec,
2267                                         diff_time.tv_nsec / 1000);
2268                                 conf = get_multipath_config();
2269                                 max_checkint = conf->max_checkint;
2270                                 put_multipath_config(conf);
2271                                 if (diff_time.tv_sec > max_checkint)
2272                                         condlog(1, "path checkers took longer "
2273                                                 "than %lu seconds, consider "
2274                                                 "increasing max_polling_interval",
2275                                                 diff_time.tv_sec);
2276                         }
2277                 }
2278                 check_foreign();
2279                 post_config_state(DAEMON_IDLE);
2280                 conf = get_multipath_config();
2281                 strict_timing = conf->strict_timing;
2282                 put_multipath_config(conf);
2283                 if (!strict_timing)
2284                         sleep(1);
2285                 else {
2286                         if (diff_time.tv_nsec) {
2287                                 diff_time.tv_sec = 0;
2288                                 diff_time.tv_nsec =
2289                                      1000UL * 1000 * 1000 - diff_time.tv_nsec;
2290                         } else
2291                                 diff_time.tv_sec = 1;
2292
2293                         condlog(3, "waiting for %lu.%06lu secs",
2294                                 diff_time.tv_sec,
2295                                 diff_time.tv_nsec / 1000);
2296                         if (nanosleep(&diff_time, NULL) != 0) {
2297                                 condlog(3, "nanosleep failed with error %d",
2298                                         errno);
2299                                 conf = get_multipath_config();
2300                                 conf->strict_timing = 0;
2301                                 put_multipath_config(conf);
2302                                 break;
2303                         }
2304                 }
2305         }
2306         pthread_cleanup_pop(1);
2307         return NULL;
2308 }
2309
2310 int
2311 configure (struct vectors * vecs)
2312 {
2313         struct multipath * mpp;
2314         struct path * pp;
2315         vector mpvec;
2316         int i, ret;
2317         struct config *conf;
2318         static int force_reload = FORCE_RELOAD_WEAK;
2319
2320         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc())) {
2321                 condlog(0, "couldn't allocate path vec in configure");
2322                 return 1;
2323         }
2324
2325         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc())) {
2326                 condlog(0, "couldn't allocate multipath vec in configure");
2327                 return 1;
2328         }
2329
2330         if (!(mpvec = vector_alloc())) {
2331                 condlog(0, "couldn't allocate new maps vec in configure");
2332                 return 1;
2333         }
2334
2335         /*
2336          * probe for current path (from sysfs) and map (from dm) sets
2337          */
2338         ret = path_discovery(vecs->pathvec, DI_ALL);
2339         if (ret < 0) {
2340                 condlog(0, "configure failed at path discovery");
2341                 goto fail;
2342         }
2343
2344         conf = get_multipath_config();
2345         pthread_cleanup_push(put_multipath_config, conf);
2346         vector_foreach_slot (vecs->pathvec, pp, i){
2347                 if (filter_path(conf, pp) > 0){
2348                         vector_del_slot(vecs->pathvec, i);
2349                         free_path(pp);
2350                         i--;
2351                 }
2352         }
2353         pthread_cleanup_pop(1);
2354
2355         if (map_discovery(vecs)) {
2356                 condlog(0, "configure failed at map discovery");
2357                 goto fail;
2358         }
2359
2360         /*
2361          * create new set of maps & push changed ones into dm
2362          * In the first call, use FORCE_RELOAD_WEAK to avoid making
2363          * superfluous ACT_RELOAD ioctls. Later calls are done
2364          * with FORCE_RELOAD_YES.
2365          */
2366         ret = coalesce_paths(vecs, mpvec, NULL, force_reload, CMD_NONE);
2367         if (force_reload == FORCE_RELOAD_WEAK)
2368                 force_reload = FORCE_RELOAD_YES;
2369         if (ret) {
2370                 condlog(0, "configure failed while coalescing paths");
2371                 goto fail;
2372         }
2373
2374         /*
2375          * may need to remove some maps which are no longer relevant
2376          * e.g., due to blacklist changes in conf file
2377          */
2378         if (coalesce_maps(vecs, mpvec)) {
2379                 condlog(0, "configure failed while coalescing maps");
2380                 goto fail;
2381         }
2382
2383         dm_lib_release();
2384
2385         sync_maps_state(mpvec);
2386         vector_foreach_slot(mpvec, mpp, i){
2387                 if (remember_wwid(mpp->wwid) == 1)
2388                         trigger_paths_udev_change(mpp, true);
2389                 update_map_pr(mpp);
2390         }
2391
2392         /*
2393          * purge dm of old maps
2394          */
2395         remove_maps(vecs);
2396
2397         /*
2398          * save new set of maps formed by considering current path state
2399          */
2400         vector_free(vecs->mpvec);
2401         vecs->mpvec = mpvec;
2402
2403         /*
2404          * start dm event waiter threads for these new maps
2405          */
2406         vector_foreach_slot(vecs->mpvec, mpp, i) {
2407                 if (wait_for_events(mpp, vecs)) {
2408                         remove_map(mpp, vecs, 1);
2409                         i--;
2410                         continue;
2411                 }
2412                 if (setup_multipath(vecs, mpp))
2413                         i--;
2414         }
2415         return 0;
2416
2417 fail:
2418         vector_free(mpvec);
2419         return 1;
2420 }
2421
2422 int
2423 need_to_delay_reconfig(struct vectors * vecs)
2424 {
2425         struct multipath *mpp;
2426         int i;
2427
2428         if (!VECTOR_SIZE(vecs->mpvec))
2429                 return 0;
2430
2431         vector_foreach_slot(vecs->mpvec, mpp, i) {
2432                 if (mpp->wait_for_udev)
2433                         return 1;
2434         }
2435         return 0;
2436 }
2437
2438 void rcu_free_config(struct rcu_head *head)
2439 {
2440         struct config *conf = container_of(head, struct config, rcu);
2441
2442         free_config(conf);
2443 }
2444
2445 int
2446 reconfigure (struct vectors * vecs)
2447 {
2448         struct config * old, *conf;
2449
2450         conf = load_config(DEFAULT_CONFIGFILE);
2451         if (!conf)
2452                 return 1;
2453
2454         /*
2455          * free old map and path vectors ... they use old conf state
2456          */
2457         if (VECTOR_SIZE(vecs->mpvec))
2458                 remove_maps_and_stop_waiters(vecs);
2459
2460         free_pathvec(vecs->pathvec, FREE_PATHS);
2461         vecs->pathvec = NULL;
2462         delete_all_foreign();
2463
2464         /* Re-read any timezone changes */
2465         tzset();
2466
2467         dm_tgt_version(conf->version, TGT_MPATH);
2468         if (verbosity)
2469                 conf->verbosity = verbosity;
2470         if (bindings_read_only)
2471                 conf->bindings_read_only = bindings_read_only;
2472         uxsock_timeout = conf->uxsock_timeout;
2473
2474         old = rcu_dereference(multipath_conf);
2475         rcu_assign_pointer(multipath_conf, conf);
2476         call_rcu(&old->rcu, rcu_free_config);
2477
2478         configure(vecs);
2479
2480
2481         return 0;
2482 }
2483
2484 static struct vectors *
2485 init_vecs (void)
2486 {
2487         struct vectors * vecs;
2488
2489         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
2490
2491         if (!vecs)
2492                 return NULL;
2493
2494         pthread_mutex_init(&vecs->lock.mutex, NULL);
2495
2496         return vecs;
2497 }
2498
2499 static void *
2500 signal_set(int signo, void (*func) (int))
2501 {
2502         int r;
2503         struct sigaction sig;
2504         struct sigaction osig;
2505
2506         sig.sa_handler = func;
2507         sigemptyset(&sig.sa_mask);
2508         sig.sa_flags = 0;
2509
2510         r = sigaction(signo, &sig, &osig);
2511
2512         if (r < 0)
2513                 return (SIG_ERR);
2514         else
2515                 return (osig.sa_handler);
2516 }
2517
2518 void
2519 handle_signals(bool nonfatal)
2520 {
2521         if (exit_sig) {
2522                 condlog(2, "exit (signal)");
2523                 exit_sig = 0;
2524                 exit_daemon();
2525         }
2526         if (!nonfatal)
2527                 return;
2528         if (reconfig_sig) {
2529                 condlog(2, "reconfigure (signal)");
2530                 set_config_state(DAEMON_CONFIGURE);
2531         }
2532         if (log_reset_sig) {
2533                 condlog(2, "reset log (signal)");
2534                 if (logsink == 1)
2535                         log_thread_reset();
2536         }
2537         reconfig_sig = 0;
2538         log_reset_sig = 0;
2539 }
2540
2541 static void
2542 sighup (int sig)
2543 {
2544         reconfig_sig = 1;
2545 }
2546
2547 static void
2548 sigend (int sig)
2549 {
2550         exit_sig = 1;
2551 }
2552
2553 static void
2554 sigusr1 (int sig)
2555 {
2556         log_reset_sig = 1;
2557 }
2558
2559 static void
2560 sigusr2 (int sig)
2561 {
2562         condlog(3, "SIGUSR2 received");
2563 }
2564
2565 static void
2566 signal_init(void)
2567 {
2568         sigset_t set;
2569
2570         /* block all signals */
2571         sigfillset(&set);
2572         /* SIGPIPE occurs if logging fails */
2573         sigdelset(&set, SIGPIPE);
2574         pthread_sigmask(SIG_SETMASK, &set, NULL);
2575
2576         /* Other signals will be unblocked in the uxlsnr thread */
2577         signal_set(SIGHUP, sighup);
2578         signal_set(SIGUSR1, sigusr1);
2579         signal_set(SIGUSR2, sigusr2);
2580         signal_set(SIGINT, sigend);
2581         signal_set(SIGTERM, sigend);
2582         signal_set(SIGPIPE, sigend);
2583 }
2584
2585 static void
2586 setscheduler (void)
2587 {
2588         int res;
2589         static struct sched_param sched_param = {
2590                 .sched_priority = 99
2591         };
2592
2593         res = sched_setscheduler (0, SCHED_RR, &sched_param);
2594
2595         if (res == -1)
2596                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
2597         return;
2598 }
2599
2600 static void
2601 set_oom_adj (void)
2602 {
2603 #ifdef OOM_SCORE_ADJ_MIN
2604         int retry = 1;
2605         char *file = "/proc/self/oom_score_adj";
2606         int score = OOM_SCORE_ADJ_MIN;
2607 #else
2608         int retry = 0;
2609         char *file = "/proc/self/oom_adj";
2610         int score = OOM_ADJUST_MIN;
2611 #endif
2612         FILE *fp;
2613         struct stat st;
2614         char *envp;
2615
2616         envp = getenv("OOMScoreAdjust");
2617         if (envp) {
2618                 condlog(3, "Using systemd provided OOMScoreAdjust");
2619                 return;
2620         }
2621         do {
2622                 if (stat(file, &st) == 0){
2623                         fp = fopen(file, "w");
2624                         if (!fp) {
2625                                 condlog(0, "couldn't fopen %s : %s", file,
2626                                         strerror(errno));
2627                                 return;
2628                         }
2629                         fprintf(fp, "%i", score);
2630                         fclose(fp);
2631                         return;
2632                 }
2633                 if (errno != ENOENT) {
2634                         condlog(0, "couldn't stat %s : %s", file,
2635                                 strerror(errno));
2636                         return;
2637                 }
2638 #ifdef OOM_ADJUST_MIN
2639                 file = "/proc/self/oom_adj";
2640                 score = OOM_ADJUST_MIN;
2641 #else
2642                 retry = 0;
2643 #endif
2644         } while (retry--);
2645         condlog(0, "couldn't adjust oom score");
2646 }
2647
2648 static int
2649 child (void * param)
2650 {
2651         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr, dmevent_thr;
2652         pthread_attr_t log_attr, misc_attr, uevent_attr;
2653         struct vectors * vecs;
2654         struct multipath * mpp;
2655         int i;
2656 #ifdef USE_SYSTEMD
2657         unsigned long checkint;
2658         int startup_done = 0;
2659 #endif
2660         int rc;
2661         int pid_fd = -1;
2662         struct config *conf;
2663         char *envp;
2664         int queue_without_daemon;
2665
2666         mlockall(MCL_CURRENT | MCL_FUTURE);
2667         signal_init();
2668         rcu_init();
2669
2670         setup_thread_attr(&misc_attr, 64 * 1024, 0);
2671         setup_thread_attr(&uevent_attr, DEFAULT_UEVENT_STACKSIZE * 1024, 0);
2672         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
2673         setup_thread_attr(&io_err_stat_attr, 32 * 1024, 0);
2674
2675         if (logsink == 1) {
2676                 setup_thread_attr(&log_attr, 64 * 1024, 0);
2677                 log_thread_start(&log_attr);
2678                 pthread_attr_destroy(&log_attr);
2679         }
2680         pid_fd = pidfile_create(DEFAULT_PIDFILE, daemon_pid);
2681         if (pid_fd < 0) {
2682                 condlog(1, "failed to create pidfile");
2683                 if (logsink == 1)
2684                         log_thread_stop();
2685                 exit(1);
2686         }
2687
2688         post_config_state(DAEMON_START);
2689
2690         condlog(2, "--------start up--------");
2691         condlog(2, "read " DEFAULT_CONFIGFILE);
2692
2693         conf = load_config(DEFAULT_CONFIGFILE);
2694         if (!conf)
2695                 goto failed;
2696
2697         if (verbosity)
2698                 conf->verbosity = verbosity;
2699         if (bindings_read_only)
2700                 conf->bindings_read_only = bindings_read_only;
2701         uxsock_timeout = conf->uxsock_timeout;
2702         rcu_assign_pointer(multipath_conf, conf);
2703         if (init_checkers(conf->multipath_dir)) {
2704                 condlog(0, "failed to initialize checkers");
2705                 goto failed;
2706         }
2707         if (init_prio(conf->multipath_dir)) {
2708                 condlog(0, "failed to initialize prioritizers");
2709                 goto failed;
2710         }
2711         /* Failing this is non-fatal */
2712
2713         init_foreign(conf->multipath_dir);
2714
2715         if (poll_dmevents)
2716                 poll_dmevents = dmevent_poll_supported();
2717         setlogmask(LOG_UPTO(conf->verbosity + 3));
2718
2719         envp = getenv("LimitNOFILE");
2720
2721         if (envp)
2722                 condlog(2,"Using systemd provided open fds limit of %s", envp);
2723         else
2724                 set_max_fds(conf->max_fds);
2725
2726         vecs = gvecs = init_vecs();
2727         if (!vecs)
2728                 goto failed;
2729
2730         setscheduler();
2731         set_oom_adj();
2732
2733 #ifdef USE_SYSTEMD
2734         envp = getenv("WATCHDOG_USEC");
2735         if (envp && sscanf(envp, "%lu", &checkint) == 1) {
2736                 /* Value is in microseconds */
2737                 conf->max_checkint = checkint / 1000000;
2738                 /* Rescale checkint */
2739                 if (conf->checkint > conf->max_checkint)
2740                         conf->checkint = conf->max_checkint;
2741                 else
2742                         conf->checkint = conf->max_checkint / 4;
2743                 condlog(3, "enabling watchdog, interval %d max %d",
2744                         conf->checkint, conf->max_checkint);
2745                 use_watchdog = conf->checkint;
2746         }
2747 #endif
2748         /*
2749          * Startup done, invalidate configuration
2750          */
2751         conf = NULL;
2752
2753         pthread_cleanup_push(config_cleanup, NULL);
2754         pthread_mutex_lock(&config_lock);
2755
2756         __post_config_state(DAEMON_IDLE);
2757         rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs);
2758         if (!rc) {
2759                 /* Wait for uxlsnr startup */
2760                 while (running_state == DAEMON_IDLE)
2761                         pthread_cond_wait(&config_cond, &config_lock);
2762         }
2763         pthread_cleanup_pop(1);
2764
2765         if (rc) {
2766                 condlog(0, "failed to create cli listener: %d", rc);
2767                 goto failed;
2768         }
2769         else if (running_state != DAEMON_CONFIGURE) {
2770                 condlog(0, "cli listener failed to start");
2771                 goto failed;
2772         }
2773
2774         if (poll_dmevents) {
2775                 if (init_dmevent_waiter(vecs)) {
2776                         condlog(0, "failed to allocate dmevents waiter info");
2777                         goto failed;
2778                 }
2779                 if ((rc = pthread_create(&dmevent_thr, &misc_attr,
2780                                          wait_dmevents, NULL))) {
2781                         condlog(0, "failed to create dmevent waiter thread: %d",
2782                                 rc);
2783                         goto failed;
2784                 }
2785         }
2786
2787         /*
2788          * Start uevent listener early to catch events
2789          */
2790         if ((rc = pthread_create(&uevent_thr, &uevent_attr, ueventloop, udev))) {
2791                 condlog(0, "failed to create uevent thread: %d", rc);
2792                 goto failed;
2793         }
2794         pthread_attr_destroy(&uevent_attr);
2795
2796         /*
2797          * start threads
2798          */
2799         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
2800                 condlog(0,"failed to create checker loop thread: %d", rc);
2801                 goto failed;
2802         }
2803         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
2804                 condlog(0, "failed to create uevent dispatcher: %d", rc);
2805                 goto failed;
2806         }
2807         pthread_attr_destroy(&misc_attr);
2808
2809         while (running_state != DAEMON_SHUTDOWN) {
2810                 pthread_cleanup_push(config_cleanup, NULL);
2811                 pthread_mutex_lock(&config_lock);
2812                 if (running_state != DAEMON_CONFIGURE &&
2813                     running_state != DAEMON_SHUTDOWN) {
2814                         pthread_cond_wait(&config_cond, &config_lock);
2815                 }
2816                 pthread_cleanup_pop(1);
2817                 if (running_state == DAEMON_CONFIGURE) {
2818                         pthread_cleanup_push(cleanup_lock, &vecs->lock);
2819                         lock(&vecs->lock);
2820                         pthread_testcancel();
2821                         if (!need_to_delay_reconfig(vecs)) {
2822                                 reconfigure(vecs);
2823                         } else {
2824                                 conf = get_multipath_config();
2825                                 conf->delayed_reconfig = 1;
2826                                 put_multipath_config(conf);
2827                         }
2828                         lock_cleanup_pop(vecs->lock);
2829                         post_config_state(DAEMON_IDLE);
2830 #ifdef USE_SYSTEMD
2831                         if (!startup_done) {
2832                                 sd_notify(0, "READY=1");
2833                                 startup_done = 1;
2834                         }
2835 #endif
2836                 }
2837         }
2838
2839         lock(&vecs->lock);
2840         conf = get_multipath_config();
2841         queue_without_daemon = conf->queue_without_daemon;
2842         put_multipath_config(conf);
2843         if (queue_without_daemon == QUE_NO_DAEMON_OFF)
2844                 vector_foreach_slot(vecs->mpvec, mpp, i)
2845                         dm_queue_if_no_path(mpp->alias, 0);
2846         remove_maps_and_stop_waiters(vecs);
2847         unlock(&vecs->lock);
2848
2849         pthread_cancel(check_thr);
2850         pthread_cancel(uevent_thr);
2851         pthread_cancel(uxlsnr_thr);
2852         pthread_cancel(uevq_thr);
2853         if (poll_dmevents)
2854                 pthread_cancel(dmevent_thr);
2855
2856         pthread_join(check_thr, NULL);
2857         pthread_join(uevent_thr, NULL);
2858         pthread_join(uxlsnr_thr, NULL);
2859         pthread_join(uevq_thr, NULL);
2860         if (poll_dmevents)
2861                 pthread_join(dmevent_thr, NULL);
2862
2863         stop_io_err_stat_thread();
2864
2865         lock(&vecs->lock);
2866         free_pathvec(vecs->pathvec, FREE_PATHS);
2867         vecs->pathvec = NULL;
2868         unlock(&vecs->lock);
2869
2870         pthread_mutex_destroy(&vecs->lock.mutex);
2871         FREE(vecs);
2872         vecs = NULL;
2873
2874         cleanup_foreign();
2875         cleanup_checkers();
2876         cleanup_prio();
2877         if (poll_dmevents)
2878                 cleanup_dmevent_waiter();
2879
2880         dm_lib_release();
2881         dm_lib_exit();
2882
2883         /* We're done here */
2884         condlog(3, "unlink pidfile");
2885         unlink(DEFAULT_PIDFILE);
2886
2887         condlog(2, "--------shut down-------");
2888
2889         if (logsink == 1)
2890                 log_thread_stop();
2891
2892         /*
2893          * Freeing config must be done after condlog() and dm_lib_exit(),
2894          * because logging functions like dlog() and dm_write_log()
2895          * reference the config.
2896          */
2897         conf = rcu_dereference(multipath_conf);
2898         rcu_assign_pointer(multipath_conf, NULL);
2899         call_rcu(&conf->rcu, rcu_free_config);
2900         udev_unref(udev);
2901         udev = NULL;
2902         pthread_attr_destroy(&waiter_attr);
2903         pthread_attr_destroy(&io_err_stat_attr);
2904 #ifdef _DEBUG_
2905         dbg_free_final(NULL);
2906 #endif
2907
2908 #ifdef USE_SYSTEMD
2909         sd_notify(0, "ERRNO=0");
2910 #endif
2911         exit(0);
2912
2913 failed:
2914 #ifdef USE_SYSTEMD
2915         sd_notify(0, "ERRNO=1");
2916 #endif
2917         if (pid_fd >= 0)
2918                 close(pid_fd);
2919         exit(1);
2920 }
2921
2922 static int
2923 daemonize(void)
2924 {
2925         int pid;
2926         int dev_null_fd;
2927
2928         if( (pid = fork()) < 0){
2929                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
2930                 return -1;
2931         }
2932         else if (pid != 0)
2933                 return pid;
2934
2935         setsid();
2936
2937         if ( (pid = fork()) < 0)
2938                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
2939         else if (pid != 0)
2940                 _exit(0);
2941
2942         if (chdir("/") < 0)
2943                 fprintf(stderr, "cannot chdir to '/', continuing\n");
2944
2945         dev_null_fd = open("/dev/null", O_RDWR);
2946         if (dev_null_fd < 0){
2947                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
2948                         strerror(errno));
2949                 _exit(0);
2950         }
2951
2952         close(STDIN_FILENO);
2953         if (dup(dev_null_fd) < 0) {
2954                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
2955                         strerror(errno));
2956                 _exit(0);
2957         }
2958         close(STDOUT_FILENO);
2959         if (dup(dev_null_fd) < 0) {
2960                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
2961                         strerror(errno));
2962                 _exit(0);
2963         }
2964         close(STDERR_FILENO);
2965         if (dup(dev_null_fd) < 0) {
2966                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
2967                         strerror(errno));
2968                 _exit(0);
2969         }
2970         close(dev_null_fd);
2971         daemon_pid = getpid();
2972         return 0;
2973 }
2974
2975 int
2976 main (int argc, char *argv[])
2977 {
2978         extern char *optarg;
2979         extern int optind;
2980         int arg;
2981         int err;
2982         int foreground = 0;
2983         struct config *conf;
2984
2985         ANNOTATE_BENIGN_RACE_SIZED(&multipath_conf, sizeof(multipath_conf),
2986                                    "Manipulated through RCU");
2987         ANNOTATE_BENIGN_RACE_SIZED(&running_state, sizeof(running_state),
2988                 "Suppress complaints about unprotected running_state reads");
2989         ANNOTATE_BENIGN_RACE_SIZED(&uxsock_timeout, sizeof(uxsock_timeout),
2990                 "Suppress complaints about this scalar variable");
2991
2992         logsink = 1;
2993
2994         if (getuid() != 0) {
2995                 fprintf(stderr, "need to be root\n");
2996                 exit(1);
2997         }
2998
2999         /* make sure we don't lock any path */
3000         if (chdir("/") < 0)
3001                 fprintf(stderr, "can't chdir to root directory : %s\n",
3002                         strerror(errno));
3003         umask(umask(077) | 022);
3004
3005         pthread_cond_init_mono(&config_cond);
3006
3007         udev = udev_new();
3008         libmp_udev_set_sync_support(0);
3009
3010         while ((arg = getopt(argc, argv, ":dsv:k::Bniw")) != EOF ) {
3011                 switch(arg) {
3012                 case 'd':
3013                         foreground = 1;
3014                         if (logsink > 0)
3015                                 logsink = 0;
3016                         //debug=1; /* ### comment me out ### */
3017                         break;
3018                 case 'v':
3019                         if (sizeof(optarg) > sizeof(char *) ||
3020                             !isdigit(optarg[0]))
3021                                 exit(1);
3022
3023                         verbosity = atoi(optarg);
3024                         break;
3025                 case 's':
3026                         logsink = -1;
3027                         break;
3028                 case 'k':
3029                         logsink = 0;
3030                         conf = load_config(DEFAULT_CONFIGFILE);
3031                         if (!conf)
3032                                 exit(1);
3033                         if (verbosity)
3034                                 conf->verbosity = verbosity;
3035                         uxsock_timeout = conf->uxsock_timeout;
3036                         err = uxclnt(optarg, uxsock_timeout + 100);
3037                         free_config(conf);
3038                         return err;
3039                 case 'B':
3040                         bindings_read_only = 1;
3041                         break;
3042                 case 'n':
3043                         condlog(0, "WARNING: ignoring deprecated option -n, use 'ignore_wwids = no' instead");
3044                         break;
3045                 case 'w':
3046                         poll_dmevents = 0;
3047                         break;
3048                 default:
3049                         fprintf(stderr, "Invalid argument '-%c'\n",
3050                                 optopt);
3051                         exit(1);
3052                 }
3053         }
3054         if (optind < argc) {
3055                 char cmd[CMDSIZE];
3056                 char * s = cmd;
3057                 char * c = s;
3058
3059                 logsink = 0;
3060                 conf = load_config(DEFAULT_CONFIGFILE);
3061                 if (!conf)
3062                         exit(1);
3063                 if (verbosity)
3064                         conf->verbosity = verbosity;
3065                 uxsock_timeout = conf->uxsock_timeout;
3066                 memset(cmd, 0x0, CMDSIZE);
3067                 while (optind < argc) {
3068                         if (strchr(argv[optind], ' '))
3069                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
3070                         else
3071                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
3072                         optind++;
3073                 }
3074                 c += snprintf(c, s + CMDSIZE - c, "\n");
3075                 err = uxclnt(s, uxsock_timeout + 100);
3076                 free_config(conf);
3077                 return err;
3078         }
3079
3080         if (foreground) {
3081                 if (!isatty(fileno(stdout)))
3082                         setbuf(stdout, NULL);
3083                 err = 0;
3084                 daemon_pid = getpid();
3085         } else
3086                 err = daemonize();
3087
3088         if (err < 0)
3089                 /* error */
3090                 exit(1);
3091         else if (err > 0)
3092                 /* parent dies */
3093                 exit(0);
3094         else
3095                 /* child lives */
3096                 return (child(NULL));
3097 }
3098
3099 void *  mpath_pr_event_handler_fn (void * pathp )
3100 {
3101         struct multipath * mpp;
3102         int i, ret, isFound;
3103         struct path * pp = (struct path *)pathp;
3104         struct prout_param_descriptor *param;
3105         struct prin_resp *resp;
3106
3107         rcu_register_thread();
3108         mpp = pp->mpp;
3109
3110         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
3111         if (!resp){
3112                 condlog(0,"%s Alloc failed for prin response", pp->dev);
3113                 goto out;
3114         }
3115
3116         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
3117         if (ret != MPATH_PR_SUCCESS )
3118         {
3119                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
3120                 goto out;
3121         }
3122
3123         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
3124                         resp->prin_descriptor.prin_readkeys.additional_length );
3125
3126         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
3127         {
3128                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
3129                 ret = MPATH_PR_SUCCESS;
3130                 goto out;
3131         }
3132         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ",
3133                 get_be64(mpp->reservation_key));
3134
3135         isFound =0;
3136         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
3137         {
3138                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
3139                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
3140                 if (!memcmp(&mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
3141                 {
3142                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
3143                         isFound =1;
3144                         break;
3145                 }
3146         }
3147         if (!isFound)
3148         {
3149                 condlog(0, "%s: Either device not registered or ", pp->dev);
3150                 condlog(0, "host is not authorised for registration. Skip path");
3151                 ret = MPATH_PR_OTHER;
3152                 goto out;
3153         }
3154
3155         param= malloc(sizeof(struct prout_param_descriptor));
3156         memset(param, 0 , sizeof(struct prout_param_descriptor));
3157         param->sa_flags = mpp->sa_flags;
3158         memcpy(param->sa_key, &mpp->reservation_key, 8);
3159         param->num_transportid = 0;
3160
3161         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
3162
3163         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
3164         if (ret != MPATH_PR_SUCCESS )
3165         {
3166                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
3167         }
3168         mpp->prflag = 1;
3169
3170         free(param);
3171 out:
3172         if (resp)
3173                 free(resp);
3174         rcu_unregister_thread();
3175         return NULL;
3176 }
3177
3178 int mpath_pr_event_handle(struct path *pp)
3179 {
3180         pthread_t thread;
3181         int rc;
3182         pthread_attr_t attr;
3183         struct multipath * mpp;
3184
3185         if (pp->bus != SYSFS_BUS_SCSI)
3186                 return 0;
3187
3188         mpp = pp->mpp;
3189
3190         if (!get_be64(mpp->reservation_key))
3191                 return -1;
3192
3193         pthread_attr_init(&attr);
3194         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
3195
3196         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
3197         if (rc) {
3198                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
3199                 return -1;
3200         }
3201         pthread_attr_destroy(&attr);
3202         rc = pthread_join(thread, NULL);
3203         return 0;
3204 }