Return error when receiving CLI packet
[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 <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 #ifdef USE_SYSTEMD
21 #include <systemd/sd-daemon.h>
22 #endif
23 #include <semaphore.h>
24 #include <mpath_persist.h>
25 #include <time.h>
26
27 /*
28  * libcheckers
29  */
30 #include <checkers.h>
31
32 /*
33  * libmultipath
34  */
35 #include <parser.h>
36 #include <vector.h>
37 #include <memory.h>
38 #include <config.h>
39 #include <util.h>
40 #include <hwtable.h>
41 #include <defaults.h>
42 #include <structs.h>
43 #include <blacklist.h>
44 #include <structs_vec.h>
45 #include <dmparser.h>
46 #include <devmapper.h>
47 #include <sysfs.h>
48 #include <dict.h>
49 #include <discovery.h>
50 #include <debug.h>
51 #include <propsel.h>
52 #include <uevent.h>
53 #include <switchgroup.h>
54 #include <print.h>
55 #include <configure.h>
56 #include <prio.h>
57 #include <wwids.h>
58 #include <pgpolicies.h>
59 #include <uevent.h>
60 #include <log.h>
61
62 #include "main.h"
63 #include "pidfile.h"
64 #include "uxlsnr.h"
65 #include "uxclnt.h"
66 #include "cli.h"
67 #include "cli_handlers.h"
68 #include "lock.h"
69 #include "waiter.h"
70 #include "wwids.h"
71
72 #define FILE_NAME_SIZE 256
73 #define CMDSIZE 160
74
75 #define LOG_MSG(a, b) \
76 do { \
77         if (pp->offline) \
78                 condlog(a, "%s: %s - path offline", pp->mpp->alias, pp->dev); \
79         else if (strlen(b)) \
80                 condlog(a, "%s: %s - %s", pp->mpp->alias, pp->dev, b); \
81 } while(0)
82
83 struct mpath_event_param
84 {
85         char * devname;
86         struct multipath *mpp;
87 };
88
89 unsigned int mpath_mx_alloc_len;
90
91 int logsink;
92 enum daemon_status running_state;
93 pid_t daemon_pid;
94
95 static sem_t exit_sem;
96 /*
97  * global copy of vecs for use in sig handlers
98  */
99 struct vectors * gvecs;
100
101 struct udev * udev;
102
103 static int
104 need_switch_pathgroup (struct multipath * mpp, int refresh)
105 {
106         struct pathgroup * pgp;
107         struct path * pp;
108         unsigned int i, j;
109
110         if (!mpp || mpp->pgfailback == -FAILBACK_MANUAL)
111                 return 0;
112
113         /*
114          * Refresh path priority values
115          */
116         if (refresh)
117                 vector_foreach_slot (mpp->pg, pgp, i)
118                         vector_foreach_slot (pgp->paths, pp, j)
119                                 pathinfo(pp, conf->hwtable, DI_PRIO);
120
121         mpp->bestpg = select_path_group(mpp);
122
123         if (mpp->bestpg != mpp->nextpg)
124                 return 1;
125
126         return 0;
127 }
128
129 static void
130 switch_pathgroup (struct multipath * mpp)
131 {
132         mpp->stat_switchgroup++;
133         dm_switchgroup(mpp->alias, mpp->bestpg);
134         condlog(2, "%s: switch to path group #%i",
135                  mpp->alias, mpp->bestpg);
136 }
137
138 static int
139 coalesce_maps(struct vectors *vecs, vector nmpv)
140 {
141         struct multipath * ompp;
142         vector ompv = vecs->mpvec;
143         unsigned int i;
144
145         vector_foreach_slot (ompv, ompp, i) {
146                 condlog(3, "%s: coalesce map", ompp->alias);
147                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
148                         /*
149                          * remove all current maps not allowed by the
150                          * current configuration
151                          */
152                         if (dm_flush_map(ompp->alias)) {
153                                 condlog(0, "%s: unable to flush devmap",
154                                         ompp->alias);
155                                 /*
156                                  * may be just because the device is open
157                                  */
158                                 if (setup_multipath(vecs, ompp) != 0) {
159                                         i--;
160                                         continue;
161                                 }
162                                 if (!vector_alloc_slot(nmpv))
163                                         return 1;
164
165                                 vector_set_slot(nmpv, ompp);
166
167                                 vector_del_slot(ompv, i);
168                                 i--;
169                         }
170                         else {
171                                 dm_lib_release();
172                                 condlog(2, "%s devmap removed", ompp->alias);
173                         }
174                 } else if (conf->reassign_maps) {
175                         condlog(3, "%s: Reassign existing device-mapper"
176                                 " devices", ompp->alias);
177                         dm_reassign(ompp->alias);
178                 }
179         }
180         return 0;
181 }
182
183 void
184 sync_map_state(struct multipath *mpp)
185 {
186         struct pathgroup *pgp;
187         struct path *pp;
188         unsigned int i, j;
189
190         if (!mpp->pg)
191                 return;
192
193         vector_foreach_slot (mpp->pg, pgp, i){
194                 vector_foreach_slot (pgp->paths, pp, j){
195                         if (pp->state == PATH_UNCHECKED || 
196                             pp->state == PATH_WILD ||
197                             pp->state == PATH_DELAYED)
198                                 continue;
199                         if ((pp->dmstate == PSTATE_FAILED ||
200                              pp->dmstate == PSTATE_UNDEF) &&
201                             (pp->state == PATH_UP || pp->state == PATH_GHOST))
202                                 dm_reinstate_path(mpp->alias, pp->dev_t);
203                         else if ((pp->dmstate == PSTATE_ACTIVE ||
204                                   pp->dmstate == PSTATE_UNDEF) &&
205                                  (pp->state == PATH_DOWN ||
206                                   pp->state == PATH_SHAKY))
207                                 dm_fail_path(mpp->alias, pp->dev_t);
208                 }
209         }
210 }
211
212 static void
213 sync_maps_state(vector mpvec)
214 {
215         unsigned int i;
216         struct multipath *mpp;
217
218         vector_foreach_slot (mpvec, mpp, i)
219                 sync_map_state(mpp);
220 }
221
222 static int
223 flush_map(struct multipath * mpp, struct vectors * vecs, int nopaths)
224 {
225         int r;
226
227         if (nopaths)
228                 r = dm_flush_map_nopaths(mpp->alias, mpp->deferred_remove);
229         else
230                 r = dm_flush_map(mpp->alias);
231         /*
232          * clear references to this map before flushing so we can ignore
233          * the spurious uevent we may generate with the dm_flush_map call below
234          */
235         if (r) {
236                 /*
237                  * May not really be an error -- if the map was already flushed
238                  * from the device mapper by dmsetup(8) for instance.
239                  */
240                 if (r == 1)
241                         condlog(0, "%s: can't flush", mpp->alias);
242                 else {
243                         condlog(2, "%s: devmap deferred remove", mpp->alias);
244                         mpp->deferred_remove = DEFERRED_REMOVE_IN_PROGRESS;
245                 }
246                 return r;
247         }
248         else {
249                 dm_lib_release();
250                 condlog(2, "%s: map flushed", mpp->alias);
251         }
252
253         orphan_paths(vecs->pathvec, mpp);
254         remove_map_and_stop_waiter(mpp, vecs, 1);
255
256         return 0;
257 }
258
259 static int
260 uev_add_map (struct uevent * uev, struct vectors * vecs)
261 {
262         char *alias;
263         int major = -1, minor = -1, rc;
264
265         condlog(3, "%s: add map (uevent)", uev->kernel);
266         alias = uevent_get_dm_name(uev);
267         if (!alias) {
268                 condlog(3, "%s: No DM_NAME in uevent", uev->kernel);
269                 major = uevent_get_major(uev);
270                 minor = uevent_get_minor(uev);
271                 alias = dm_mapname(major, minor);
272                 if (!alias) {
273                         condlog(2, "%s: mapname not found for %d:%d",
274                                 uev->kernel, major, minor);
275                         return 1;
276                 }
277         }
278         rc = ev_add_map(uev->kernel, alias, vecs);
279         FREE(alias);
280         return rc;
281 }
282
283 int
284 ev_add_map (char * dev, char * alias, struct vectors * vecs)
285 {
286         char * refwwid;
287         struct multipath * mpp;
288         int map_present;
289         int r = 1;
290
291         map_present = dm_map_present(alias);
292
293         if (map_present && dm_type(alias, TGT_MPATH) <= 0) {
294                 condlog(4, "%s: not a multipath map", alias);
295                 return 0;
296         }
297
298         mpp = find_mp_by_alias(vecs->mpvec, alias);
299
300         if (mpp) {
301                 /*
302                  * Not really an error -- we generate our own uevent
303                  * if we create a multipath mapped device as a result
304                  * of uev_add_path
305                  */
306                 if (conf->reassign_maps) {
307                         condlog(3, "%s: Reassign existing device-mapper devices",
308                                 alias);
309                         dm_reassign(alias);
310                 }
311                 return 0;
312         }
313         condlog(2, "%s: adding map", alias);
314
315         /*
316          * now we can register the map
317          */
318         if (map_present) {
319                 if ((mpp = add_map_without_path(vecs, alias))) {
320                         sync_map_state(mpp);
321                         condlog(2, "%s: devmap %s registered", alias, dev);
322                         return 0;
323                 } else {
324                         condlog(2, "%s: uev_add_map failed", dev);
325                         return 1;
326                 }
327         }
328         r = get_refwwid(dev, DEV_DEVMAP, vecs->pathvec, &refwwid);
329
330         if (refwwid) {
331                 r = coalesce_paths(vecs, NULL, refwwid, 0);
332                 dm_lib_release();
333         }
334
335         if (!r)
336                 condlog(2, "%s: devmap %s added", alias, dev);
337         else if (r == 2)
338                 condlog(2, "%s: uev_add_map %s blacklisted", alias, dev);
339         else
340                 condlog(0, "%s: uev_add_map %s failed", alias, dev);
341
342         FREE(refwwid);
343         return r;
344 }
345
346 static int
347 uev_remove_map (struct uevent * uev, struct vectors * vecs)
348 {
349         char *alias;
350         int minor;
351         struct multipath *mpp;
352
353         condlog(2, "%s: remove map (uevent)", uev->kernel);
354         alias = uevent_get_dm_name(uev);
355         if (!alias) {
356                 condlog(3, "%s: No DM_NAME in uevent, ignoring", uev->kernel);
357                 return 0;
358         }
359         minor = uevent_get_minor(uev);
360         mpp = find_mp_by_minor(vecs->mpvec, minor);
361
362         if (!mpp) {
363                 condlog(2, "%s: devmap not registered, can't remove",
364                         uev->kernel);
365                 goto out;
366         }
367         if (strcmp(mpp->alias, alias)) {
368                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
369                         mpp->alias, mpp->dmi->minor, minor);
370                 goto out;
371         }
372
373         orphan_paths(vecs->pathvec, mpp);
374         remove_map_and_stop_waiter(mpp, vecs, 1);
375 out:
376         FREE(alias);
377         return 0;
378 }
379
380 int
381 ev_remove_map (char * devname, char * alias, int minor, struct vectors * vecs)
382 {
383         struct multipath * mpp;
384
385         mpp = find_mp_by_minor(vecs->mpvec, minor);
386
387         if (!mpp) {
388                 condlog(2, "%s: devmap not registered, can't remove",
389                         devname);
390                 return 0;
391         }
392         if (strcmp(mpp->alias, alias)) {
393                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
394                         mpp->alias, mpp->dmi->minor, minor);
395                 return 0;
396         }
397         return flush_map(mpp, vecs, 0);
398 }
399
400 static int
401 uev_add_path (struct uevent *uev, struct vectors * vecs)
402 {
403         struct path *pp;
404         int ret, i;
405
406         condlog(2, "%s: add path (uevent)", uev->kernel);
407         if (strstr(uev->kernel, "..") != NULL) {
408                 /*
409                  * Don't allow relative device names in the pathvec
410                  */
411                 condlog(0, "%s: path name is invalid", uev->kernel);
412                 return 1;
413         }
414
415         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
416         if (pp) {
417                 condlog(0, "%s: spurious uevent, path already in pathvec",
418                         uev->kernel);
419                 if (pp->mpp)
420                         return 0;
421                 if (!strlen(pp->wwid)) {
422                         udev_device_unref(pp->udev);
423                         pp->udev = udev_device_ref(uev->udev);
424                         ret = pathinfo(pp, conf->hwtable,
425                                        DI_ALL | DI_BLACKLIST);
426                         if (ret == 2) {
427                                 i = find_slot(vecs->pathvec, (void *)pp);
428                                 if (i != -1)
429                                         vector_del_slot(vecs->pathvec, i);
430                                 free_path(pp);
431                                 return 0;
432                         } else if (ret == 1) {
433                                 condlog(0, "%s: failed to reinitialize path",
434                                         uev->kernel);
435                                 return 1;
436                         }
437                 }
438         } else {
439                 /*
440                  * get path vital state
441                  */
442                 ret = store_pathinfo(vecs->pathvec, conf->hwtable,
443                                      uev->udev, DI_ALL, &pp);
444                 if (!pp) {
445                         if (ret == 2)
446                                 return 0;
447                         condlog(0, "%s: failed to store path info",
448                                 uev->kernel);
449                         return 1;
450                 }
451                 pp->checkint = conf->checkint;
452         }
453
454         return ev_add_path(pp, vecs);
455 }
456
457 /*
458  * returns:
459  * 0: added
460  * 1: error
461  */
462 int
463 ev_add_path (struct path * pp, struct vectors * vecs)
464 {
465         struct multipath * mpp;
466         char empty_buff[WWID_SIZE] = {0};
467         char params[PARAMS_SIZE] = {0};
468         int retries = 3;
469         int start_waiter = 0;
470         int ret;
471
472         /*
473          * need path UID to go any further
474          */
475         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
476                 condlog(0, "%s: failed to get path uid", pp->dev);
477                 goto fail; /* leave path added to pathvec */
478         }
479         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
480 rescan:
481         if (mpp) {
482                 if (mpp->size != pp->size) {
483                         condlog(0, "%s: failed to add new path %s, "
484                                 "device size mismatch",
485                                 mpp->alias, pp->dev);
486                         int i = find_slot(vecs->pathvec, (void *)pp);
487                         if (i != -1)
488                                 vector_del_slot(vecs->pathvec, i);
489                         free_path(pp);
490                         return 1;
491                 }
492
493                 condlog(4,"%s: adopting all paths for path %s",
494                         mpp->alias, pp->dev);
495                 if (adopt_paths(vecs->pathvec, mpp, 1))
496                         goto fail; /* leave path added to pathvec */
497
498                 verify_paths(mpp, vecs);
499                 mpp->flush_on_last_del = FLUSH_UNDEF;
500                 mpp->action = ACT_RELOAD;
501         } else {
502                 if (conf->find_multipaths &&
503                     !should_multipath(pp, vecs->pathvec)) {
504                         orphan_path(pp, "only one path");
505                         return 0;
506                 }
507                 condlog(4,"%s: creating new map", pp->dev);
508                 if ((mpp = add_map_with_path(vecs, pp, 1))) {
509                         mpp->action = ACT_CREATE;
510                         /*
511                          * We don't depend on ACT_CREATE, as domap will
512                          * set it to ACT_NOTHING when complete.
513                          */
514                         start_waiter = 1;
515                 }
516                 else
517                         goto fail; /* leave path added to pathvec */
518         }
519
520         /* persistent reseravtion check*/
521         mpath_pr_event_handle(pp);      
522
523         /*
524          * push the map to the device-mapper
525          */
526         if (setup_map(mpp, params, PARAMS_SIZE)) {
527                 condlog(0, "%s: failed to setup map for addition of new "
528                         "path %s", mpp->alias, pp->dev);
529                 goto fail_map;
530         }
531         /*
532          * reload the map for the multipath mapped device
533          */
534 retry:
535         ret = domap(mpp, params);
536         if (ret <= 0) {
537                 if (ret < 0 && retries-- > 0) {
538                         condlog(0, "%s: retry domap for addition of new "
539                                 "path %s", mpp->alias, pp->dev);
540                         sleep(1);
541                         goto retry;
542                 }
543                 condlog(0, "%s: failed in domap for addition of new "
544                         "path %s", mpp->alias, pp->dev);
545                 /*
546                  * deal with asynchronous uevents :((
547                  */
548                 if (mpp->action == ACT_RELOAD && retries-- > 0) {
549                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
550                         sleep(1);
551                         update_mpp_paths(mpp, vecs->pathvec);
552                         goto rescan;
553                 }
554                 else if (mpp->action == ACT_RELOAD)
555                         condlog(0, "%s: giving up reload", mpp->alias);
556                 else
557                         goto fail_map;
558         }
559         dm_lib_release();
560
561         /*
562          * update our state from kernel regardless of create or reload
563          */
564         if (setup_multipath(vecs, mpp))
565                 goto fail; /* if setup_multipath fails, it removes the map */
566
567         sync_map_state(mpp);
568
569         if ((mpp->action == ACT_CREATE ||
570              (mpp->action == ACT_NOTHING && start_waiter && !mpp->waiter)) &&
571             start_waiter_thread(mpp, vecs))
572                         goto fail_map;
573
574         if (retries >= 0) {
575                 condlog(2, "%s [%s]: path added to devmap %s",
576                         pp->dev, pp->dev_t, mpp->alias);
577                 return 0;
578         }
579         else
580                 goto fail;
581
582 fail_map:
583         remove_map(mpp, vecs, 1);
584 fail:
585         orphan_path(pp, "failed to add path");
586         return 1;
587 }
588
589 static int
590 uev_remove_path (struct uevent *uev, struct vectors * vecs)
591 {
592         struct path *pp;
593
594         condlog(2, "%s: remove path (uevent)", uev->kernel);
595         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
596
597         if (!pp) {
598                 /* Not an error; path might have been purged earlier */
599                 condlog(0, "%s: path already removed", uev->kernel);
600                 return 0;
601         }
602
603         return ev_remove_path(pp, vecs);
604 }
605
606 int
607 ev_remove_path (struct path *pp, struct vectors * vecs)
608 {
609         struct multipath * mpp;
610         int i, retval = 0;
611         char params[PARAMS_SIZE] = {0};
612
613         /*
614          * avoid referring to the map of an orphaned path
615          */
616         if ((mpp = pp->mpp)) {
617                 /*
618                  * transform the mp->pg vector of vectors of paths
619                  * into a mp->params string to feed the device-mapper
620                  */
621                 if (update_mpp_paths(mpp, vecs->pathvec)) {
622                         condlog(0, "%s: failed to update paths",
623                                 mpp->alias);
624                         goto fail;
625                 }
626                 if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
627                         vector_del_slot(mpp->paths, i);
628
629                 /*
630                  * remove the map IFF removing the last path
631                  */
632                 if (VECTOR_SIZE(mpp->paths) == 0) {
633                         char alias[WWID_SIZE];
634
635                         /*
636                          * flush_map will fail if the device is open
637                          */
638                         strncpy(alias, mpp->alias, WWID_SIZE);
639                         if (mpp->flush_on_last_del == FLUSH_ENABLED) {
640                                 condlog(2, "%s Last path deleted, disabling queueing", mpp->alias);
641                                 mpp->retry_tick = 0;
642                                 mpp->no_path_retry = NO_PATH_RETRY_FAIL;
643                                 mpp->flush_on_last_del = FLUSH_IN_PROGRESS;
644                                 dm_queue_if_no_path(mpp->alias, 0);
645                         }
646                         if (!flush_map(mpp, vecs, 1)) {
647                                 condlog(2, "%s: removed map after"
648                                         " removing all paths",
649                                         alias);
650                                 retval = 0;
651                                 goto out;
652                         }
653                         /*
654                          * Not an error, continue
655                          */
656                 }
657
658                 if (setup_map(mpp, params, PARAMS_SIZE)) {
659                         condlog(0, "%s: failed to setup map for"
660                                 " removal of path %s", mpp->alias, pp->dev);
661                         goto fail;
662                 }
663                 /*
664                  * reload the map
665                  */
666                 mpp->action = ACT_RELOAD;
667                 if (domap(mpp, params) <= 0) {
668                         condlog(0, "%s: failed in domap for "
669                                 "removal of path %s",
670                                 mpp->alias, pp->dev);
671                         retval = 1;
672                 } else {
673                         /*
674                          * update our state from kernel
675                          */
676                         if (setup_multipath(vecs, mpp))
677                                 return 1;
678                         sync_map_state(mpp);
679
680                         condlog(2, "%s [%s]: path removed from map %s",
681                                 pp->dev, pp->dev_t, mpp->alias);
682                 }
683         }
684
685 out:
686         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
687                 vector_del_slot(vecs->pathvec, i);
688
689         free_path(pp);
690
691         return retval;
692
693 fail:
694         remove_map_and_stop_waiter(mpp, vecs, 1);
695         return 1;
696 }
697
698 static int
699 uev_update_path (struct uevent *uev, struct vectors * vecs)
700 {
701         int ro, retval = 0;
702
703         ro = uevent_get_disk_ro(uev);
704
705         if (ro >= 0) {
706                 struct path * pp;
707
708                 condlog(2, "%s: update path write_protect to '%d' (uevent)",
709                         uev->kernel, ro);
710                 pp = find_path_by_dev(vecs->pathvec, uev->kernel);
711                 if (!pp) {
712                         condlog(0, "%s: spurious uevent, path not found",
713                                 uev->kernel);
714                         return 1;
715                 }
716                 if (pp->mpp) {
717                         retval = reload_map(vecs, pp->mpp, 0);
718
719                         condlog(2, "%s: map %s reloaded (retval %d)",
720                                 uev->kernel, pp->mpp->alias, retval);
721                 }
722
723         }
724
725         return retval;
726 }
727
728 static int
729 map_discovery (struct vectors * vecs)
730 {
731         struct multipath * mpp;
732         unsigned int i;
733
734         if (dm_get_maps(vecs->mpvec))
735                 return 1;
736
737         vector_foreach_slot (vecs->mpvec, mpp, i)
738                 if (setup_multipath(vecs, mpp))
739                         return 1;
740
741         return 0;
742 }
743
744 int
745 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
746 {
747         struct vectors * vecs;
748         int r;
749
750         *reply = NULL;
751         *len = 0;
752         vecs = (struct vectors *)trigger_data;
753
754         pthread_cleanup_push(cleanup_lock, &vecs->lock);
755         lock(vecs->lock);
756         pthread_testcancel();
757
758         r = parse_cmd(str, reply, len, vecs);
759
760         if (r > 0) {
761                 *reply = STRDUP("fail\n");
762                 *len = strlen(*reply) + 1;
763                 r = 1;
764         }
765         else if (!r && *len == 0) {
766                 *reply = STRDUP("ok\n");
767                 *len = strlen(*reply) + 1;
768                 r = 0;
769         }
770         /* else if (r < 0) leave *reply alone */
771
772         lock_cleanup_pop(vecs->lock);
773         return r;
774 }
775
776 static int
777 uev_discard(char * devpath)
778 {
779         char *tmp;
780         char a[11], b[11];
781
782         /*
783          * keep only block devices, discard partitions
784          */
785         tmp = strstr(devpath, "/block/");
786         if (tmp == NULL){
787                 condlog(4, "no /block/ in '%s'", devpath);
788                 return 1;
789         }
790         if (sscanf(tmp, "/block/%10s", a) != 1 ||
791             sscanf(tmp, "/block/%10[^/]/%10s", a, b) == 2) {
792                 condlog(4, "discard event on %s", devpath);
793                 return 1;
794         }
795         return 0;
796 }
797
798 int
799 uev_trigger (struct uevent * uev, void * trigger_data)
800 {
801         int r = 0;
802         struct vectors * vecs;
803
804         vecs = (struct vectors *)trigger_data;
805
806         if (uev_discard(uev->devpath))
807                 return 0;
808
809         pthread_cleanup_push(cleanup_lock, &vecs->lock);
810         lock(vecs->lock);
811         pthread_testcancel();
812
813         /*
814          * device map event
815          * Add events are ignored here as the tables
816          * are not fully initialised then.
817          */
818         if (!strncmp(uev->kernel, "dm-", 3)) {
819                 if (!strncmp(uev->action, "change", 6)) {
820                         r = uev_add_map(uev, vecs);
821                         goto out;
822                 }
823                 if (!strncmp(uev->action, "remove", 6)) {
824                         r = uev_remove_map(uev, vecs);
825                         goto out;
826                 }
827                 goto out;
828         }
829
830         /*
831          * path add/remove event
832          */
833         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
834                            uev->kernel) > 0)
835                 goto out;
836
837         if (!strncmp(uev->action, "add", 3)) {
838                 r = uev_add_path(uev, vecs);
839                 goto out;
840         }
841         if (!strncmp(uev->action, "remove", 6)) {
842                 r = uev_remove_path(uev, vecs);
843                 goto out;
844         }
845         if (!strncmp(uev->action, "change", 6)) {
846                 r = uev_update_path(uev, vecs);
847                 goto out;
848         }
849
850 out:
851         lock_cleanup_pop(vecs->lock);
852         return r;
853 }
854
855 static void *
856 ueventloop (void * ap)
857 {
858         struct udev *udev = ap;
859
860         if (uevent_listen(udev))
861                 condlog(0, "error starting uevent listener");
862
863         return NULL;
864 }
865
866 static void *
867 uevqloop (void * ap)
868 {
869         if (uevent_dispatch(&uev_trigger, ap))
870                 condlog(0, "error starting uevent dispatcher");
871
872         return NULL;
873 }
874 static void *
875 uxlsnrloop (void * ap)
876 {
877         if (cli_init())
878                 return NULL;
879
880         set_handler_callback(LIST+PATHS, cli_list_paths);
881         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
882         set_handler_callback(LIST+PATH, cli_list_path);
883         set_handler_callback(LIST+MAPS, cli_list_maps);
884         set_handler_callback(LIST+STATUS, cli_list_status);
885         set_handler_callback(LIST+DAEMON, cli_list_daemon);
886         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
887         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
888         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
889         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
890         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
891         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
892         set_handler_callback(LIST+CONFIG, cli_list_config);
893         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
894         set_handler_callback(LIST+DEVICES, cli_list_devices);
895         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
896         set_handler_callback(ADD+PATH, cli_add_path);
897         set_handler_callback(DEL+PATH, cli_del_path);
898         set_handler_callback(ADD+MAP, cli_add_map);
899         set_handler_callback(DEL+MAP, cli_del_map);
900         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
901         set_handler_callback(RECONFIGURE, cli_reconfigure);
902         set_handler_callback(SUSPEND+MAP, cli_suspend);
903         set_handler_callback(RESUME+MAP, cli_resume);
904         set_handler_callback(RESIZE+MAP, cli_resize);
905         set_handler_callback(RELOAD+MAP, cli_reload);
906         set_handler_callback(RESET+MAP, cli_reassign);
907         set_handler_callback(REINSTATE+PATH, cli_reinstate);
908         set_handler_callback(FAIL+PATH, cli_fail);
909         set_handler_callback(DISABLEQ+MAP, cli_disable_queueing);
910         set_handler_callback(RESTOREQ+MAP, cli_restore_queueing);
911         set_handler_callback(DISABLEQ+MAPS, cli_disable_all_queueing);
912         set_handler_callback(RESTOREQ+MAPS, cli_restore_all_queueing);
913         set_handler_callback(QUIT, cli_quit);
914         set_handler_callback(SHUTDOWN, cli_shutdown);
915         set_handler_callback(GETPRSTATUS+MAP, cli_getprstatus);
916         set_handler_callback(SETPRSTATUS+MAP, cli_setprstatus);
917         set_handler_callback(UNSETPRSTATUS+MAP, cli_unsetprstatus);
918         set_handler_callback(FORCEQ+DAEMON, cli_force_no_daemon_q);
919         set_handler_callback(RESTOREQ+DAEMON, cli_restore_no_daemon_q);
920
921         umask(077);
922         uxsock_listen(&uxsock_trigger, ap);
923
924         return NULL;
925 }
926
927 void
928 exit_daemon (void)
929 {
930         sem_post(&exit_sem);
931 }
932
933 const char *
934 daemon_status(void)
935 {
936         switch (running_state) {
937         case DAEMON_INIT:
938                 return "init";
939         case DAEMON_START:
940                 return "startup";
941         case DAEMON_CONFIGURE:
942                 return "configure";
943         case DAEMON_RUNNING:
944                 return "running";
945         case DAEMON_SHUTDOWN:
946                 return "shutdown";
947         }
948         return NULL;
949 }
950
951 static void
952 fail_path (struct path * pp, int del_active)
953 {
954         if (!pp->mpp)
955                 return;
956
957         condlog(2, "checker failed path %s in map %s",
958                  pp->dev_t, pp->mpp->alias);
959
960         dm_fail_path(pp->mpp->alias, pp->dev_t);
961         if (del_active)
962                 update_queue_mode_del_path(pp->mpp);
963 }
964
965 /*
966  * caller must have locked the path list before calling that function
967  */
968 static void
969 reinstate_path (struct path * pp, int add_active)
970 {
971         if (!pp->mpp)
972                 return;
973
974         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
975                 condlog(0, "%s: reinstate failed", pp->dev_t);
976         else {
977                 condlog(2, "%s: reinstated", pp->dev_t);
978                 if (add_active)
979                         update_queue_mode_add_path(pp->mpp);
980         }
981 }
982
983 static void
984 enable_group(struct path * pp)
985 {
986         struct pathgroup * pgp;
987
988         /*
989          * if path is added through uev_add_path, pgindex can be unset.
990          * next update_strings() will set it, upon map reload event.
991          *
992          * we can safely return here, because upon map reload, all
993          * PG will be enabled.
994          */
995         if (!pp->mpp->pg || !pp->pgindex)
996                 return;
997
998         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
999
1000         if (pgp->status == PGSTATE_DISABLED) {
1001                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
1002                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
1003         }
1004 }
1005
1006 static void
1007 mpvec_garbage_collector (struct vectors * vecs)
1008 {
1009         struct multipath * mpp;
1010         unsigned int i;
1011
1012         if (!vecs->mpvec)
1013                 return;
1014
1015         vector_foreach_slot (vecs->mpvec, mpp, i) {
1016                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
1017                         condlog(2, "%s: remove dead map", mpp->alias);
1018                         remove_map_and_stop_waiter(mpp, vecs, 1);
1019                         i--;
1020                 }
1021         }
1022 }
1023
1024 /* This is called after a path has started working again. It the multipath
1025  * device for this path uses the followover failback type, and this is the
1026  * best pathgroup, and this is the first path in the pathgroup to come back
1027  * up, then switch to this pathgroup */
1028 static int
1029 followover_should_failback(struct path * pp)
1030 {
1031         struct pathgroup * pgp;
1032         struct path *pp1;
1033         int i;
1034
1035         if (pp->mpp->pgfailback != -FAILBACK_FOLLOWOVER ||
1036             !pp->mpp->pg || !pp->pgindex ||
1037             pp->pgindex != pp->mpp->bestpg)
1038                 return 0;
1039
1040         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1041         vector_foreach_slot(pgp->paths, pp1, i) {
1042                 if (pp1 == pp)
1043                         continue;
1044                 if (pp1->chkrstate != PATH_DOWN && pp1->chkrstate != PATH_SHAKY)
1045                         return 0;
1046         }
1047         return 1;
1048 }
1049
1050 static void
1051 defered_failback_tick (vector mpvec)
1052 {
1053         struct multipath * mpp;
1054         unsigned int i;
1055
1056         vector_foreach_slot (mpvec, mpp, i) {
1057                 /*
1058                  * defered failback getting sooner
1059                  */
1060                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1061                         mpp->failback_tick--;
1062
1063                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1064                                 switch_pathgroup(mpp);
1065                 }
1066         }
1067 }
1068
1069 static void
1070 retry_count_tick(vector mpvec)
1071 {
1072         struct multipath *mpp;
1073         unsigned int i;
1074
1075         vector_foreach_slot (mpvec, mpp, i) {
1076                 if (mpp->retry_tick) {
1077                         mpp->stat_total_queueing_time++;
1078                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1079                         if(--mpp->retry_tick == 0) {
1080                                 dm_queue_if_no_path(mpp->alias, 0);
1081                                 condlog(2, "%s: Disable queueing", mpp->alias);
1082                         }
1083                 }
1084         }
1085 }
1086
1087 int update_prio(struct path *pp, int refresh_all)
1088 {
1089         int oldpriority;
1090         struct path *pp1;
1091         struct pathgroup * pgp;
1092         int i, j, changed = 0;
1093
1094         if (refresh_all) {
1095                 vector_foreach_slot (pp->mpp->pg, pgp, i) {
1096                         vector_foreach_slot (pgp->paths, pp1, j) {
1097                                 oldpriority = pp1->priority;
1098                                 pathinfo(pp1, conf->hwtable, DI_PRIO);
1099                                 if (pp1->priority != oldpriority)
1100                                         changed = 1;
1101                         }
1102                 }
1103                 return changed;
1104         }
1105         oldpriority = pp->priority;
1106         pathinfo(pp, conf->hwtable, DI_PRIO);
1107
1108         if (pp->priority == oldpriority)
1109                 return 0;
1110         return 1;
1111 }
1112
1113 int update_path_groups(struct multipath *mpp, struct vectors *vecs, int refresh)
1114 {
1115         if (reload_map(vecs, mpp, refresh))
1116                 return 1;
1117
1118         dm_lib_release();
1119         if (setup_multipath(vecs, mpp) != 0)
1120                 return 1;
1121         sync_map_state(mpp);
1122
1123         return 0;
1124 }
1125
1126 /*
1127  * Returns '1' if the path has been checked, '0' otherwise
1128  */
1129 int
1130 check_path (struct vectors * vecs, struct path * pp)
1131 {
1132         int newstate;
1133         int new_path_up = 0;
1134         int chkr_new_path_up = 0;
1135         int oldchkrstate = pp->chkrstate;
1136
1137         if (pp->initialized && !pp->mpp)
1138                 return 0;
1139
1140         if (pp->tick && --pp->tick)
1141                 return 0; /* don't check this path yet */
1142
1143         /*
1144          * provision a next check soonest,
1145          * in case we exit abnormaly from here
1146          */
1147         pp->tick = conf->checkint;
1148
1149         newstate = path_offline(pp);
1150         if (newstate == PATH_REMOVED) {
1151                 condlog(2, "%s: remove path (checker)", pp->dev);
1152                 ev_remove_path(pp, vecs);
1153                 return 0;
1154         }
1155         if (newstate == PATH_UP)
1156                 newstate = get_state(pp, 1);
1157         else
1158                 checker_clear_message(&pp->checker);
1159
1160         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1161                 condlog(2, "%s: unusable path", pp->dev);
1162                 pathinfo(pp, conf->hwtable, 0);
1163                 return 1;
1164         }
1165         if (!pp->mpp) {
1166                 if (!strlen(pp->wwid) &&
1167                     (newstate == PATH_UP || newstate == PATH_GHOST)) {
1168                         condlog(2, "%s: add missing path", pp->dev);
1169                         if (pathinfo(pp, conf->hwtable, DI_ALL) == 0) {
1170                                 ev_add_path(pp, vecs);
1171                                 pp->tick = 1;
1172                         }
1173                 }
1174                 return 0;
1175         }
1176         /*
1177          * Async IO in flight. Keep the previous path state
1178          * and reschedule as soon as possible
1179          */
1180         if (newstate == PATH_PENDING) {
1181                 pp->tick = 1;
1182                 return 0;
1183         }
1184         /*
1185          * Synchronize with kernel state
1186          */
1187         if (update_multipath_strings(pp->mpp, vecs->pathvec)) {
1188                 condlog(1, "%s: Could not synchronize with kernel state",
1189                         pp->dev);
1190                 pp->dmstate = PSTATE_UNDEF;
1191         }
1192         /* if update_multipath_strings orphaned the path, quit early */
1193         if (!pp->mpp)
1194                 return 0;
1195
1196         if ((newstate == PATH_UP || newstate == PATH_GHOST) &&
1197              pp->wait_checks > 0) {
1198                 if (pp->mpp && pp->mpp->nr_active > 0) {
1199                         pp->state = PATH_DELAYED;
1200                         pp->wait_checks--;
1201                         return 1;
1202                 } else
1203                         pp->wait_checks = 0;
1204         }
1205
1206         pp->chkrstate = newstate;
1207         if (newstate != pp->state) {
1208                 int oldstate = pp->state;
1209                 pp->state = newstate;
1210
1211                 if (strlen(checker_message(&pp->checker)))
1212                         LOG_MSG(1, checker_message(&pp->checker));
1213
1214                 /*
1215                  * upon state change, reset the checkint
1216                  * to the shortest delay
1217                  */
1218                 pp->checkint = conf->checkint;
1219
1220                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY) {
1221                         /*
1222                          * proactively fail path in the DM
1223                          */
1224                         if (oldstate == PATH_UP ||
1225                             oldstate == PATH_GHOST) {
1226                                 fail_path(pp, 1);
1227                                 if (pp->mpp->delay_wait_checks > 0 &&
1228                                     pp->watch_checks > 0) {
1229                                         pp->wait_checks = pp->mpp->delay_wait_checks;
1230                                         pp->watch_checks = 0;
1231                                 }
1232                         }else
1233                                 fail_path(pp, 0);
1234
1235                         /*
1236                          * cancel scheduled failback
1237                          */
1238                         pp->mpp->failback_tick = 0;
1239
1240                         pp->mpp->stat_path_failures++;
1241                         return 1;
1242                 }
1243
1244                 if(newstate == PATH_UP || newstate == PATH_GHOST){
1245                         if ( pp->mpp && pp->mpp->prflag ){
1246                                 /*
1247                                  * Check Persistent Reservation.
1248                                  */
1249                         condlog(2, "%s: checking persistent reservation "
1250                                 "registration", pp->dev);
1251                         mpath_pr_event_handle(pp);
1252                         }
1253                 }
1254
1255                 /*
1256                  * reinstate this path
1257                  */
1258                 if (oldstate != PATH_UP &&
1259                     oldstate != PATH_GHOST) {
1260                         if (pp->mpp->delay_watch_checks > 0)
1261                                 pp->watch_checks = pp->mpp->delay_watch_checks;
1262                         reinstate_path(pp, 1);
1263                 } else {
1264                         if (pp->watch_checks > 0)
1265                                 pp->watch_checks--;
1266                         reinstate_path(pp, 0);
1267                 }
1268                 new_path_up = 1;
1269
1270                 if (oldchkrstate != PATH_UP && oldchkrstate != PATH_GHOST)
1271                         chkr_new_path_up = 1;
1272
1273                 /*
1274                  * if at least one path is up in a group, and
1275                  * the group is disabled, re-enable it
1276                  */
1277                 if (newstate == PATH_UP)
1278                         enable_group(pp);
1279         }
1280         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1281                 if (pp->dmstate == PSTATE_FAILED ||
1282                     pp->dmstate == PSTATE_UNDEF) {
1283                         /* Clear IO errors */
1284                         reinstate_path(pp, 0);
1285                 } else {
1286                         LOG_MSG(4, checker_message(&pp->checker));
1287                         if (pp->checkint != conf->max_checkint) {
1288                                 /*
1289                                  * double the next check delay.
1290                                  * max at conf->max_checkint
1291                                  */
1292                                 if (pp->checkint < (conf->max_checkint / 2))
1293                                         pp->checkint = 2 * pp->checkint;
1294                                 else
1295                                         pp->checkint = conf->max_checkint;
1296
1297                                 condlog(4, "%s: delay next check %is",
1298                                         pp->dev_t, pp->checkint);
1299                         }
1300                         if (pp->watch_checks > 0)
1301                                 pp->watch_checks--;
1302                         pp->tick = pp->checkint;
1303                 }
1304         }
1305         else if (newstate == PATH_DOWN &&
1306                  strlen(checker_message(&pp->checker))) {
1307                 if (conf->log_checker_err == LOG_CHKR_ERR_ONCE)
1308                         LOG_MSG(3, checker_message(&pp->checker));
1309                 else
1310                         LOG_MSG(2, checker_message(&pp->checker));
1311         }
1312
1313         pp->state = newstate;
1314
1315         /*
1316          * path prio refreshing
1317          */
1318         condlog(4, "path prio refresh");
1319
1320         if (update_prio(pp, new_path_up) &&
1321             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
1322              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1323                 update_path_groups(pp->mpp, vecs, !new_path_up);
1324         else if (need_switch_pathgroup(pp->mpp, 0)) {
1325                 if (pp->mpp->pgfailback > 0 &&
1326                     (new_path_up || pp->mpp->failback_tick <= 0))
1327                         pp->mpp->failback_tick =
1328                                 pp->mpp->pgfailback + 1;
1329                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE ||
1330                          (chkr_new_path_up && followover_should_failback(pp)))
1331                         switch_pathgroup(pp->mpp);
1332         }
1333         return 1;
1334 }
1335
1336 static void *
1337 checkerloop (void *ap)
1338 {
1339         struct vectors *vecs;
1340         struct path *pp;
1341         int count = 0;
1342         unsigned int i;
1343
1344         mlockall(MCL_CURRENT | MCL_FUTURE);
1345         vecs = (struct vectors *)ap;
1346         condlog(2, "path checkers start up");
1347
1348         /*
1349          * init the path check interval
1350          */
1351         vector_foreach_slot (vecs->pathvec, pp, i) {
1352                 pp->checkint = conf->checkint;
1353         }
1354
1355         while (1) {
1356                 struct timeval diff_time, start_time, end_time;
1357                 int num_paths = 0;
1358
1359                 if (gettimeofday(&start_time, NULL) != 0)
1360                         start_time.tv_sec = 0;
1361                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1362                 lock(vecs->lock);
1363                 pthread_testcancel();
1364                 condlog(4, "tick");
1365 #ifdef USE_SYSTEMD
1366                 if (conf->watchdog)
1367                         sd_notify(0, "WATCHDOG=1");
1368 #endif
1369                 if (vecs->pathvec) {
1370                         vector_foreach_slot (vecs->pathvec, pp, i) {
1371                                 num_paths += check_path(vecs, pp);
1372                         }
1373                 }
1374                 if (vecs->mpvec) {
1375                         defered_failback_tick(vecs->mpvec);
1376                         retry_count_tick(vecs->mpvec);
1377                 }
1378                 if (count)
1379                         count--;
1380                 else {
1381                         condlog(4, "map garbage collection");
1382                         mpvec_garbage_collector(vecs);
1383                         count = MAPGCINT;
1384                 }
1385
1386                 lock_cleanup_pop(vecs->lock);
1387                 if (start_time.tv_sec &&
1388                     gettimeofday(&end_time, NULL) == 0 &&
1389                     num_paths) {
1390                         timersub(&end_time, &start_time, &diff_time);
1391                         condlog(3, "checked %d path%s in %lu.%06lu secs",
1392                                 num_paths, num_paths > 1 ? "s" : "",
1393                                 diff_time.tv_sec, diff_time.tv_usec);
1394                 }
1395                 sleep(1);
1396         }
1397         return NULL;
1398 }
1399
1400 int
1401 configure (struct vectors * vecs, int start_waiters)
1402 {
1403         struct multipath * mpp;
1404         struct path * pp;
1405         vector mpvec;
1406         int i, ret;
1407
1408         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1409                 return 1;
1410
1411         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1412                 return 1;
1413
1414         if (!(mpvec = vector_alloc()))
1415                 return 1;
1416
1417         /*
1418          * probe for current path (from sysfs) and map (from dm) sets
1419          */
1420         ret = path_discovery(vecs->pathvec, conf, DI_ALL);
1421         if (ret < 0)
1422                 return 1;
1423
1424         vector_foreach_slot (vecs->pathvec, pp, i){
1425                 if (filter_path(conf, pp) > 0){
1426                         vector_del_slot(vecs->pathvec, i);
1427                         free_path(pp);
1428                         i--;
1429                 }
1430                 else
1431                         pp->checkint = conf->checkint;
1432         }
1433         if (map_discovery(vecs))
1434                 return 1;
1435
1436         /*
1437          * create new set of maps & push changed ones into dm
1438          */
1439         if (coalesce_paths(vecs, mpvec, NULL, 1))
1440                 return 1;
1441
1442         /*
1443          * may need to remove some maps which are no longer relevant
1444          * e.g., due to blacklist changes in conf file
1445          */
1446         if (coalesce_maps(vecs, mpvec))
1447                 return 1;
1448
1449         dm_lib_release();
1450
1451         sync_maps_state(mpvec);
1452         vector_foreach_slot(mpvec, mpp, i){
1453                 remember_wwid(mpp->wwid);
1454                 update_map_pr(mpp);
1455         }
1456
1457         /*
1458          * purge dm of old maps
1459          */
1460         remove_maps(vecs);
1461
1462         /*
1463          * save new set of maps formed by considering current path state
1464          */
1465         vector_free(vecs->mpvec);
1466         vecs->mpvec = mpvec;
1467
1468         /*
1469          * start dm event waiter threads for these new maps
1470          */
1471         vector_foreach_slot(vecs->mpvec, mpp, i) {
1472                 if (setup_multipath(vecs, mpp))
1473                         return 1;
1474                 if (start_waiters)
1475                         if (start_waiter_thread(mpp, vecs))
1476                                 return 1;
1477         }
1478         return 0;
1479 }
1480
1481 int
1482 reconfigure (struct vectors * vecs)
1483 {
1484         struct config * old = conf;
1485         int retval = 1;
1486
1487         /*
1488          * free old map and path vectors ... they use old conf state
1489          */
1490         if (VECTOR_SIZE(vecs->mpvec))
1491                 remove_maps_and_stop_waiters(vecs);
1492
1493         if (VECTOR_SIZE(vecs->pathvec))
1494                 free_pathvec(vecs->pathvec, FREE_PATHS);
1495
1496         vecs->pathvec = NULL;
1497         conf = NULL;
1498
1499         /* Re-read any timezone changes */
1500         tzset();
1501
1502         if (!load_config(DEFAULT_CONFIGFILE, udev)) {
1503                 dm_drv_version(conf->version, TGT_MPATH);
1504                 conf->verbosity = old->verbosity;
1505                 conf->daemon = 1;
1506                 configure(vecs, 1);
1507                 free_config(old);
1508                 retval = 0;
1509         }
1510
1511         return retval;
1512 }
1513
1514 static struct vectors *
1515 init_vecs (void)
1516 {
1517         struct vectors * vecs;
1518
1519         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1520
1521         if (!vecs)
1522                 return NULL;
1523
1524         vecs->lock.mutex =
1525                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1526
1527         if (!vecs->lock.mutex)
1528                 goto out;
1529
1530         pthread_mutex_init(vecs->lock.mutex, NULL);
1531         vecs->lock.depth = 0;
1532
1533         return vecs;
1534
1535 out:
1536         FREE(vecs);
1537         condlog(0, "failed to init paths");
1538         return NULL;
1539 }
1540
1541 static void *
1542 signal_set(int signo, void (*func) (int))
1543 {
1544         int r;
1545         struct sigaction sig;
1546         struct sigaction osig;
1547
1548         sig.sa_handler = func;
1549         sigemptyset(&sig.sa_mask);
1550         sig.sa_flags = 0;
1551
1552         r = sigaction(signo, &sig, &osig);
1553
1554         if (r < 0)
1555                 return (SIG_ERR);
1556         else
1557                 return (osig.sa_handler);
1558 }
1559
1560 void
1561 handle_signals(void)
1562 {
1563         if (reconfig_sig && running_state == DAEMON_RUNNING) {
1564                 condlog(2, "reconfigure (signal)");
1565                 pthread_cleanup_push(cleanup_lock,
1566                                 &gvecs->lock);
1567                 lock(gvecs->lock);
1568                 pthread_testcancel();
1569                 reconfigure(gvecs);
1570                 lock_cleanup_pop(gvecs->lock);
1571         }
1572         if (log_reset_sig) {
1573                 condlog(2, "reset log (signal)");
1574                 pthread_mutex_lock(&logq_lock);
1575                 log_reset("multipathd");
1576                 pthread_mutex_unlock(&logq_lock);
1577         }
1578         reconfig_sig = 0;
1579         log_reset_sig = 0;
1580 }
1581
1582 static void
1583 sighup (int sig)
1584 {
1585         reconfig_sig = 1;
1586 }
1587
1588 static void
1589 sigend (int sig)
1590 {
1591         exit_daemon();
1592 }
1593
1594 static void
1595 sigusr1 (int sig)
1596 {
1597         log_reset_sig = 1;
1598 }
1599
1600 static void
1601 sigusr2 (int sig)
1602 {
1603         condlog(3, "SIGUSR2 received");
1604 }
1605
1606 static void
1607 signal_init(void)
1608 {
1609         sigset_t set;
1610
1611         sigemptyset(&set);
1612         sigaddset(&set, SIGHUP);
1613         sigaddset(&set, SIGUSR1);
1614         sigaddset(&set, SIGUSR2);
1615         pthread_sigmask(SIG_BLOCK, &set, NULL);
1616
1617         signal_set(SIGHUP, sighup);
1618         signal_set(SIGUSR1, sigusr1);
1619         signal_set(SIGUSR2, sigusr2);
1620         signal_set(SIGINT, sigend);
1621         signal_set(SIGTERM, sigend);
1622         signal(SIGPIPE, SIG_IGN);
1623 }
1624
1625 static void
1626 setscheduler (void)
1627 {
1628         int res;
1629         static struct sched_param sched_param = {
1630                 .sched_priority = 99
1631         };
1632
1633         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1634
1635         if (res == -1)
1636                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1637         return;
1638 }
1639
1640 static void
1641 set_oom_adj (void)
1642 {
1643 #ifdef OOM_SCORE_ADJ_MIN
1644         int retry = 1;
1645         char *file = "/proc/self/oom_score_adj";
1646         int score = OOM_SCORE_ADJ_MIN;
1647 #else
1648         int retry = 0;
1649         char *file = "/proc/self/oom_adj";
1650         int score = OOM_ADJUST_MIN;
1651 #endif
1652         FILE *fp;
1653         struct stat st;
1654         char *envp;
1655
1656         envp = getenv("OOMScoreAdjust");
1657         if (envp) {
1658                 condlog(3, "Using systemd provided OOMScoreAdjust");
1659                 return;
1660         }
1661         do {
1662                 if (stat(file, &st) == 0){
1663                         fp = fopen(file, "w");
1664                         if (!fp) {
1665                                 condlog(0, "couldn't fopen %s : %s", file,
1666                                         strerror(errno));
1667                                 return;
1668                         }
1669                         fprintf(fp, "%i", score);
1670                         fclose(fp);
1671                         return;
1672                 }
1673                 if (errno != ENOENT) {
1674                         condlog(0, "couldn't stat %s : %s", file,
1675                                 strerror(errno));
1676                         return;
1677                 }
1678 #ifdef OOM_ADJUST_MIN
1679                 file = "/proc/self/oom_adj";
1680                 score = OOM_ADJUST_MIN;
1681 #else
1682                 retry = 0;
1683 #endif
1684         } while (retry--);
1685         condlog(0, "couldn't adjust oom score");
1686 }
1687
1688 static int
1689 child (void * param)
1690 {
1691         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1692         pthread_attr_t log_attr, misc_attr, uevent_attr;
1693         struct vectors * vecs;
1694         struct multipath * mpp;
1695         int i;
1696 #ifdef USE_SYSTEMD
1697         unsigned long checkint;
1698 #endif
1699         int rc, pid_rc;
1700         char *envp;
1701
1702         mlockall(MCL_CURRENT | MCL_FUTURE);
1703         sem_init(&exit_sem, 0, 0);
1704         signal_init();
1705
1706         udev = udev_new();
1707
1708         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1709         setup_thread_attr(&uevent_attr, DEFAULT_UEVENT_STACKSIZE * 1024, 1);
1710         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1711
1712         if (logsink == 1) {
1713                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1714                 log_thread_start(&log_attr);
1715                 pthread_attr_destroy(&log_attr);
1716         }
1717
1718         running_state = DAEMON_START;
1719
1720 #ifdef USE_SYSTEMD
1721         sd_notify(0, "STATUS=startup");
1722 #endif
1723         condlog(2, "--------start up--------");
1724         condlog(2, "read " DEFAULT_CONFIGFILE);
1725
1726         if (load_config(DEFAULT_CONFIGFILE, udev))
1727                 goto failed;
1728
1729         dm_drv_version(conf->version, TGT_MPATH);
1730         if (init_checkers()) {
1731                 condlog(0, "failed to initialize checkers");
1732                 goto failed;
1733         }
1734         if (init_prio()) {
1735                 condlog(0, "failed to initialize prioritizers");
1736                 goto failed;
1737         }
1738
1739         setlogmask(LOG_UPTO(conf->verbosity + 3));
1740
1741         envp = getenv("LimitNOFILE");
1742
1743         if (envp) {
1744                 condlog(2,"Using systemd provided open fds limit of %s", envp);
1745         } else if (conf->max_fds) {
1746                 struct rlimit fd_limit;
1747
1748                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1749                         condlog(0, "can't get open fds limit: %s",
1750                                 strerror(errno));
1751                         fd_limit.rlim_cur = 0;
1752                         fd_limit.rlim_max = 0;
1753                 }
1754                 if (fd_limit.rlim_cur < conf->max_fds) {
1755                         fd_limit.rlim_cur = conf->max_fds;
1756                         if (fd_limit.rlim_max < conf->max_fds)
1757                                 fd_limit.rlim_max = conf->max_fds;
1758                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1759                                 condlog(0, "can't set open fds limit to "
1760                                         "%lu/%lu : %s",
1761                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1762                                         strerror(errno));
1763                         } else {
1764                                 condlog(3, "set open fds limit to %lu/%lu",
1765                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1766                         }
1767                 }
1768
1769         }
1770
1771         vecs = gvecs = init_vecs();
1772         if (!vecs)
1773                 goto failed;
1774
1775         setscheduler();
1776         set_oom_adj();
1777
1778         conf->daemon = 1;
1779         udev_set_sync_support(0);
1780 #ifdef USE_SYSTEMD
1781         envp = getenv("WATCHDOG_USEC");
1782         if (envp && sscanf(envp, "%lu", &checkint) == 1) {
1783                 /* Value is in microseconds */
1784                 conf->max_checkint = checkint / 1000000;
1785                 /* Rescale checkint */
1786                 if (conf->checkint > conf->max_checkint)
1787                         conf->checkint = conf->max_checkint;
1788                 else
1789                         conf->checkint = conf->max_checkint / 4;
1790                 condlog(3, "enabling watchdog, interval %d max %d",
1791                         conf->checkint, conf->max_checkint);
1792                 conf->watchdog = conf->checkint;
1793         }
1794 #endif
1795         /*
1796          * Start uevent listener early to catch events
1797          */
1798         if ((rc = pthread_create(&uevent_thr, &uevent_attr, ueventloop, udev))) {
1799                 condlog(0, "failed to create uevent thread: %d", rc);
1800                 goto failed;
1801         }
1802         pthread_attr_destroy(&uevent_attr);
1803         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1804                 condlog(0, "failed to create cli listener: %d", rc);
1805                 goto failed;
1806         }
1807         /*
1808          * fetch and configure both paths and multipaths
1809          */
1810 #ifdef USE_SYSTEMD
1811         sd_notify(0, "STATUS=configure");
1812 #endif
1813         running_state = DAEMON_CONFIGURE;
1814
1815         lock(vecs->lock);
1816         if (configure(vecs, 1)) {
1817                 unlock(vecs->lock);
1818                 condlog(0, "failure during configuration");
1819                 goto failed;
1820         }
1821         unlock(vecs->lock);
1822
1823         /*
1824          * start threads
1825          */
1826         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1827                 condlog(0,"failed to create checker loop thread: %d", rc);
1828                 goto failed;
1829         }
1830         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1831                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1832                 goto failed;
1833         }
1834         pthread_attr_destroy(&misc_attr);
1835
1836         /* Startup complete, create logfile */
1837         pid_rc = pidfile_create(DEFAULT_PIDFILE, daemon_pid);
1838         /* Ignore errors, we can live without */
1839
1840         running_state = DAEMON_RUNNING;
1841 #ifdef USE_SYSTEMD
1842         sd_notify(0, "READY=1\nSTATUS=running");
1843 #endif
1844
1845         /*
1846          * exit path
1847          */
1848         while(sem_wait(&exit_sem) != 0); /* Do nothing */
1849
1850 #ifdef USE_SYSTEMD
1851         sd_notify(0, "STATUS=shutdown");
1852 #endif
1853         running_state = DAEMON_SHUTDOWN;
1854         lock(vecs->lock);
1855         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1856                 vector_foreach_slot(vecs->mpvec, mpp, i)
1857                         dm_queue_if_no_path(mpp->alias, 0);
1858         remove_maps_and_stop_waiters(vecs);
1859         unlock(vecs->lock);
1860
1861         pthread_cancel(check_thr);
1862         pthread_cancel(uevent_thr);
1863         pthread_cancel(uxlsnr_thr);
1864         pthread_cancel(uevq_thr);
1865
1866         lock(vecs->lock);
1867         free_pathvec(vecs->pathvec, FREE_PATHS);
1868         vecs->pathvec = NULL;
1869         unlock(vecs->lock);
1870         /* Now all the waitevent threads will start rushing in. */
1871         while (vecs->lock.depth > 0) {
1872                 sleep (1); /* This is weak. */
1873                 condlog(3, "Have %d wait event checkers threads to de-alloc,"
1874                         " waiting...", vecs->lock.depth);
1875         }
1876         pthread_mutex_destroy(vecs->lock.mutex);
1877         FREE(vecs->lock.mutex);
1878         vecs->lock.depth = 0;
1879         vecs->lock.mutex = NULL;
1880         FREE(vecs);
1881         vecs = NULL;
1882
1883         cleanup_checkers();
1884         cleanup_prio();
1885
1886         dm_lib_release();
1887         dm_lib_exit();
1888
1889         /* We're done here */
1890         if (!pid_rc) {
1891                 condlog(3, "unlink pidfile");
1892                 unlink(DEFAULT_PIDFILE);
1893         }
1894
1895         condlog(2, "--------shut down-------");
1896
1897         if (logsink == 1)
1898                 log_thread_stop();
1899
1900         /*
1901          * Freeing config must be done after condlog() and dm_lib_exit(),
1902          * because logging functions like dlog() and dm_write_log()
1903          * reference the config.
1904          */
1905         free_config(conf);
1906         conf = NULL;
1907         udev_unref(udev);
1908         udev = NULL;
1909 #ifdef _DEBUG_
1910         dbg_free_final(NULL);
1911 #endif
1912
1913 #ifdef USE_SYSTEMD
1914         sd_notify(0, "ERRNO=0");
1915 #endif
1916         exit(0);
1917
1918 failed:
1919 #ifdef USE_SYSTEMD
1920         sd_notify(0, "ERRNO=1");
1921 #endif
1922         exit(1);
1923 }
1924
1925 static int
1926 daemonize(void)
1927 {
1928         int pid;
1929         int dev_null_fd;
1930
1931         if( (pid = fork()) < 0){
1932                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1933                 return -1;
1934         }
1935         else if (pid != 0)
1936                 return pid;
1937
1938         setsid();
1939
1940         if ( (pid = fork()) < 0)
1941                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1942         else if (pid != 0)
1943                 _exit(0);
1944
1945         if (chdir("/") < 0)
1946                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1947
1948         dev_null_fd = open("/dev/null", O_RDWR);
1949         if (dev_null_fd < 0){
1950                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
1951                         strerror(errno));
1952                 _exit(0);
1953         }
1954
1955         close(STDIN_FILENO);
1956         if (dup(dev_null_fd) < 0) {
1957                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
1958                         strerror(errno));
1959                 _exit(0);
1960         }
1961         close(STDOUT_FILENO);
1962         if (dup(dev_null_fd) < 0) {
1963                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
1964                         strerror(errno));
1965                 _exit(0);
1966         }
1967         close(STDERR_FILENO);
1968         if (dup(dev_null_fd) < 0) {
1969                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
1970                         strerror(errno));
1971                 _exit(0);
1972         }
1973         close(dev_null_fd);
1974         daemon_pid = getpid();
1975         return 0;
1976 }
1977
1978 int
1979 main (int argc, char *argv[])
1980 {
1981         extern char *optarg;
1982         extern int optind;
1983         int arg;
1984         int err;
1985         int foreground = 0;
1986
1987         logsink = 1;
1988         running_state = DAEMON_INIT;
1989         dm_init();
1990
1991         if (getuid() != 0) {
1992                 fprintf(stderr, "need to be root\n");
1993                 exit(1);
1994         }
1995
1996         /* make sure we don't lock any path */
1997         if (chdir("/") < 0)
1998                 fprintf(stderr, "can't chdir to root directory : %s\n",
1999                         strerror(errno));
2000         umask(umask(077) | 022);
2001
2002         conf = alloc_config();
2003
2004         if (!conf)
2005                 exit(1);
2006
2007         while ((arg = getopt(argc, argv, ":dsv:k::B")) != EOF ) {
2008         switch(arg) {
2009                 case 'd':
2010                         foreground = 1;
2011                         if (logsink > 0)
2012                                 logsink = 0;
2013                         //debug=1; /* ### comment me out ### */
2014                         break;
2015                 case 'v':
2016                         if (sizeof(optarg) > sizeof(char *) ||
2017                             !isdigit(optarg[0]))
2018                                 exit(1);
2019
2020                         conf->verbosity = atoi(optarg);
2021                         break;
2022                 case 's':
2023                         logsink = -1;
2024                         break;
2025                 case 'k':
2026                         uxclnt(optarg, DEFAULT_UXSOCK_TIMEOUT);
2027                         exit(0);
2028                 case 'B':
2029                         conf->bindings_read_only = 1;
2030                         break;
2031                 default:
2032                         ;
2033                 }
2034         }
2035         if (optind < argc) {
2036                 char cmd[CMDSIZE];
2037                 char * s = cmd;
2038                 char * c = s;
2039
2040                 while (optind < argc) {
2041                         if (strchr(argv[optind], ' '))
2042                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
2043                         else
2044                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
2045                         optind++;
2046                 }
2047                 c += snprintf(c, s + CMDSIZE - c, "\n");
2048                 uxclnt(s, DEFAULT_UXSOCK_TIMEOUT);
2049                 exit(0);
2050         }
2051
2052         if (foreground) {
2053                 if (!isatty(fileno(stdout)))
2054                         setbuf(stdout, NULL);
2055                 err = 0;
2056                 daemon_pid = getpid();
2057         } else
2058                 err = daemonize();
2059
2060         if (err < 0)
2061                 /* error */
2062                 exit(1);
2063         else if (err > 0)
2064                 /* parent dies */
2065                 exit(0);
2066         else
2067                 /* child lives */
2068                 return (child(NULL));
2069 }
2070
2071 void *  mpath_pr_event_handler_fn (void * pathp )
2072 {
2073         struct multipath * mpp;
2074         int i,j, ret, isFound;
2075         struct path * pp = (struct path *)pathp;
2076         unsigned char *keyp;
2077         uint64_t prkey;
2078         struct prout_param_descriptor *param;
2079         struct prin_resp *resp;
2080
2081         mpp = pp->mpp;
2082
2083         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
2084         if (!resp){
2085                 condlog(0,"%s Alloc failed for prin response", pp->dev);
2086                 return NULL;
2087         }
2088
2089         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
2090         if (ret != MPATH_PR_SUCCESS )
2091         {
2092                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
2093                 goto out;
2094         }
2095
2096         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
2097                         resp->prin_descriptor.prin_readkeys.additional_length );
2098
2099         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
2100         {
2101                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
2102                 ret = MPATH_PR_SUCCESS;
2103                 goto out;
2104         }
2105         prkey = 0;
2106         keyp = (unsigned char *)mpp->reservation_key;
2107         for (j = 0; j < 8; ++j) {
2108                 if (j > 0)
2109                         prkey <<= 8;
2110                 prkey |= *keyp;
2111                 ++keyp;
2112         }
2113         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ", prkey);
2114
2115         isFound =0;
2116         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
2117         {
2118                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
2119                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
2120                 if (!memcmp(mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
2121                 {
2122                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
2123                         isFound =1;
2124                         break;
2125                 }
2126         }
2127         if (!isFound)
2128         {
2129                 condlog(0, "%s: Either device not registered or ", pp->dev);
2130                 condlog(0, "host is not authorised for registration. Skip path");
2131                 ret = MPATH_PR_OTHER;
2132                 goto out;
2133         }
2134
2135         param= malloc(sizeof(struct prout_param_descriptor));
2136         memset(param, 0 , sizeof(struct prout_param_descriptor));
2137
2138         for (j = 7; j >= 0; --j) {
2139                 param->sa_key[j] = (prkey & 0xff);
2140                 prkey >>= 8;
2141         }
2142         param->num_transportid = 0;
2143
2144         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
2145
2146         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
2147         if (ret != MPATH_PR_SUCCESS )
2148         {
2149                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
2150         }
2151         mpp->prflag = 1;
2152
2153         free(param);
2154 out:
2155         free(resp);
2156         return NULL;
2157 }
2158
2159 int mpath_pr_event_handle(struct path *pp)
2160 {
2161         pthread_t thread;
2162         int rc;
2163         pthread_attr_t attr;
2164         struct multipath * mpp;
2165
2166         mpp = pp->mpp;
2167
2168         if (!mpp->reservation_key)
2169                 return -1;
2170
2171         pthread_attr_init(&attr);
2172         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
2173
2174         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
2175         if (rc) {
2176                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
2177                 return -1;
2178         }
2179         pthread_attr_destroy(&attr);
2180         rc = pthread_join(thread, NULL);
2181         return 0;
2182 }
2183