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