Always synchronize with dm state
[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         /*
1032          * Synchronize with kernel state
1033          */
1034         if (update_multipath_strings(pp->mpp, vecs->pathvec)) {
1035                 condlog(1, "%s: Could not synchronize with kernel state\n",
1036                         pp->dev);
1037                 pp->dmstate = PSTATE_UNDEF;
1038         }
1039         if (newstate != pp->state) {
1040                 int oldstate = pp->state;
1041                 pp->state = newstate;
1042                 LOG_MSG(1, checker_message(&pp->checker));
1043
1044                 /*
1045                  * upon state change, reset the checkint
1046                  * to the shortest delay
1047                  */
1048                 pp->checkint = conf->checkint;
1049
1050                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY) {
1051                         /*
1052                          * proactively fail path in the DM
1053                          */
1054                         if (oldstate == PATH_UP ||
1055                             oldstate == PATH_GHOST)
1056                                 fail_path(pp, 1);
1057                         else
1058                                 fail_path(pp, 0);
1059
1060                         /*
1061                          * cancel scheduled failback
1062                          */
1063                         pp->mpp->failback_tick = 0;
1064
1065                         pp->mpp->stat_path_failures++;
1066                         return;
1067                 }
1068
1069                 /*
1070                  * reinstate this path
1071                  */
1072                 if (oldstate != PATH_UP &&
1073                     oldstate != PATH_GHOST)
1074                         reinstate_path(pp, 1);
1075                 else
1076                         reinstate_path(pp, 0);
1077
1078                 new_path_up = 1;
1079
1080                 /*
1081                  * if at least one path is up in a group, and
1082                  * the group is disabled, re-enable it
1083                  */
1084                 if (newstate == PATH_UP)
1085                         enable_group(pp);
1086         }
1087         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1088                 if (pp->dmstate == PSTATE_FAILED ||
1089                     pp->dmstate == PSTATE_UNDEF) {
1090                         /* Clear IO errors */
1091                         reinstate_path(pp, 0);
1092                 } else {
1093                         LOG_MSG(4, checker_message(&pp->checker));
1094                         /*
1095                          * double the next check delay.
1096                          * max at conf->max_checkint
1097                          */
1098                         if (pp->checkint < (conf->max_checkint / 2))
1099                                 pp->checkint = 2 * pp->checkint;
1100                         else
1101                                 pp->checkint = conf->max_checkint;
1102
1103                         pp->tick = pp->checkint;
1104                         condlog(4, "%s: delay next check %is",
1105                                 pp->dev_t, pp->tick);
1106                 }
1107         }
1108         else if (newstate == PATH_DOWN)
1109                 LOG_MSG(2, checker_message(&pp->checker));
1110
1111         pp->state = newstate;
1112
1113         /*
1114          * path prio refreshing
1115          */
1116         condlog(4, "path prio refresh");
1117
1118         if (update_prio(pp, new_path_up) &&
1119             pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio)
1120                 update_path_groups(pp->mpp, vecs, !new_path_up);
1121         else if (need_switch_pathgroup(pp->mpp, 0)) {
1122                 if (pp->mpp->pgfailback > 0 &&
1123                     (new_path_up || pp->mpp->failback_tick <= 0))
1124                         pp->mpp->failback_tick =
1125                                 pp->mpp->pgfailback + 1;
1126                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1127                         switch_pathgroup(pp->mpp);
1128         }
1129 }
1130
1131 static void *
1132 checkerloop (void *ap)
1133 {
1134         struct vectors *vecs;
1135         struct path *pp;
1136         int count = 0;
1137         unsigned int i;
1138         sigset_t old;
1139
1140         mlockall(MCL_CURRENT | MCL_FUTURE);
1141         vecs = (struct vectors *)ap;
1142         condlog(2, "path checkers start up");
1143
1144         /*
1145          * init the path check interval
1146          */
1147         vector_foreach_slot (vecs->pathvec, pp, i) {
1148                 pp->checkint = conf->checkint;
1149         }
1150
1151         while (1) {
1152                 block_signal(SIGHUP, &old);
1153                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1154                 lock(vecs->lock);
1155                 condlog(4, "tick");
1156
1157                 if (vecs->pathvec) {
1158                         vector_foreach_slot (vecs->pathvec, pp, i) {
1159                                 check_path(vecs, pp);
1160                         }
1161                 }
1162                 if (vecs->mpvec) {
1163                         defered_failback_tick(vecs->mpvec);
1164                         retry_count_tick(vecs->mpvec);
1165                 }
1166                 if (count)
1167                         count--;
1168                 else {
1169                         condlog(4, "map garbage collection");
1170                         mpvec_garbage_collector(vecs);
1171                         count = MAPGCINT;
1172                 }
1173
1174                 lock_cleanup_pop(vecs->lock);
1175                 pthread_sigmask(SIG_SETMASK, &old, NULL);
1176                 sleep(1);
1177         }
1178         return NULL;
1179 }
1180
1181 int
1182 configure (struct vectors * vecs, int start_waiters)
1183 {
1184         struct multipath * mpp;
1185         struct path * pp;
1186         vector mpvec;
1187         int i;
1188
1189         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1190                 return 1;
1191
1192         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1193                 return 1;
1194
1195         if (!(mpvec = vector_alloc()))
1196                 return 1;
1197
1198         /*
1199          * probe for current path (from sysfs) and map (from dm) sets
1200          */
1201         path_discovery(vecs->pathvec, conf, DI_ALL);
1202
1203         vector_foreach_slot (vecs->pathvec, pp, i){
1204                 if (filter_path(conf, pp) > 0){
1205                         vector_del_slot(vecs->pathvec, i);
1206                         free_path(pp);
1207                         i--;
1208                 }
1209                 else
1210                         pp->checkint = conf->checkint;
1211         }
1212         if (map_discovery(vecs))
1213                 return 1;
1214
1215         /*
1216          * create new set of maps & push changed ones into dm
1217          */
1218         if (coalesce_paths(vecs, mpvec, NULL, 1))
1219                 return 1;
1220
1221         /*
1222          * may need to remove some maps which are no longer relevant
1223          * e.g., due to blacklist changes in conf file
1224          */
1225         if (coalesce_maps(vecs, mpvec))
1226                 return 1;
1227
1228         dm_lib_release();
1229
1230         sync_maps_state(mpvec);
1231
1232         /*
1233          * purge dm of old maps
1234          */
1235         remove_maps(vecs);
1236
1237         /*
1238          * save new set of maps formed by considering current path state
1239          */
1240         vector_free(vecs->mpvec);
1241         vecs->mpvec = mpvec;
1242
1243         /*
1244          * start dm event waiter threads for these new maps
1245          */
1246         vector_foreach_slot(vecs->mpvec, mpp, i) {
1247                 if (setup_multipath(vecs, mpp))
1248                         return 1;
1249                 if (start_waiters)
1250                         if (start_waiter_thread(mpp, vecs))
1251                                 return 1;
1252         }
1253         return 0;
1254 }
1255
1256 int
1257 reconfigure (struct vectors * vecs)
1258 {
1259         struct config * old = conf;
1260
1261         /*
1262          * free old map and path vectors ... they use old conf state
1263          */
1264         if (VECTOR_SIZE(vecs->mpvec))
1265                 remove_maps_and_stop_waiters(vecs);
1266
1267         if (VECTOR_SIZE(vecs->pathvec))
1268                 free_pathvec(vecs->pathvec, FREE_PATHS);
1269
1270         vecs->pathvec = NULL;
1271         conf = NULL;
1272
1273         if (load_config(DEFAULT_CONFIGFILE))
1274                 return 1;
1275
1276         conf->verbosity = old->verbosity;
1277
1278         if (!conf->checkint) {
1279                 conf->checkint = DEFAULT_CHECKINT;
1280                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1281         }
1282         conf->daemon = 1;
1283         configure(vecs, 1);
1284         free_config(old);
1285         return 0;
1286 }
1287
1288 static struct vectors *
1289 init_vecs (void)
1290 {
1291         struct vectors * vecs;
1292
1293         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1294
1295         if (!vecs)
1296                 return NULL;
1297
1298         vecs->lock.mutex =
1299                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1300
1301         if (!vecs->lock.mutex)
1302                 goto out;
1303
1304         pthread_mutex_init(vecs->lock.mutex, NULL);
1305         vecs->lock.depth = 0;
1306
1307         return vecs;
1308
1309 out:
1310         FREE(vecs);
1311         condlog(0, "failed to init paths");
1312         return NULL;
1313 }
1314
1315 static void *
1316 signal_set(int signo, void (*func) (int))
1317 {
1318         int r;
1319         struct sigaction sig;
1320         struct sigaction osig;
1321
1322         sig.sa_handler = func;
1323         sigemptyset(&sig.sa_mask);
1324         sig.sa_flags = 0;
1325
1326         r = sigaction(signo, &sig, &osig);
1327
1328         if (r < 0)
1329                 return (SIG_ERR);
1330         else
1331                 return (osig.sa_handler);
1332 }
1333
1334 static void
1335 sighup (int sig)
1336 {
1337         condlog(2, "reconfigure (SIGHUP)");
1338
1339         lock(gvecs->lock);
1340         reconfigure(gvecs);
1341         unlock(gvecs->lock);
1342
1343 #ifdef _DEBUG_
1344         dbg_free_final(NULL);
1345 #endif
1346 }
1347
1348 static void
1349 sigend (int sig)
1350 {
1351         exit_daemon(0);
1352 }
1353
1354 static void
1355 sigusr1 (int sig)
1356 {
1357         condlog(3, "SIGUSR1 received");
1358 }
1359
1360 static void
1361 signal_init(void)
1362 {
1363         signal_set(SIGHUP, sighup);
1364         signal_set(SIGUSR1, sigusr1);
1365         signal_set(SIGINT, sigend);
1366         signal_set(SIGTERM, sigend);
1367         signal(SIGPIPE, SIG_IGN);
1368 }
1369
1370 static void
1371 setscheduler (void)
1372 {
1373         int res;
1374         static struct sched_param sched_param = {
1375                 .sched_priority = 99
1376         };
1377
1378         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1379
1380         if (res == -1)
1381                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1382         return;
1383 }
1384
1385 static void
1386 set_oom_adj (int val)
1387 {
1388         FILE *fp;
1389
1390         fp = fopen("/proc/self/oom_adj", "w");
1391
1392         if (!fp)
1393                 return;
1394
1395         fprintf(fp, "%i", val);
1396         fclose(fp);
1397 }
1398
1399 static int
1400 child (void * param)
1401 {
1402         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1403         pthread_attr_t log_attr, misc_attr;
1404         struct vectors * vecs;
1405         struct multipath * mpp;
1406         int i;
1407         int rc;
1408
1409         mlockall(MCL_CURRENT | MCL_FUTURE);
1410
1411         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1412         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1413
1414         if (logsink) {
1415                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1416                 log_thread_start(&log_attr);
1417                 pthread_attr_destroy(&log_attr);
1418         }
1419
1420         condlog(2, "--------start up--------");
1421         condlog(2, "read " DEFAULT_CONFIGFILE);
1422
1423         if (load_config(DEFAULT_CONFIGFILE))
1424                 exit(1);
1425
1426         if (init_checkers()) {
1427                 condlog(0, "failed to initialize checkers");
1428                 exit(1);
1429         }
1430         if (init_prio()) {
1431                 condlog(0, "failed to initialize prioritizers");
1432                 exit(1);
1433         }
1434
1435         setlogmask(LOG_UPTO(conf->verbosity + 3));
1436
1437         /*
1438          * fill the voids left in the config file
1439          */
1440         if (!conf->checkint) {
1441                 conf->checkint = DEFAULT_CHECKINT;
1442                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1443         }
1444
1445         if (conf->max_fds) {
1446                 struct rlimit fd_limit;
1447
1448                 fd_limit.rlim_cur = conf->max_fds;
1449                 fd_limit.rlim_max = conf->max_fds;
1450                 if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0)
1451                         condlog(0, "can't set open fds limit to %d : %s\n",
1452                                 conf->max_fds, strerror(errno));
1453         }
1454
1455         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1456                 if (logsink)
1457                         log_thread_stop();
1458
1459                 exit(1);
1460         }
1461         signal_init();
1462         setscheduler();
1463         set_oom_adj(-16);
1464         vecs = gvecs = init_vecs();
1465
1466         if (!vecs)
1467                 exit(1);
1468
1469         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1470                 condlog(0, "can not find sysfs mount point");
1471                 exit(1);
1472         }
1473         conf->daemon = 1;
1474         udev_set_sync_support(0);
1475         /*
1476          * Start uevent listener early to catch events
1477          */
1478         if ((rc = pthread_create(&uevent_thr, &misc_attr, ueventloop, vecs))) {
1479                 condlog(0, "failed to create uevent thread: %d", rc);
1480                 exit(1);
1481         }
1482         /*
1483          * fetch and configure both paths and multipaths
1484          */
1485         lock(vecs->lock);
1486         if (configure(vecs, 1)) {
1487                 unlock(vecs->lock);
1488                 condlog(0, "failure during configuration");
1489                 exit(1);
1490         }
1491         unlock(vecs->lock);
1492
1493         /*
1494          * start threads
1495          */
1496         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1497                 condlog(0,"failed to create checker loop thread: %d", rc);
1498                 exit(1);
1499         }
1500         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1501                 condlog(0, "failed to create cli listener: %d", rc);
1502                 exit(1);
1503         }
1504         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1505                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1506                 exit(1);
1507         }
1508         pthread_attr_destroy(&misc_attr);
1509
1510         pthread_mutex_lock(&exit_mutex);
1511         pthread_cond_wait(&exit_cond, &exit_mutex);
1512
1513         /*
1514          * exit path
1515          */
1516         block_signal(SIGHUP, NULL);
1517         lock(vecs->lock);
1518         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1519                 vector_foreach_slot(vecs->mpvec, mpp, i)
1520                         dm_queue_if_no_path(mpp->alias, 0);
1521         remove_maps_and_stop_waiters(vecs);
1522         unlock(vecs->lock);
1523
1524         pthread_cancel(check_thr);
1525         pthread_cancel(uevent_thr);
1526         pthread_cancel(uxlsnr_thr);
1527         pthread_cancel(uevq_thr);
1528
1529         sysfs_cleanup();
1530
1531         lock(vecs->lock);
1532         free_pathvec(vecs->pathvec, FREE_PATHS);
1533         vecs->pathvec = NULL;
1534         unlock(vecs->lock);
1535         /* Now all the waitevent threads will start rushing in. */
1536         while (vecs->lock.depth > 0) {
1537                 sleep (1); /* This is weak. */
1538                 condlog(3,"Have %d wait event checkers threads to de-alloc, waiting..\n", vecs->lock.depth);
1539         }
1540         pthread_mutex_destroy(vecs->lock.mutex);
1541         FREE(vecs->lock.mutex);
1542         vecs->lock.depth = 0;
1543         vecs->lock.mutex = NULL;
1544         FREE(vecs);
1545         vecs = NULL;
1546
1547         cleanup_checkers();
1548         cleanup_prio();
1549
1550         condlog(2, "--------shut down-------");
1551
1552         if (logsink)
1553                 log_thread_stop();
1554
1555         dm_lib_release();
1556         dm_lib_exit();
1557
1558         cleanup_prio();
1559         cleanup_checkers();
1560         /*
1561          * Freeing config must be done after condlog() and dm_lib_exit(),
1562          * because logging functions like dlog() and dm_write_log()
1563          * reference the config.
1564          */
1565         free_config(conf);
1566         conf = NULL;
1567
1568 #ifdef _DEBUG_
1569         dbg_free_final(NULL);
1570 #endif
1571
1572         exit(0);
1573 }
1574
1575 static int
1576 daemonize(void)
1577 {
1578         int pid;
1579         int in_fd, out_fd;
1580
1581         if( (pid = fork()) < 0){
1582                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1583                 return -1;
1584         }
1585         else if (pid != 0)
1586                 return pid;
1587
1588         setsid();
1589
1590         if ( (pid = fork()) < 0)
1591                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1592         else if (pid != 0)
1593                 _exit(0);
1594
1595         in_fd = open("/dev/null", O_RDONLY);
1596         if (in_fd < 0){
1597                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1598                         strerror(errno));
1599                 _exit(0);
1600         }
1601         out_fd = open("/dev/console", O_WRONLY);
1602         if (out_fd < 0){
1603                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1604                         strerror(errno));
1605                 _exit(0);
1606         }
1607
1608         close(STDIN_FILENO);
1609         dup(in_fd);
1610         close(STDOUT_FILENO);
1611         dup(out_fd);
1612         close(STDERR_FILENO);
1613         dup(out_fd);
1614
1615         close(in_fd);
1616         close(out_fd);
1617         if (chdir("/") < 0)
1618                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1619
1620         return 0;
1621 }
1622
1623 int
1624 main (int argc, char *argv[])
1625 {
1626         extern char *optarg;
1627         extern int optind;
1628         int arg;
1629         int err;
1630
1631         logsink = 1;
1632         dm_init();
1633
1634         if (getuid() != 0) {
1635                 fprintf(stderr, "need to be root\n");
1636                 exit(1);
1637         }
1638
1639         /* make sure we don't lock any path */
1640         chdir("/");
1641         umask(umask(077) | 022);
1642
1643         conf = alloc_config();
1644
1645         if (!conf)
1646                 exit(1);
1647
1648         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1649         switch(arg) {
1650                 case 'd':
1651                         logsink = 0;
1652                         //debug=1; /* ### comment me out ### */
1653                         break;
1654                 case 'v':
1655                         if (sizeof(optarg) > sizeof(char *) ||
1656                             !isdigit(optarg[0]))
1657                                 exit(1);
1658
1659                         conf->verbosity = atoi(optarg);
1660                         break;
1661                 case 'k':
1662                         uxclnt(optarg);
1663                         exit(0);
1664                 default:
1665                         ;
1666                 }
1667         }
1668         if (optind < argc) {
1669                 char cmd[CMDSIZE];
1670                 char * s = cmd;
1671                 char * c = s;
1672
1673                 while (optind < argc) {
1674                         if (strchr(argv[optind], ' '))
1675                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1676                         else
1677                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1678                         optind++;
1679                 }
1680                 c += snprintf(c, s + CMDSIZE - c, "\n");
1681                 uxclnt(s);
1682                 exit(0);
1683         }
1684
1685         if (!logsink)
1686                 err = 0;
1687         else
1688                 err = daemonize();
1689
1690         if (err < 0)
1691                 /* error */
1692                 exit(1);
1693         else if (err > 0)
1694                 /* parent dies */
1695                 exit(0);
1696         else
1697                 /* child lives */
1698                 return (child(NULL));
1699 }
1700