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