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