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