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