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