d40c41663b53311736cd8535fb5de89e99bfb6ca
[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, vecs->mpvec)) {
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 /*
1787  * Returns '1' if the path has been checked, '-1' if it was blacklisted
1788  * and '0' otherwise
1789  */
1790 int
1791 check_path (struct vectors * vecs, struct path * pp, int ticks)
1792 {
1793         int newstate;
1794         int new_path_up = 0;
1795         int chkr_new_path_up = 0;
1796         int add_active;
1797         int disable_reinstate = 0;
1798         int oldchkrstate = pp->chkrstate;
1799         int retrigger_tries, checkint;
1800         struct config *conf;
1801         int ret;
1802
1803         if ((pp->initialized == INIT_OK ||
1804              pp->initialized == INIT_REQUESTED_UDEV) && !pp->mpp)
1805                 return 0;
1806
1807         if (pp->tick)
1808                 pp->tick -= (pp->tick > ticks) ? ticks : pp->tick;
1809         if (pp->tick)
1810                 return 0; /* don't check this path yet */
1811
1812         conf = get_multipath_config();
1813         retrigger_tries = conf->retrigger_tries;
1814         checkint = conf->checkint;
1815         put_multipath_config(conf);
1816         if (!pp->mpp && pp->initialized == INIT_MISSING_UDEV &&
1817             pp->retriggers < retrigger_tries) {
1818                 condlog(2, "%s: triggering change event to reinitialize",
1819                         pp->dev);
1820                 pp->initialized = INIT_REQUESTED_UDEV;
1821                 pp->retriggers++;
1822                 sysfs_attr_set_value(pp->udev, "uevent", "change",
1823                                      strlen("change"));
1824                 return 0;
1825         }
1826
1827         /*
1828          * provision a next check soonest,
1829          * in case we exit abnormaly from here
1830          */
1831         pp->tick = checkint;
1832
1833         newstate = path_offline(pp);
1834         /*
1835          * Wait for uevent for removed paths;
1836          * some LLDDs like zfcp keep paths unavailable
1837          * without sending uevents.
1838          */
1839         if (newstate == PATH_REMOVED)
1840                 newstate = PATH_DOWN;
1841
1842         if (newstate == PATH_UP) {
1843                 conf = get_multipath_config();
1844                 pthread_cleanup_push(put_multipath_config, conf);
1845                 newstate = get_state(pp, conf, 1, newstate);
1846                 pthread_cleanup_pop(1);
1847         } else
1848                 checker_clear_message(&pp->checker);
1849
1850         if (pp->wwid_changed) {
1851                 condlog(2, "%s: path wwid has changed. Refusing to use",
1852                         pp->dev);
1853                 newstate = PATH_DOWN;
1854         }
1855
1856         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1857                 condlog(2, "%s: unusable path", pp->dev);
1858                 conf = get_multipath_config();
1859                 pthread_cleanup_push(put_multipath_config, conf);
1860                 pathinfo(pp, conf, 0);
1861                 pthread_cleanup_pop(1);
1862                 return 1;
1863         }
1864         if (!pp->mpp) {
1865                 if (!strlen(pp->wwid) && pp->initialized != INIT_MISSING_UDEV &&
1866                     (newstate == PATH_UP || newstate == PATH_GHOST)) {
1867                         condlog(2, "%s: add missing path", pp->dev);
1868                         conf = get_multipath_config();
1869                         pthread_cleanup_push(put_multipath_config, conf);
1870                         ret = pathinfo(pp, conf, DI_ALL | DI_BLACKLIST);
1871                         pthread_cleanup_pop(1);
1872                         if (ret == PATHINFO_OK) {
1873                                 ev_add_path(pp, vecs, 1);
1874                                 pp->tick = 1;
1875                         } else if (ret == PATHINFO_SKIPPED)
1876                                 return -1;
1877                 }
1878                 return 0;
1879         }
1880         /*
1881          * Async IO in flight. Keep the previous path state
1882          * and reschedule as soon as possible
1883          */
1884         if (newstate == PATH_PENDING) {
1885                 pp->tick = 1;
1886                 return 0;
1887         }
1888         /*
1889          * Synchronize with kernel state
1890          */
1891         if (update_multipath_strings(pp->mpp, vecs->pathvec, 1)) {
1892                 condlog(1, "%s: Could not synchronize with kernel state",
1893                         pp->dev);
1894                 pp->dmstate = PSTATE_UNDEF;
1895         }
1896         /* if update_multipath_strings orphaned the path, quit early */
1897         if (!pp->mpp)
1898                 return 0;
1899
1900         if (pp->io_err_disable_reinstate && hit_io_err_recheck_time(pp)) {
1901                 pp->state = PATH_SHAKY;
1902                 /*
1903                  * to reschedule as soon as possible,so that this path can
1904                  * be recoverd in time
1905                  */
1906                 pp->tick = 1;
1907                 return 1;
1908         }
1909
1910         if ((newstate == PATH_UP || newstate == PATH_GHOST) &&
1911              pp->wait_checks > 0) {
1912                 if (pp->mpp->nr_active > 0) {
1913                         pp->state = PATH_DELAYED;
1914                         pp->wait_checks--;
1915                         return 1;
1916                 } else
1917                         pp->wait_checks = 0;
1918         }
1919
1920         /*
1921          * don't reinstate failed path, if its in stand-by
1922          * and if target supports only implicit tpgs mode.
1923          * this will prevent unnecessary i/o by dm on stand-by
1924          * paths if there are no other active paths in map.
1925          */
1926         disable_reinstate = (newstate == PATH_GHOST &&
1927                             pp->mpp->nr_active == 0 &&
1928                             pp->tpgs == TPGS_IMPLICIT) ? 1 : 0;
1929
1930         pp->chkrstate = newstate;
1931         if (newstate != pp->state) {
1932                 int oldstate = pp->state;
1933                 pp->state = newstate;
1934
1935                 LOG_MSG(1, checker_message(&pp->checker));
1936
1937                 /*
1938                  * upon state change, reset the checkint
1939                  * to the shortest delay
1940                  */
1941                 conf = get_multipath_config();
1942                 pp->checkint = conf->checkint;
1943                 put_multipath_config(conf);
1944
1945                 if (newstate != PATH_UP && newstate != PATH_GHOST) {
1946                         /*
1947                          * proactively fail path in the DM
1948                          */
1949                         if (oldstate == PATH_UP ||
1950                             oldstate == PATH_GHOST) {
1951                                 fail_path(pp, 1);
1952                                 if (pp->mpp->delay_wait_checks > 0 &&
1953                                     pp->watch_checks > 0) {
1954                                         pp->wait_checks = pp->mpp->delay_wait_checks;
1955                                         pp->watch_checks = 0;
1956                                 }
1957                         }else
1958                                 fail_path(pp, 0);
1959
1960                         /*
1961                          * cancel scheduled failback
1962                          */
1963                         pp->mpp->failback_tick = 0;
1964
1965                         pp->mpp->stat_path_failures++;
1966                         return 1;
1967                 }
1968
1969                 if(newstate == PATH_UP || newstate == PATH_GHOST){
1970                         if ( pp->mpp && pp->mpp->prflag ){
1971                                 /*
1972                                  * Check Persistent Reservation.
1973                                  */
1974                         condlog(2, "%s: checking persistent reservation "
1975                                 "registration", pp->dev);
1976                         mpath_pr_event_handle(pp);
1977                         }
1978                 }
1979
1980                 /*
1981                  * reinstate this path
1982                  */
1983                 if (oldstate != PATH_UP &&
1984                     oldstate != PATH_GHOST) {
1985                         if (pp->mpp->delay_watch_checks > 0)
1986                                 pp->watch_checks = pp->mpp->delay_watch_checks;
1987                         add_active = 1;
1988                 } else {
1989                         if (pp->watch_checks > 0)
1990                                 pp->watch_checks--;
1991                         add_active = 0;
1992                 }
1993                 if (!disable_reinstate && reinstate_path(pp, add_active)) {
1994                         condlog(3, "%s: reload map", pp->dev);
1995                         ev_add_path(pp, vecs, 1);
1996                         pp->tick = 1;
1997                         return 0;
1998                 }
1999                 new_path_up = 1;
2000
2001                 if (oldchkrstate != PATH_UP && oldchkrstate != PATH_GHOST)
2002                         chkr_new_path_up = 1;
2003
2004                 /*
2005                  * if at least one path is up in a group, and
2006                  * the group is disabled, re-enable it
2007                  */
2008                 if (newstate == PATH_UP)
2009                         enable_group(pp);
2010         }
2011         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
2012                 if ((pp->dmstate == PSTATE_FAILED ||
2013                     pp->dmstate == PSTATE_UNDEF) &&
2014                     !disable_reinstate) {
2015                         /* Clear IO errors */
2016                         if (reinstate_path(pp, 0)) {
2017                                 condlog(3, "%s: reload map", pp->dev);
2018                                 ev_add_path(pp, vecs, 1);
2019                                 pp->tick = 1;
2020                                 return 0;
2021                         }
2022                 } else {
2023                         unsigned int max_checkint;
2024                         LOG_MSG(4, checker_message(&pp->checker));
2025                         conf = get_multipath_config();
2026                         max_checkint = conf->max_checkint;
2027                         put_multipath_config(conf);
2028                         if (pp->checkint != max_checkint) {
2029                                 /*
2030                                  * double the next check delay.
2031                                  * max at conf->max_checkint
2032                                  */
2033                                 if (pp->checkint < (max_checkint / 2))
2034                                         pp->checkint = 2 * pp->checkint;
2035                                 else
2036                                         pp->checkint = max_checkint;
2037
2038                                 condlog(4, "%s: delay next check %is",
2039                                         pp->dev_t, pp->checkint);
2040                         }
2041                         if (pp->watch_checks > 0)
2042                                 pp->watch_checks--;
2043                         pp->tick = pp->checkint;
2044                 }
2045         }
2046         else if (newstate != PATH_UP && newstate != PATH_GHOST) {
2047                 if (pp->dmstate == PSTATE_ACTIVE ||
2048                     pp->dmstate == PSTATE_UNDEF)
2049                         fail_path(pp, 0);
2050                 if (newstate == PATH_DOWN) {
2051                         int log_checker_err;
2052
2053                         conf = get_multipath_config();
2054                         log_checker_err = conf->log_checker_err;
2055                         put_multipath_config(conf);
2056                         if (log_checker_err == LOG_CHKR_ERR_ONCE)
2057                                 LOG_MSG(3, checker_message(&pp->checker));
2058                         else
2059                                 LOG_MSG(2, checker_message(&pp->checker));
2060                 }
2061         }
2062
2063         pp->state = newstate;
2064
2065         if (pp->mpp->wait_for_udev)
2066                 return 1;
2067         /*
2068          * path prio refreshing
2069          */
2070         condlog(4, "path prio refresh");
2071
2072         if (update_prio(pp, new_path_up) &&
2073             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
2074              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
2075                 update_path_groups(pp->mpp, vecs, !new_path_up);
2076         else if (need_switch_pathgroup(pp->mpp, 0)) {
2077                 if (pp->mpp->pgfailback > 0 &&
2078                     (new_path_up || pp->mpp->failback_tick <= 0))
2079                         pp->mpp->failback_tick =
2080                                 pp->mpp->pgfailback + 1;
2081                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE ||
2082                          (chkr_new_path_up && followover_should_failback(pp)))
2083                         switch_pathgroup(pp->mpp);
2084         }
2085         return 1;
2086 }
2087
2088 static void init_path_check_interval(struct vectors *vecs)
2089 {
2090         struct config *conf;
2091         struct path *pp;
2092         unsigned int i;
2093
2094         vector_foreach_slot (vecs->pathvec, pp, i) {
2095                 conf = get_multipath_config();
2096                 pp->checkint = conf->checkint;
2097                 put_multipath_config(conf);
2098         }
2099 }
2100
2101 static void *
2102 checkerloop (void *ap)
2103 {
2104         struct vectors *vecs;
2105         struct path *pp;
2106         int count = 0;
2107         unsigned int i;
2108         struct timespec last_time;
2109         struct config *conf;
2110
2111         pthread_cleanup_push(rcu_unregister, NULL);
2112         rcu_register_thread();
2113         mlockall(MCL_CURRENT | MCL_FUTURE);
2114         vecs = (struct vectors *)ap;
2115         condlog(2, "path checkers start up");
2116
2117         /* Tweak start time for initial path check */
2118         if (clock_gettime(CLOCK_MONOTONIC, &last_time) != 0)
2119                 last_time.tv_sec = 0;
2120         else
2121                 last_time.tv_sec -= 1;
2122
2123         while (1) {
2124                 struct timespec diff_time, start_time, end_time;
2125                 int num_paths = 0, ticks = 0, strict_timing, rc = 0;
2126
2127                 if (clock_gettime(CLOCK_MONOTONIC, &start_time) != 0)
2128                         start_time.tv_sec = 0;
2129                 if (start_time.tv_sec && last_time.tv_sec) {
2130                         timespecsub(&start_time, &last_time, &diff_time);
2131                         condlog(4, "tick (%lu.%06lu secs)",
2132                                 diff_time.tv_sec, diff_time.tv_nsec / 1000);
2133                         last_time = start_time;
2134                         ticks = diff_time.tv_sec;
2135                 } else {
2136                         ticks = 1;
2137                         condlog(4, "tick (%d ticks)", ticks);
2138                 }
2139 #ifdef USE_SYSTEMD
2140                 if (use_watchdog)
2141                         sd_notify(0, "WATCHDOG=1");
2142 #endif
2143                 rc = set_config_state(DAEMON_RUNNING);
2144                 if (rc == ETIMEDOUT) {
2145                         condlog(4, "timeout waiting for DAEMON_IDLE");
2146                         continue;
2147                 }
2148
2149                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
2150                 lock(&vecs->lock);
2151                 pthread_testcancel();
2152                 vector_foreach_slot (vecs->pathvec, pp, i) {
2153                         rc = check_path(vecs, pp, ticks);
2154                         if (rc < 0) {
2155                                 vector_del_slot(vecs->pathvec, i);
2156                                 free_path(pp);
2157                                 i--;
2158                         } else
2159                                 num_paths += rc;
2160                 }
2161                 lock_cleanup_pop(vecs->lock);
2162
2163                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
2164                 lock(&vecs->lock);
2165                 pthread_testcancel();
2166                 defered_failback_tick(vecs->mpvec);
2167                 retry_count_tick(vecs->mpvec);
2168                 missing_uev_wait_tick(vecs);
2169                 ghost_delay_tick(vecs);
2170                 lock_cleanup_pop(vecs->lock);
2171
2172                 if (count)
2173                         count--;
2174                 else {
2175                         pthread_cleanup_push(cleanup_lock, &vecs->lock);
2176                         lock(&vecs->lock);
2177                         pthread_testcancel();
2178                         condlog(4, "map garbage collection");
2179                         mpvec_garbage_collector(vecs);
2180                         count = MAPGCINT;
2181                         lock_cleanup_pop(vecs->lock);
2182                 }
2183
2184                 diff_time.tv_nsec = 0;
2185                 if (start_time.tv_sec &&
2186                     clock_gettime(CLOCK_MONOTONIC, &end_time) == 0) {
2187                         timespecsub(&end_time, &start_time, &diff_time);
2188                         if (num_paths) {
2189                                 unsigned int max_checkint;
2190
2191                                 condlog(3, "checked %d path%s in %lu.%06lu secs",
2192                                         num_paths, num_paths > 1 ? "s" : "",
2193                                         diff_time.tv_sec,
2194                                         diff_time.tv_nsec / 1000);
2195                                 conf = get_multipath_config();
2196                                 max_checkint = conf->max_checkint;
2197                                 put_multipath_config(conf);
2198                                 if (diff_time.tv_sec > max_checkint)
2199                                         condlog(1, "path checkers took longer "
2200                                                 "than %lu seconds, consider "
2201                                                 "increasing max_polling_interval",
2202                                                 diff_time.tv_sec);
2203                         }
2204                 }
2205                 check_foreign();
2206                 post_config_state(DAEMON_IDLE);
2207                 conf = get_multipath_config();
2208                 strict_timing = conf->strict_timing;
2209                 put_multipath_config(conf);
2210                 if (!strict_timing)
2211                         sleep(1);
2212                 else {
2213                         if (diff_time.tv_nsec) {
2214                                 diff_time.tv_sec = 0;
2215                                 diff_time.tv_nsec =
2216                                      1000UL * 1000 * 1000 - diff_time.tv_nsec;
2217                         } else
2218                                 diff_time.tv_sec = 1;
2219
2220                         condlog(3, "waiting for %lu.%06lu secs",
2221                                 diff_time.tv_sec,
2222                                 diff_time.tv_nsec / 1000);
2223                         if (nanosleep(&diff_time, NULL) != 0) {
2224                                 condlog(3, "nanosleep failed with error %d",
2225                                         errno);
2226                                 conf = get_multipath_config();
2227                                 conf->strict_timing = 0;
2228                                 put_multipath_config(conf);
2229                                 break;
2230                         }
2231                 }
2232         }
2233         pthread_cleanup_pop(1);
2234         return NULL;
2235 }
2236
2237 int
2238 configure (struct vectors * vecs)
2239 {
2240         struct multipath * mpp;
2241         struct path * pp;
2242         vector mpvec;
2243         int i, ret;
2244         struct config *conf;
2245         static int force_reload = FORCE_RELOAD_WEAK;
2246
2247         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc())) {
2248                 condlog(0, "couldn't allocate path vec in configure");
2249                 return 1;
2250         }
2251
2252         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc())) {
2253                 condlog(0, "couldn't allocate multipath vec in configure");
2254                 return 1;
2255         }
2256
2257         if (!(mpvec = vector_alloc())) {
2258                 condlog(0, "couldn't allocate new maps vec in configure");
2259                 return 1;
2260         }
2261
2262         /*
2263          * probe for current path (from sysfs) and map (from dm) sets
2264          */
2265         ret = path_discovery(vecs->pathvec, DI_ALL);
2266         if (ret < 0) {
2267                 condlog(0, "configure failed at path discovery");
2268                 return 1;
2269         }
2270
2271         vector_foreach_slot (vecs->pathvec, pp, i){
2272                 conf = get_multipath_config();
2273                 pthread_cleanup_push(put_multipath_config, conf);
2274                 if (filter_path(conf, pp) > 0){
2275                         vector_del_slot(vecs->pathvec, i);
2276                         free_path(pp);
2277                         i--;
2278                 }
2279                 else
2280                         pp->checkint = conf->checkint;
2281                 pthread_cleanup_pop(1);
2282         }
2283         if (map_discovery(vecs)) {
2284                 condlog(0, "configure failed at map discovery");
2285                 return 1;
2286         }
2287
2288         /*
2289          * create new set of maps & push changed ones into dm
2290          * In the first call, use FORCE_RELOAD_WEAK to avoid making
2291          * superfluous ACT_RELOAD ioctls. Later calls are done
2292          * with FORCE_RELOAD_YES.
2293          */
2294         ret = coalesce_paths(vecs, mpvec, NULL, force_reload, CMD_NONE);
2295         if (force_reload == FORCE_RELOAD_WEAK)
2296                 force_reload = FORCE_RELOAD_YES;
2297         if (ret) {
2298                 condlog(0, "configure failed while coalescing paths");
2299                 return 1;
2300         }
2301
2302         /*
2303          * may need to remove some maps which are no longer relevant
2304          * e.g., due to blacklist changes in conf file
2305          */
2306         if (coalesce_maps(vecs, mpvec)) {
2307                 condlog(0, "configure failed while coalescing maps");
2308                 return 1;
2309         }
2310
2311         dm_lib_release();
2312
2313         sync_maps_state(mpvec);
2314         vector_foreach_slot(mpvec, mpp, i){
2315                 if (remember_wwid(mpp->wwid) == 1)
2316                         trigger_paths_udev_change(mpp, true);
2317                 update_map_pr(mpp);
2318         }
2319
2320         /*
2321          * purge dm of old maps
2322          */
2323         remove_maps(vecs);
2324
2325         /*
2326          * save new set of maps formed by considering current path state
2327          */
2328         vector_free(vecs->mpvec);
2329         vecs->mpvec = mpvec;
2330
2331         /*
2332          * start dm event waiter threads for these new maps
2333          */
2334         vector_foreach_slot(vecs->mpvec, mpp, i) {
2335                 if (wait_for_events(mpp, vecs)) {
2336                         remove_map(mpp, vecs, 1);
2337                         i--;
2338                         continue;
2339                 }
2340                 if (setup_multipath(vecs, mpp))
2341                         i--;
2342         }
2343         return 0;
2344 }
2345
2346 int
2347 need_to_delay_reconfig(struct vectors * vecs)
2348 {
2349         struct multipath *mpp;
2350         int i;
2351
2352         if (!VECTOR_SIZE(vecs->mpvec))
2353                 return 0;
2354
2355         vector_foreach_slot(vecs->mpvec, mpp, i) {
2356                 if (mpp->wait_for_udev)
2357                         return 1;
2358         }
2359         return 0;
2360 }
2361
2362 void rcu_free_config(struct rcu_head *head)
2363 {
2364         struct config *conf = container_of(head, struct config, rcu);
2365
2366         free_config(conf);
2367 }
2368
2369 int
2370 reconfigure (struct vectors * vecs)
2371 {
2372         struct config * old, *conf;
2373
2374         conf = load_config(DEFAULT_CONFIGFILE);
2375         if (!conf)
2376                 return 1;
2377
2378         /*
2379          * free old map and path vectors ... they use old conf state
2380          */
2381         if (VECTOR_SIZE(vecs->mpvec))
2382                 remove_maps_and_stop_waiters(vecs);
2383
2384         free_pathvec(vecs->pathvec, FREE_PATHS);
2385         vecs->pathvec = NULL;
2386         delete_all_foreign();
2387
2388         /* Re-read any timezone changes */
2389         tzset();
2390
2391         dm_tgt_version(conf->version, TGT_MPATH);
2392         if (verbosity)
2393                 conf->verbosity = verbosity;
2394         if (bindings_read_only)
2395                 conf->bindings_read_only = bindings_read_only;
2396         uxsock_timeout = conf->uxsock_timeout;
2397
2398         old = rcu_dereference(multipath_conf);
2399         rcu_assign_pointer(multipath_conf, conf);
2400         call_rcu(&old->rcu, rcu_free_config);
2401
2402         configure(vecs);
2403
2404
2405         return 0;
2406 }
2407
2408 static struct vectors *
2409 init_vecs (void)
2410 {
2411         struct vectors * vecs;
2412
2413         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
2414
2415         if (!vecs)
2416                 return NULL;
2417
2418         pthread_mutex_init(&vecs->lock.mutex, NULL);
2419
2420         return vecs;
2421 }
2422
2423 static void *
2424 signal_set(int signo, void (*func) (int))
2425 {
2426         int r;
2427         struct sigaction sig;
2428         struct sigaction osig;
2429
2430         sig.sa_handler = func;
2431         sigemptyset(&sig.sa_mask);
2432         sig.sa_flags = 0;
2433
2434         r = sigaction(signo, &sig, &osig);
2435
2436         if (r < 0)
2437                 return (SIG_ERR);
2438         else
2439                 return (osig.sa_handler);
2440 }
2441
2442 void
2443 handle_signals(bool nonfatal)
2444 {
2445         if (exit_sig) {
2446                 condlog(2, "exit (signal)");
2447                 exit_sig = 0;
2448                 exit_daemon();
2449         }
2450         if (!nonfatal)
2451                 return;
2452         if (reconfig_sig) {
2453                 condlog(2, "reconfigure (signal)");
2454                 set_config_state(DAEMON_CONFIGURE);
2455         }
2456         if (log_reset_sig) {
2457                 condlog(2, "reset log (signal)");
2458                 if (logsink == 1)
2459                         log_thread_reset();
2460         }
2461         reconfig_sig = 0;
2462         log_reset_sig = 0;
2463 }
2464
2465 static void
2466 sighup (int sig)
2467 {
2468         reconfig_sig = 1;
2469 }
2470
2471 static void
2472 sigend (int sig)
2473 {
2474         exit_sig = 1;
2475 }
2476
2477 static void
2478 sigusr1 (int sig)
2479 {
2480         log_reset_sig = 1;
2481 }
2482
2483 static void
2484 sigusr2 (int sig)
2485 {
2486         condlog(3, "SIGUSR2 received");
2487 }
2488
2489 static void
2490 signal_init(void)
2491 {
2492         sigset_t set;
2493
2494         /* block all signals */
2495         sigfillset(&set);
2496         /* SIGPIPE occurs if logging fails */
2497         sigdelset(&set, SIGPIPE);
2498         pthread_sigmask(SIG_SETMASK, &set, NULL);
2499
2500         /* Other signals will be unblocked in the uxlsnr thread */
2501         signal_set(SIGHUP, sighup);
2502         signal_set(SIGUSR1, sigusr1);
2503         signal_set(SIGUSR2, sigusr2);
2504         signal_set(SIGINT, sigend);
2505         signal_set(SIGTERM, sigend);
2506         signal_set(SIGPIPE, sigend);
2507 }
2508
2509 static void
2510 setscheduler (void)
2511 {
2512         int res;
2513         static struct sched_param sched_param = {
2514                 .sched_priority = 99
2515         };
2516
2517         res = sched_setscheduler (0, SCHED_RR, &sched_param);
2518
2519         if (res == -1)
2520                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
2521         return;
2522 }
2523
2524 static void
2525 set_oom_adj (void)
2526 {
2527 #ifdef OOM_SCORE_ADJ_MIN
2528         int retry = 1;
2529         char *file = "/proc/self/oom_score_adj";
2530         int score = OOM_SCORE_ADJ_MIN;
2531 #else
2532         int retry = 0;
2533         char *file = "/proc/self/oom_adj";
2534         int score = OOM_ADJUST_MIN;
2535 #endif
2536         FILE *fp;
2537         struct stat st;
2538         char *envp;
2539
2540         envp = getenv("OOMScoreAdjust");
2541         if (envp) {
2542                 condlog(3, "Using systemd provided OOMScoreAdjust");
2543                 return;
2544         }
2545         do {
2546                 if (stat(file, &st) == 0){
2547                         fp = fopen(file, "w");
2548                         if (!fp) {
2549                                 condlog(0, "couldn't fopen %s : %s", file,
2550                                         strerror(errno));
2551                                 return;
2552                         }
2553                         fprintf(fp, "%i", score);
2554                         fclose(fp);
2555                         return;
2556                 }
2557                 if (errno != ENOENT) {
2558                         condlog(0, "couldn't stat %s : %s", file,
2559                                 strerror(errno));
2560                         return;
2561                 }
2562 #ifdef OOM_ADJUST_MIN
2563                 file = "/proc/self/oom_adj";
2564                 score = OOM_ADJUST_MIN;
2565 #else
2566                 retry = 0;
2567 #endif
2568         } while (retry--);
2569         condlog(0, "couldn't adjust oom score");
2570 }
2571
2572 static int
2573 child (void * param)
2574 {
2575         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr, dmevent_thr;
2576         pthread_attr_t log_attr, misc_attr, uevent_attr;
2577         struct vectors * vecs;
2578         struct multipath * mpp;
2579         int i;
2580 #ifdef USE_SYSTEMD
2581         unsigned long checkint;
2582         int startup_done = 0;
2583 #endif
2584         int rc;
2585         int pid_fd = -1;
2586         struct config *conf;
2587         char *envp;
2588         int queue_without_daemon;
2589
2590         mlockall(MCL_CURRENT | MCL_FUTURE);
2591         signal_init();
2592         rcu_init();
2593
2594         setup_thread_attr(&misc_attr, 64 * 1024, 0);
2595         setup_thread_attr(&uevent_attr, DEFAULT_UEVENT_STACKSIZE * 1024, 0);
2596         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
2597         setup_thread_attr(&io_err_stat_attr, 32 * 1024, 0);
2598
2599         if (logsink == 1) {
2600                 setup_thread_attr(&log_attr, 64 * 1024, 0);
2601                 log_thread_start(&log_attr);
2602                 pthread_attr_destroy(&log_attr);
2603         }
2604         pid_fd = pidfile_create(DEFAULT_PIDFILE, daemon_pid);
2605         if (pid_fd < 0) {
2606                 condlog(1, "failed to create pidfile");
2607                 if (logsink == 1)
2608                         log_thread_stop();
2609                 exit(1);
2610         }
2611
2612         post_config_state(DAEMON_START);
2613
2614         condlog(2, "--------start up--------");
2615         condlog(2, "read " DEFAULT_CONFIGFILE);
2616
2617         conf = load_config(DEFAULT_CONFIGFILE);
2618         if (!conf)
2619                 goto failed;
2620
2621         if (verbosity)
2622                 conf->verbosity = verbosity;
2623         if (bindings_read_only)
2624                 conf->bindings_read_only = bindings_read_only;
2625         uxsock_timeout = conf->uxsock_timeout;
2626         rcu_assign_pointer(multipath_conf, conf);
2627         if (init_checkers(conf->multipath_dir)) {
2628                 condlog(0, "failed to initialize checkers");
2629                 goto failed;
2630         }
2631         if (init_prio(conf->multipath_dir)) {
2632                 condlog(0, "failed to initialize prioritizers");
2633                 goto failed;
2634         }
2635         /* Failing this is non-fatal */
2636
2637         init_foreign(conf->multipath_dir);
2638
2639         if (poll_dmevents)
2640                 poll_dmevents = dmevent_poll_supported();
2641         setlogmask(LOG_UPTO(conf->verbosity + 3));
2642
2643         envp = getenv("LimitNOFILE");
2644
2645         if (envp) {
2646                 condlog(2,"Using systemd provided open fds limit of %s", envp);
2647         } else if (conf->max_fds) {
2648                 struct rlimit fd_limit;
2649
2650                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
2651                         condlog(0, "can't get open fds limit: %s",
2652                                 strerror(errno));
2653                         fd_limit.rlim_cur = 0;
2654                         fd_limit.rlim_max = 0;
2655                 }
2656                 if (fd_limit.rlim_cur < conf->max_fds) {
2657                         fd_limit.rlim_cur = conf->max_fds;
2658                         if (fd_limit.rlim_max < conf->max_fds)
2659                                 fd_limit.rlim_max = conf->max_fds;
2660                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
2661                                 condlog(0, "can't set open fds limit to "
2662                                         "%lu/%lu : %s",
2663                                         fd_limit.rlim_cur, fd_limit.rlim_max,
2664                                         strerror(errno));
2665                         } else {
2666                                 condlog(3, "set open fds limit to %lu/%lu",
2667                                         fd_limit.rlim_cur, fd_limit.rlim_max);
2668                         }
2669                 }
2670
2671         }
2672
2673         vecs = gvecs = init_vecs();
2674         if (!vecs)
2675                 goto failed;
2676
2677         setscheduler();
2678         set_oom_adj();
2679
2680 #ifdef USE_SYSTEMD
2681         envp = getenv("WATCHDOG_USEC");
2682         if (envp && sscanf(envp, "%lu", &checkint) == 1) {
2683                 /* Value is in microseconds */
2684                 conf->max_checkint = checkint / 1000000;
2685                 /* Rescale checkint */
2686                 if (conf->checkint > conf->max_checkint)
2687                         conf->checkint = conf->max_checkint;
2688                 else
2689                         conf->checkint = conf->max_checkint / 4;
2690                 condlog(3, "enabling watchdog, interval %d max %d",
2691                         conf->checkint, conf->max_checkint);
2692                 use_watchdog = conf->checkint;
2693         }
2694 #endif
2695         /*
2696          * Startup done, invalidate configuration
2697          */
2698         conf = NULL;
2699
2700         /*
2701          * Signal start of configuration
2702          */
2703         post_config_state(DAEMON_CONFIGURE);
2704
2705         init_path_check_interval(vecs);
2706
2707         if (poll_dmevents) {
2708                 if (init_dmevent_waiter(vecs)) {
2709                         condlog(0, "failed to allocate dmevents waiter info");
2710                         goto failed;
2711                 }
2712                 if ((rc = pthread_create(&dmevent_thr, &misc_attr,
2713                                          wait_dmevents, NULL))) {
2714                         condlog(0, "failed to create dmevent waiter thread: %d",
2715                                 rc);
2716                         goto failed;
2717                 }
2718         }
2719
2720         /*
2721          * Start uevent listener early to catch events
2722          */
2723         if ((rc = pthread_create(&uevent_thr, &uevent_attr, ueventloop, udev))) {
2724                 condlog(0, "failed to create uevent thread: %d", rc);
2725                 goto failed;
2726         }
2727         pthread_attr_destroy(&uevent_attr);
2728         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
2729                 condlog(0, "failed to create cli listener: %d", rc);
2730                 goto failed;
2731         }
2732
2733         /*
2734          * start threads
2735          */
2736         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
2737                 condlog(0,"failed to create checker loop thread: %d", rc);
2738                 goto failed;
2739         }
2740         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
2741                 condlog(0, "failed to create uevent dispatcher: %d", rc);
2742                 goto failed;
2743         }
2744         pthread_attr_destroy(&misc_attr);
2745
2746         while (running_state != DAEMON_SHUTDOWN) {
2747                 pthread_cleanup_push(config_cleanup, NULL);
2748                 pthread_mutex_lock(&config_lock);
2749                 if (running_state != DAEMON_CONFIGURE &&
2750                     running_state != DAEMON_SHUTDOWN) {
2751                         pthread_cond_wait(&config_cond, &config_lock);
2752                 }
2753                 pthread_cleanup_pop(1);
2754                 if (running_state == DAEMON_CONFIGURE) {
2755                         pthread_cleanup_push(cleanup_lock, &vecs->lock);
2756                         lock(&vecs->lock);
2757                         pthread_testcancel();
2758                         if (!need_to_delay_reconfig(vecs)) {
2759                                 reconfigure(vecs);
2760                         } else {
2761                                 conf = get_multipath_config();
2762                                 conf->delayed_reconfig = 1;
2763                                 put_multipath_config(conf);
2764                         }
2765                         lock_cleanup_pop(vecs->lock);
2766                         post_config_state(DAEMON_IDLE);
2767 #ifdef USE_SYSTEMD
2768                         if (!startup_done) {
2769                                 sd_notify(0, "READY=1");
2770                                 startup_done = 1;
2771                         }
2772 #endif
2773                 }
2774         }
2775
2776         lock(&vecs->lock);
2777         conf = get_multipath_config();
2778         queue_without_daemon = conf->queue_without_daemon;
2779         put_multipath_config(conf);
2780         if (queue_without_daemon == QUE_NO_DAEMON_OFF)
2781                 vector_foreach_slot(vecs->mpvec, mpp, i)
2782                         dm_queue_if_no_path(mpp->alias, 0);
2783         remove_maps_and_stop_waiters(vecs);
2784         unlock(&vecs->lock);
2785
2786         pthread_cancel(check_thr);
2787         pthread_cancel(uevent_thr);
2788         pthread_cancel(uxlsnr_thr);
2789         pthread_cancel(uevq_thr);
2790         if (poll_dmevents)
2791                 pthread_cancel(dmevent_thr);
2792
2793         pthread_join(check_thr, NULL);
2794         pthread_join(uevent_thr, NULL);
2795         pthread_join(uxlsnr_thr, NULL);
2796         pthread_join(uevq_thr, NULL);
2797         if (poll_dmevents)
2798                 pthread_join(dmevent_thr, NULL);
2799
2800         stop_io_err_stat_thread();
2801
2802         lock(&vecs->lock);
2803         free_pathvec(vecs->pathvec, FREE_PATHS);
2804         vecs->pathvec = NULL;
2805         unlock(&vecs->lock);
2806
2807         pthread_mutex_destroy(&vecs->lock.mutex);
2808         FREE(vecs);
2809         vecs = NULL;
2810
2811         cleanup_foreign();
2812         cleanup_checkers();
2813         cleanup_prio();
2814         if (poll_dmevents)
2815                 cleanup_dmevent_waiter();
2816
2817         dm_lib_release();
2818         dm_lib_exit();
2819
2820         /* We're done here */
2821         condlog(3, "unlink pidfile");
2822         unlink(DEFAULT_PIDFILE);
2823
2824         condlog(2, "--------shut down-------");
2825
2826         if (logsink == 1)
2827                 log_thread_stop();
2828
2829         /*
2830          * Freeing config must be done after condlog() and dm_lib_exit(),
2831          * because logging functions like dlog() and dm_write_log()
2832          * reference the config.
2833          */
2834         conf = rcu_dereference(multipath_conf);
2835         rcu_assign_pointer(multipath_conf, NULL);
2836         call_rcu(&conf->rcu, rcu_free_config);
2837         udev_unref(udev);
2838         udev = NULL;
2839         pthread_attr_destroy(&waiter_attr);
2840         pthread_attr_destroy(&io_err_stat_attr);
2841 #ifdef _DEBUG_
2842         dbg_free_final(NULL);
2843 #endif
2844
2845 #ifdef USE_SYSTEMD
2846         sd_notify(0, "ERRNO=0");
2847 #endif
2848         exit(0);
2849
2850 failed:
2851 #ifdef USE_SYSTEMD
2852         sd_notify(0, "ERRNO=1");
2853 #endif
2854         if (pid_fd >= 0)
2855                 close(pid_fd);
2856         exit(1);
2857 }
2858
2859 static int
2860 daemonize(void)
2861 {
2862         int pid;
2863         int dev_null_fd;
2864
2865         if( (pid = fork()) < 0){
2866                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
2867                 return -1;
2868         }
2869         else if (pid != 0)
2870                 return pid;
2871
2872         setsid();
2873
2874         if ( (pid = fork()) < 0)
2875                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
2876         else if (pid != 0)
2877                 _exit(0);
2878
2879         if (chdir("/") < 0)
2880                 fprintf(stderr, "cannot chdir to '/', continuing\n");
2881
2882         dev_null_fd = open("/dev/null", O_RDWR);
2883         if (dev_null_fd < 0){
2884                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
2885                         strerror(errno));
2886                 _exit(0);
2887         }
2888
2889         close(STDIN_FILENO);
2890         if (dup(dev_null_fd) < 0) {
2891                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
2892                         strerror(errno));
2893                 _exit(0);
2894         }
2895         close(STDOUT_FILENO);
2896         if (dup(dev_null_fd) < 0) {
2897                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
2898                         strerror(errno));
2899                 _exit(0);
2900         }
2901         close(STDERR_FILENO);
2902         if (dup(dev_null_fd) < 0) {
2903                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
2904                         strerror(errno));
2905                 _exit(0);
2906         }
2907         close(dev_null_fd);
2908         daemon_pid = getpid();
2909         return 0;
2910 }
2911
2912 int
2913 main (int argc, char *argv[])
2914 {
2915         extern char *optarg;
2916         extern int optind;
2917         int arg;
2918         int err;
2919         int foreground = 0;
2920         struct config *conf;
2921
2922         ANNOTATE_BENIGN_RACE_SIZED(&multipath_conf, sizeof(multipath_conf),
2923                                    "Manipulated through RCU");
2924         ANNOTATE_BENIGN_RACE_SIZED(&running_state, sizeof(running_state),
2925                 "Suppress complaints about unprotected running_state reads");
2926         ANNOTATE_BENIGN_RACE_SIZED(&uxsock_timeout, sizeof(uxsock_timeout),
2927                 "Suppress complaints about this scalar variable");
2928
2929         logsink = 1;
2930
2931         if (getuid() != 0) {
2932                 fprintf(stderr, "need to be root\n");
2933                 exit(1);
2934         }
2935
2936         /* make sure we don't lock any path */
2937         if (chdir("/") < 0)
2938                 fprintf(stderr, "can't chdir to root directory : %s\n",
2939                         strerror(errno));
2940         umask(umask(077) | 022);
2941
2942         pthread_cond_init_mono(&config_cond);
2943
2944         udev = udev_new();
2945         libmp_udev_set_sync_support(0);
2946
2947         while ((arg = getopt(argc, argv, ":dsv:k::Bniw")) != EOF ) {
2948                 switch(arg) {
2949                 case 'd':
2950                         foreground = 1;
2951                         if (logsink > 0)
2952                                 logsink = 0;
2953                         //debug=1; /* ### comment me out ### */
2954                         break;
2955                 case 'v':
2956                         if (sizeof(optarg) > sizeof(char *) ||
2957                             !isdigit(optarg[0]))
2958                                 exit(1);
2959
2960                         verbosity = atoi(optarg);
2961                         break;
2962                 case 's':
2963                         logsink = -1;
2964                         break;
2965                 case 'k':
2966                         conf = load_config(DEFAULT_CONFIGFILE);
2967                         if (!conf)
2968                                 exit(1);
2969                         if (verbosity)
2970                                 conf->verbosity = verbosity;
2971                         uxsock_timeout = conf->uxsock_timeout;
2972                         uxclnt(optarg, uxsock_timeout + 100);
2973                         free_config(conf);
2974                         exit(0);
2975                 case 'B':
2976                         bindings_read_only = 1;
2977                         break;
2978                 case 'n':
2979                         condlog(0, "WARNING: ignoring deprecated option -n, use 'ignore_wwids = no' instead");
2980                         break;
2981                 case 'w':
2982                         poll_dmevents = 0;
2983                         break;
2984                 default:
2985                         fprintf(stderr, "Invalid argument '-%c'\n",
2986                                 optopt);
2987                         exit(1);
2988                 }
2989         }
2990         if (optind < argc) {
2991                 char cmd[CMDSIZE];
2992                 char * s = cmd;
2993                 char * c = s;
2994
2995                 conf = load_config(DEFAULT_CONFIGFILE);
2996                 if (!conf)
2997                         exit(1);
2998                 if (verbosity)
2999                         conf->verbosity = verbosity;
3000                 uxsock_timeout = conf->uxsock_timeout;
3001                 memset(cmd, 0x0, CMDSIZE);
3002                 while (optind < argc) {
3003                         if (strchr(argv[optind], ' '))
3004                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
3005                         else
3006                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
3007                         optind++;
3008                 }
3009                 c += snprintf(c, s + CMDSIZE - c, "\n");
3010                 uxclnt(s, uxsock_timeout + 100);
3011                 free_config(conf);
3012                 exit(0);
3013         }
3014
3015         if (foreground) {
3016                 if (!isatty(fileno(stdout)))
3017                         setbuf(stdout, NULL);
3018                 err = 0;
3019                 daemon_pid = getpid();
3020         } else
3021                 err = daemonize();
3022
3023         if (err < 0)
3024                 /* error */
3025                 exit(1);
3026         else if (err > 0)
3027                 /* parent dies */
3028                 exit(0);
3029         else
3030                 /* child lives */
3031                 return (child(NULL));
3032 }
3033
3034 void *  mpath_pr_event_handler_fn (void * pathp )
3035 {
3036         struct multipath * mpp;
3037         int i, ret, isFound;
3038         struct path * pp = (struct path *)pathp;
3039         struct prout_param_descriptor *param;
3040         struct prin_resp *resp;
3041
3042         rcu_register_thread();
3043         mpp = pp->mpp;
3044
3045         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
3046         if (!resp){
3047                 condlog(0,"%s Alloc failed for prin response", pp->dev);
3048                 goto out;
3049         }
3050
3051         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
3052         if (ret != MPATH_PR_SUCCESS )
3053         {
3054                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
3055                 goto out;
3056         }
3057
3058         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
3059                         resp->prin_descriptor.prin_readkeys.additional_length );
3060
3061         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
3062         {
3063                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
3064                 ret = MPATH_PR_SUCCESS;
3065                 goto out;
3066         }
3067         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ",
3068                 get_be64(mpp->reservation_key));
3069
3070         isFound =0;
3071         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
3072         {
3073                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
3074                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
3075                 if (!memcmp(&mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
3076                 {
3077                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
3078                         isFound =1;
3079                         break;
3080                 }
3081         }
3082         if (!isFound)
3083         {
3084                 condlog(0, "%s: Either device not registered or ", pp->dev);
3085                 condlog(0, "host is not authorised for registration. Skip path");
3086                 ret = MPATH_PR_OTHER;
3087                 goto out;
3088         }
3089
3090         param= malloc(sizeof(struct prout_param_descriptor));
3091         memset(param, 0 , sizeof(struct prout_param_descriptor));
3092         memcpy(param->sa_key, &mpp->reservation_key, 8);
3093         param->num_transportid = 0;
3094
3095         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
3096
3097         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
3098         if (ret != MPATH_PR_SUCCESS )
3099         {
3100                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
3101         }
3102         mpp->prflag = 1;
3103
3104         free(param);
3105 out:
3106         if (resp)
3107                 free(resp);
3108         rcu_unregister_thread();
3109         return NULL;
3110 }
3111
3112 int mpath_pr_event_handle(struct path *pp)
3113 {
3114         pthread_t thread;
3115         int rc;
3116         pthread_attr_t attr;
3117         struct multipath * mpp;
3118
3119         mpp = pp->mpp;
3120
3121         if (!get_be64(mpp->reservation_key))
3122                 return -1;
3123
3124         pthread_attr_init(&attr);
3125         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
3126
3127         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
3128         if (rc) {
3129                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
3130                 return -1;
3131         }
3132         pthread_attr_destroy(&attr);
3133         rc = pthread_join(thread, NULL);
3134         return 0;
3135 }