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