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