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