395307e3e382d2593ab7dafb73c19d5ec6458bde
[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         lock(vecs->lock);
1393         /*
1394          * free old map and path vectors ... they use old conf state
1395          */
1396         if (VECTOR_SIZE(vecs->mpvec))
1397                 remove_maps_and_stop_waiters(vecs);
1398
1399         if (VECTOR_SIZE(vecs->pathvec))
1400                 free_pathvec(vecs->pathvec, FREE_PATHS);
1401
1402         vecs->pathvec = NULL;
1403         conf = NULL;
1404
1405         if (!load_config(DEFAULT_CONFIGFILE)) {
1406                 conf->verbosity = old->verbosity;
1407                 conf->daemon = 1;
1408                 configure(vecs, 1);
1409                 free_config(old);
1410                 retval = 0;
1411         }
1412
1413         unlock(vecs->lock);
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 static void
1464 sighup (int sig)
1465 {
1466         condlog(2, "reconfigure (SIGHUP)");
1467
1468         if (running_state != DAEMON_RUNNING)
1469                 return;
1470
1471         reconfigure(gvecs);
1472
1473 #ifdef _DEBUG_
1474         dbg_free_final(NULL);
1475 #endif
1476 }
1477
1478 static void
1479 sigend (int sig)
1480 {
1481         exit_daemon(0);
1482 }
1483
1484 static void
1485 sigusr1 (int sig)
1486 {
1487         condlog(3, "SIGUSR1 received");
1488 }
1489
1490 static void
1491 signal_init(void)
1492 {
1493         signal_set(SIGHUP, sighup);
1494         signal_set(SIGUSR1, sigusr1);
1495         signal_set(SIGINT, sigend);
1496         signal_set(SIGTERM, sigend);
1497         signal(SIGPIPE, SIG_IGN);
1498 }
1499
1500 static void
1501 setscheduler (void)
1502 {
1503         int res;
1504         static struct sched_param sched_param = {
1505                 .sched_priority = 99
1506         };
1507
1508         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1509
1510         if (res == -1)
1511                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1512         return;
1513 }
1514
1515 static void
1516 set_oom_adj (void)
1517 {
1518 #ifdef OOM_SCORE_ADJ_MIN
1519         int retry = 1;
1520         char *file = "/proc/self/oom_score_adj";
1521         int score = OOM_SCORE_ADJ_MIN;
1522 #else
1523         int retry = 0;
1524         char *file = "/proc/self/oom_adj";
1525         int score = OOM_ADJUST_MIN;
1526 #endif
1527         FILE *fp;
1528         struct stat st;
1529
1530         do {
1531                 if (stat(file, &st) == 0){
1532                         fp = fopen(file, "w");
1533                         if (!fp) {
1534                                 condlog(0, "couldn't fopen %s : %s", file,
1535                                         strerror(errno));
1536                                 return;
1537                         }
1538                         fprintf(fp, "%i", score);
1539                         fclose(fp);
1540                         return;
1541                 }
1542                 if (errno != ENOENT) {
1543                         condlog(0, "couldn't stat %s : %s", file,
1544                                 strerror(errno));
1545                         return;
1546                 }
1547                 file = "/proc/self/oom_adj";
1548                 score = OOM_ADJUST_MIN;
1549         } while (retry--);
1550         condlog(0, "couldn't adjust oom score");
1551 }
1552
1553 static int
1554 child (void * param)
1555 {
1556         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1557         pthread_attr_t log_attr, misc_attr;
1558         struct vectors * vecs;
1559         struct multipath * mpp;
1560         int i;
1561         sigset_t set;
1562         int rc, pid_rc;
1563
1564         mlockall(MCL_CURRENT | MCL_FUTURE);
1565
1566         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1567         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1568
1569         if (logsink) {
1570                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1571                 log_thread_start(&log_attr);
1572                 pthread_attr_destroy(&log_attr);
1573         }
1574
1575         running_state = DAEMON_START;
1576
1577         condlog(2, "--------start up--------");
1578         condlog(2, "read " DEFAULT_CONFIGFILE);
1579
1580         if (load_config(DEFAULT_CONFIGFILE))
1581                 exit(1);
1582
1583         if (init_checkers()) {
1584                 condlog(0, "failed to initialize checkers");
1585                 exit(1);
1586         }
1587         if (init_prio()) {
1588                 condlog(0, "failed to initialize prioritizers");
1589                 exit(1);
1590         }
1591
1592         setlogmask(LOG_UPTO(conf->verbosity + 3));
1593
1594         if (conf->max_fds) {
1595                 struct rlimit fd_limit;
1596
1597                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1598                         condlog(0, "can't get open fds limit: %s",
1599                                 strerror(errno));
1600                         fd_limit.rlim_cur = 0;
1601                         fd_limit.rlim_max = 0;
1602                 }
1603                 if (fd_limit.rlim_cur < conf->max_fds) {
1604                         fd_limit.rlim_cur = conf->max_fds;
1605                         if (fd_limit.rlim_max < conf->max_fds)
1606                                 fd_limit.rlim_max = conf->max_fds;
1607                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1608                                 condlog(0, "can't set open fds limit to "
1609                                         "%lu/%lu : %s",
1610                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1611                                         strerror(errno));
1612                         } else {
1613                                 condlog(3, "set open fds limit to %lu/%lu",
1614                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1615                         }
1616                 }
1617
1618         }
1619
1620         vecs = gvecs = init_vecs();
1621         if (!vecs)
1622                 exit(1);
1623
1624         signal_init();
1625         setscheduler();
1626         set_oom_adj();
1627
1628         conf->daemon = 1;
1629         udev_set_sync_support(0);
1630         /*
1631          * Start uevent listener early to catch events
1632          */
1633         if ((rc = pthread_create(&uevent_thr, &misc_attr, ueventloop, vecs))) {
1634                 condlog(0, "failed to create uevent thread: %d", rc);
1635                 exit(1);
1636         }
1637         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1638                 condlog(0, "failed to create cli listener: %d", rc);
1639                 exit(1);
1640         }
1641         /*
1642          * fetch and configure both paths and multipaths
1643          */
1644         lock(vecs->lock);
1645         running_state = DAEMON_CONFIGURE;
1646
1647         if (configure(vecs, 1)) {
1648                 unlock(vecs->lock);
1649                 condlog(0, "failure during configuration");
1650                 exit(1);
1651         }
1652         unlock(vecs->lock);
1653
1654         /*
1655          * start threads
1656          */
1657         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1658                 condlog(0,"failed to create checker loop thread: %d", rc);
1659                 exit(1);
1660         }
1661         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1662                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1663                 exit(1);
1664         }
1665         pthread_attr_destroy(&misc_attr);
1666
1667         pthread_mutex_lock(&exit_mutex);
1668         /* Startup complete, create logfile */
1669         pid_rc = pidfile_create(DEFAULT_PIDFILE, daemon_pid);
1670         /* Ignore errors, we can live without */
1671
1672         running_state = DAEMON_RUNNING;
1673         pthread_cond_wait(&exit_cond, &exit_mutex);
1674         /* Need to block these to avoid deadlocking */
1675         sigemptyset(&set);
1676         sigaddset(&set, SIGTERM);
1677         sigaddset(&set, SIGINT);
1678         pthread_sigmask(SIG_BLOCK, &set, NULL);
1679
1680         /*
1681          * exit path
1682          */
1683         running_state = DAEMON_SHUTDOWN;
1684         pthread_sigmask(SIG_UNBLOCK, &set, NULL);
1685         block_signal(SIGHUP, NULL);
1686         lock(vecs->lock);
1687         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1688                 vector_foreach_slot(vecs->mpvec, mpp, i)
1689                         dm_queue_if_no_path(mpp->alias, 0);
1690         remove_maps_and_stop_waiters(vecs);
1691         unlock(vecs->lock);
1692
1693         pthread_cancel(check_thr);
1694         pthread_cancel(uevent_thr);
1695         pthread_cancel(uxlsnr_thr);
1696         pthread_cancel(uevq_thr);
1697
1698         lock(vecs->lock);
1699         free_pathvec(vecs->pathvec, FREE_PATHS);
1700         vecs->pathvec = NULL;
1701         unlock(vecs->lock);
1702         /* Now all the waitevent threads will start rushing in. */
1703         while (vecs->lock.depth > 0) {
1704                 sleep (1); /* This is weak. */
1705                 condlog(3, "Have %d wait event checkers threads to de-alloc,"
1706                         " waiting...", vecs->lock.depth);
1707         }
1708         pthread_mutex_destroy(vecs->lock.mutex);
1709         FREE(vecs->lock.mutex);
1710         vecs->lock.depth = 0;
1711         vecs->lock.mutex = NULL;
1712         FREE(vecs);
1713         vecs = NULL;
1714
1715         cleanup_checkers();
1716         cleanup_prio();
1717
1718         dm_lib_release();
1719         dm_lib_exit();
1720
1721         /* We're done here */
1722         if (!pid_rc) {
1723                 condlog(3, "unlink pidfile");
1724                 unlink(DEFAULT_PIDFILE);
1725         }
1726
1727         condlog(2, "--------shut down-------");
1728
1729         if (logsink)
1730                 log_thread_stop();
1731
1732         /*
1733          * Freeing config must be done after condlog() and dm_lib_exit(),
1734          * because logging functions like dlog() and dm_write_log()
1735          * reference the config.
1736          */
1737         free_config(conf);
1738         conf = NULL;
1739
1740 #ifdef _DEBUG_
1741         dbg_free_final(NULL);
1742 #endif
1743
1744         exit(0);
1745 }
1746
1747 static int
1748 daemonize(void)
1749 {
1750         int pid;
1751         int dev_null_fd;
1752
1753         if( (pid = fork()) < 0){
1754                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1755                 return -1;
1756         }
1757         else if (pid != 0)
1758                 return pid;
1759
1760         setsid();
1761
1762         if ( (pid = fork()) < 0)
1763                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1764         else if (pid != 0)
1765                 _exit(0);
1766
1767         if (chdir("/") < 0)
1768                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1769
1770         dev_null_fd = open("/dev/null", O_RDWR);
1771         if (dev_null_fd < 0){
1772                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
1773                         strerror(errno));
1774                 _exit(0);
1775         }
1776
1777         close(STDIN_FILENO);
1778         if (dup(dev_null_fd) < 0) {
1779                 fprintf(stderr, "cannot dup /dev/null to stdin : %s\n",
1780                         strerror(errno));
1781                 _exit(0);
1782         }
1783         close(STDOUT_FILENO);
1784         if (dup(dev_null_fd) < 0) {
1785                 fprintf(stderr, "cannot dup /dev/null to stdout : %s\n",
1786                         strerror(errno));
1787                 _exit(0);
1788         }
1789         close(STDERR_FILENO);
1790         if (dup(dev_null_fd) < 0) {
1791                 fprintf(stderr, "cannot dup /dev/null to stderr : %s\n",
1792                         strerror(errno));
1793                 _exit(0);
1794         }
1795         close(dev_null_fd);
1796         daemon_pid = getpid();
1797         return 0;
1798 }
1799
1800 int
1801 main (int argc, char *argv[])
1802 {
1803         extern char *optarg;
1804         extern int optind;
1805         int arg;
1806         int err;
1807
1808         logsink = 1;
1809         running_state = DAEMON_INIT;
1810         dm_init();
1811
1812         if (getuid() != 0) {
1813                 fprintf(stderr, "need to be root\n");
1814                 exit(1);
1815         }
1816
1817         /* make sure we don't lock any path */
1818         if (chdir("/") < 0)
1819                 fprintf(stderr, "can't chdir to root directory : %s\n",
1820                         strerror(errno));
1821         umask(umask(077) | 022);
1822
1823         conf = alloc_config();
1824
1825         if (!conf)
1826                 exit(1);
1827
1828         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1829         switch(arg) {
1830                 case 'd':
1831                         logsink = 0;
1832                         //debug=1; /* ### comment me out ### */
1833                         break;
1834                 case 'v':
1835                         if (sizeof(optarg) > sizeof(char *) ||
1836                             !isdigit(optarg[0]))
1837                                 exit(1);
1838
1839                         conf->verbosity = atoi(optarg);
1840                         break;
1841                 case 'k':
1842                         uxclnt(optarg);
1843                         exit(0);
1844                 default:
1845                         ;
1846                 }
1847         }
1848         if (optind < argc) {
1849                 char cmd[CMDSIZE];
1850                 char * s = cmd;
1851                 char * c = s;
1852
1853                 while (optind < argc) {
1854                         if (strchr(argv[optind], ' '))
1855                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1856                         else
1857                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1858                         optind++;
1859                 }
1860                 c += snprintf(c, s + CMDSIZE - c, "\n");
1861                 uxclnt(s);
1862                 exit(0);
1863         }
1864
1865         if (!logsink)
1866                 err = 0;
1867         else
1868                 err = daemonize();
1869
1870         if (err < 0)
1871                 /* error */
1872                 exit(1);
1873         else if (err > 0)
1874                 /* parent dies */
1875                 exit(0);
1876         else
1877                 /* child lives */
1878                 return (child(NULL));
1879 }
1880
1881 void *  mpath_pr_event_handler_fn (void * pathp )
1882 {
1883         struct multipath * mpp;
1884         int i,j, ret, isFound;
1885         struct path * pp = (struct path *)pathp;
1886         unsigned char *keyp;
1887         uint64_t prkey;
1888         struct prout_param_descriptor *param;
1889         struct prin_resp *resp;
1890
1891         mpp = pp->mpp;
1892
1893         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
1894         if (!resp){
1895                 condlog(0,"%s Alloc failed for prin response", pp->dev);
1896                 return NULL;
1897         }
1898
1899         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
1900         if (ret != MPATH_PR_SUCCESS )
1901         {
1902                 condlog(0,"%s : pr in read keys service action failed. Error=%d", pp->dev, ret);
1903                 goto out;
1904         }
1905
1906         condlog(3, " event pr=%d addlen=%d",resp->prin_descriptor.prin_readkeys.prgeneration,
1907                         resp->prin_descriptor.prin_readkeys.additional_length );
1908
1909         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
1910         {
1911                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
1912                 ret = MPATH_PR_SUCCESS;
1913                 goto out;
1914         }
1915         prkey = 0;
1916         keyp = (unsigned char *)mpp->reservation_key;
1917         for (j = 0; j < 8; ++j) {
1918                 if (j > 0)
1919                         prkey <<= 8;
1920                 prkey |= *keyp;
1921                 ++keyp;
1922         }
1923         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ", prkey);
1924
1925         isFound =0;
1926         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
1927         {
1928                 condlog(2, "PR IN READKEYS[%d]  reservation key:",i);
1929                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
1930                 if (!memcmp(mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
1931                 {
1932                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
1933                         isFound =1;
1934                         break;
1935                 }
1936         }
1937         if (!isFound)
1938         {
1939                 condlog(0, "%s: Either device not registered or ", pp->dev);
1940                 condlog(0, "host is not authorised for registration. Skip path");
1941                 ret = MPATH_PR_OTHER;
1942                 goto out;
1943         }
1944
1945         param= malloc(sizeof(struct prout_param_descriptor));
1946         memset(param, 0 , sizeof(struct prout_param_descriptor));
1947
1948         for (j = 7; j >= 0; --j) {
1949                 param->sa_key[j] = (prkey & 0xff);
1950                 prkey >>= 8;
1951         }
1952         param->num_transportid = 0;
1953
1954         condlog(3, "device %s:%s", pp->dev, pp->mpp->wwid);
1955
1956         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
1957         if (ret != MPATH_PR_SUCCESS )
1958         {
1959                 condlog(0,"%s: Reservation registration failed. Error: %d", pp->dev, ret);
1960         }
1961         mpp->prflag = 1;
1962
1963         free(param);
1964 out:
1965         free(resp);
1966         return NULL;
1967 }
1968
1969 int mpath_pr_event_handle(struct path *pp)
1970 {
1971         pthread_t thread;
1972         int rc;
1973         pthread_attr_t attr;
1974         struct multipath * mpp;
1975
1976         mpp = pp->mpp;
1977
1978         if (!mpp->reservation_key)
1979                 return -1;
1980
1981         pthread_attr_init(&attr);
1982         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1983
1984         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
1985         if (rc) {
1986                 condlog(0, "%s: ERROR; return code from pthread_create() is %d", pp->dev, rc);
1987                 return -1;
1988         }
1989         pthread_attr_destroy(&attr);
1990         rc = pthread_join(thread, NULL);
1991         return 0;
1992 }
1993