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