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