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