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