[multipathd] convert another user to find_mp_by_str()
[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         mpp = find_mp_by_str(vecs->mpvec, devname);
617
618         if (!mpp)
619                 return 0;
620
621         update_mpp_paths(mpp, vecs->pathvec);
622         verify_paths(mpp, vecs, NULL);
623
624         if (!VECTOR_SIZE(mpp->paths))
625                 flush_map(mpp, vecs);
626
627         return 0;
628 }
629         
630 static int
631 uev_add_path (char * devname, struct vectors * vecs)
632 {
633         condlog(2, "%s: add path (uevent)", devname);
634         return ev_add_path(devname, vecs);
635 }
636
637 int
638 ev_add_path (char * devname, struct vectors * vecs)
639 {
640         struct multipath * mpp;
641         struct path * pp;
642         char empty_buff[WWID_SIZE] = {0};
643
644         pp = find_path_by_dev(vecs->pathvec, devname);
645
646         if (pp) {
647                 condlog(0, "%s: spurious uevent, path already in pathvec, %p",
648                         devname, pp->mpp);
649                 /*
650                  * allow reconfig of orphaned path here
651                  */
652                 if (pp->mpp) return 1;
653         }
654         else {
655                 /*
656                  * get path vital state
657                  */
658                 if (!(pp = store_pathinfo(vecs->pathvec, conf->hwtable,
659                       devname, DI_ALL))) {
660                         condlog(0, "%s: failed to store path info", devname);
661                         return 1;
662                 }
663                 pp->checkint = conf->checkint;
664         }
665
666         /*
667          * need path UID to go any further
668          */
669         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
670                 condlog(0, "%s: failed to get path uid", devname);
671                 return 1; /* leave path added to pathvec */
672         }
673
674         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
675 rescan:
676         if (mpp) {
677                 if (adopt_paths(vecs->pathvec, mpp))
678                         return 1; /* leave path added to pathvec */
679
680                 verify_paths(mpp, vecs, NULL);
681                 condlog(0, "%s: ownership set to %s", pp->dev_t, mpp->alias);
682                 mpp->action = ACT_RELOAD;
683         }
684         else {
685                 if ((mpp = add_map_with_path(vecs, pp, 1)))
686                         mpp->action = ACT_CREATE;
687                 else
688                         return 1; /* leave path added to pathvec */
689         }
690
691         /*
692          * push the map to the device-mapper
693          */
694         if (setup_map(mpp)) {
695                 condlog(0, "%s: failed to setup map for addition of new "
696                         "path %s", mpp->alias, devname);
697                 goto out;
698         }
699         /*
700          * reload the map for the multipath mapped device
701          */
702         if (domap(mpp) <= 0) {
703                 condlog(0, "%s: failed in domap for addition of new "
704                         "path %s", mpp->alias, devname);
705                 /*
706                  * deal with asynchronous uevents :((
707                  */
708                 if (mpp->action == ACT_RELOAD) {
709                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
710                         sleep(1);
711                         update_mpp_paths(mpp, vecs->pathvec);
712                         goto rescan;
713                 }
714                 else
715                         goto out;
716         }
717         dm_lib_release();
718
719         /*
720          * update our state from kernel regardless of create or reload
721          */
722         if (setup_multipath(vecs, mpp))
723                 goto out;
724
725         if (mpp->action == ACT_CREATE &&
726             start_waiter_thread(mpp, vecs))
727                         goto out;
728
729         condlog(3, "%s path added to devmap %s", devname, mpp->alias);
730         return 0;
731
732 out:
733         remove_map(mpp, vecs, NULL, 1);
734         return 1;
735 }
736
737 static int
738 uev_remove_path (char * devname, struct vectors * vecs)
739 {
740         condlog(2, "%s: remove path (uevent)", devname);
741         return ev_remove_path(devname, vecs);
742 }
743
744 int
745 ev_remove_path (char * devname, struct vectors * vecs)
746 {
747         struct multipath * mpp;
748         struct path * pp;
749         int i;
750         int rm_path = 1;
751
752         pp = find_path_by_dev(vecs->pathvec, devname);
753
754         if (!pp) {
755                 condlog(0, "%s: spurious uevent, path not in pathvec", devname);
756                 return 1;
757         }
758
759         /*
760          * avoid referring to the map of an orphanned path
761          */
762         if ((mpp = pp->mpp)) {
763
764                 /*
765                  * remove the map IFF removing the last path
766                  */
767                 if (pathcount(mpp, PATH_WILD) > 1) {
768                         vector rpvec = vector_alloc();
769
770                         /*
771                          * transform the mp->pg vector of vectors of paths
772                          * into a mp->params string to feed the device-mapper
773                          */
774                         update_mpp_paths(mpp, vecs->pathvec);
775                         if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
776                                 vector_del_slot(mpp->paths, i);
777
778                         if (VECTOR_SIZE(mpp->paths) == 0) {
779                                 char alias[WWID_SIZE];
780
781                                 /*
782                                  * flush_map will fail if the device is open
783                                  */
784                                 strncpy(alias, mpp->alias, WWID_SIZE);
785                                 if (flush_map(mpp, vecs))
786                                         rm_path = 0;
787                                 else
788                                         condlog(3, "%s: removed map after removing"
789                                                 " multiple paths", alias);
790                         }
791                         else {
792                                 if (setup_map(mpp)) {
793                                         condlog(0, "%s: failed to setup map for"
794                                                 " removal of path %s", mpp->alias, devname);
795                                         free_pathvec(rpvec, KEEP_PATHS);
796                                         goto out;
797                                 }
798                                 /*
799                                  * reload the map
800                                  */
801                                 mpp->action = ACT_RELOAD;
802                                 if (domap(mpp) <= 0) {
803                                         condlog(0, "%s: failed in domap for "
804                                                 "removal of path %s",
805                                                 mpp->alias, devname);
806                                         /*
807                                          * Delete path from pathvec so that
808                                          * update_mpp_paths wont find it later
809                                          * when/if another path is removed.
810                                          */
811                                         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
812                                                 vector_del_slot(vecs->pathvec, i);
813                                         free_path(pp);
814                                         return 1;
815                                 }
816                                 /*
817                                  * update our state from kernel
818                                  */
819                                 if (setup_multipath(vecs, mpp)) {
820                                         free_pathvec(rpvec, KEEP_PATHS);
821                                         goto out;
822                                 }
823
824                                 condlog(3, "%s path removed from devmap %s",
825                                         devname, mpp->alias);
826                         }
827                         free_pathvec(rpvec, KEEP_PATHS);
828                 }
829                 else {
830                         char alias[WWID_SIZE];
831
832                         /*
833                          * flush_map will fail if the device is open
834                          */
835                         strncpy(alias, mpp->alias, WWID_SIZE);
836                         if (flush_map(mpp, vecs))
837                                 rm_path = 0;
838                         else
839                                 condlog(3, "%s: removed map", alias);
840                 }
841         }
842
843         if (rm_path) {
844                 if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
845                         vector_del_slot(vecs->pathvec, i);
846                 free_path(pp);
847         }
848
849         return 0;
850
851 out:
852         remove_map(mpp, vecs, stop_waiter_thread, 1);
853         return 1;
854 }
855
856 static int
857 map_discovery (struct vectors * vecs)
858 {
859         int i;
860         struct multipath * mpp;
861
862         if (dm_get_maps(vecs->mpvec, "multipath"))
863                 return 1;
864
865         vector_foreach_slot (vecs->mpvec, mpp, i)
866                 if (setup_multipath(vecs, mpp))
867                         return 1;
868
869         return 0;
870 }
871
872 int
873 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
874 {
875         struct vectors * vecs;
876         int r;
877         
878         *reply = NULL;
879         *len = 0;
880         vecs = (struct vectors *)trigger_data;
881
882         pthread_cleanup_push(cleanup_lock, vecs->lock);
883         lock(vecs->lock);
884
885         r = parse_cmd(str, reply, len, vecs);
886
887         if (r > 0) {
888                 *reply = STRDUP("fail\n");
889                 *len = strlen(*reply) + 1;
890                 r = 1;
891         }
892         else if (!r && *len == 0) {
893                 *reply = STRDUP("ok\n");
894                 *len = strlen(*reply) + 1;
895                 r = 0;
896         }
897         /* else if (r < 0) leave *reply alone */
898
899         lock_cleanup_pop(vecs->lock);
900         return r;
901 }
902
903 static int
904 uev_discard(char * devpath)
905 {
906         char a[10], b[10];
907
908         /*
909          * keep only block devices, discard partitions
910          */
911         if (sscanf(devpath, "/block/%10s", a) != 1 ||
912             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
913                 condlog(4, "discard event on %s", devpath);
914                 return 1;
915         }
916         return 0;
917 }
918
919 int 
920 uev_trigger (struct uevent * uev, void * trigger_data)
921 {
922         int r = 0;
923         char devname[32];
924         struct vectors * vecs;
925
926         vecs = (struct vectors *)trigger_data;
927
928         if (uev_discard(uev->devpath))
929                 return 0;
930
931         basename(uev->devpath, devname);
932         lock(vecs->lock);
933
934         /*
935          * device map add/remove event
936          */
937         if (!strncmp(devname, "dm-", 3)) {
938                 if (!strncmp(uev->action, "add", 3)) {
939                         r = uev_add_map(devname, vecs);
940                         goto out;
941                 }
942                 if (!strncmp(uev->action, "remove", 6)) {
943                         r = uev_remove_map(devname, vecs);
944                         goto out;
945                 }
946                 if (!strncmp(uev->action, "umount", 6)) {
947                         r = uev_umount_map(devname, vecs);
948                         goto out;
949                 }
950                 goto out;
951         }
952         
953         /*
954          * path add/remove event
955          */
956         if (blacklist(conf->blist, devname))
957                 goto out;
958
959         if (!strncmp(uev->action, "add", 3)) {
960                 r = uev_add_path(devname, vecs);
961                 goto out;
962         }
963         if (!strncmp(uev->action, "remove", 6)) {
964                 r = uev_remove_path(devname, vecs);
965                 goto out;
966         }
967
968 out:
969         unlock(vecs->lock);
970         return r;
971 }
972
973 static void *
974 ueventloop (void * ap)
975 {
976         if (uevent_listen(&uev_trigger, ap))
977                 fprintf(stderr, "error starting uevent listener");
978                 
979         return NULL;
980 }
981
982 static void *
983 uxlsnrloop (void * ap)
984 {
985         if (load_keys())
986                 return NULL;
987         
988         if (alloc_handlers())
989                 return NULL;
990
991         add_handler(LIST+PATHS, cli_list_paths);
992         add_handler(LIST+MAPS, cli_list_maps);
993         add_handler(LIST+MAPS+STATS, cli_list_maps_stats);
994         add_handler(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
995         add_handler(LIST+MAP+TOPOLOGY, cli_list_map_topology);
996         add_handler(ADD+PATH, cli_add_path);
997         add_handler(DEL+PATH, cli_del_path);
998         add_handler(ADD+MAP, cli_add_map);
999         add_handler(DEL+MAP, cli_del_map);
1000         add_handler(SWITCH+MAP+GROUP, cli_switch_group);
1001         add_handler(RECONFIGURE, cli_reconfigure);
1002         add_handler(SUSPEND+MAP, cli_suspend);
1003         add_handler(RESUME+MAP, cli_resume);
1004         add_handler(REINSTATE+PATH, cli_reinstate);
1005         add_handler(FAIL+PATH, cli_fail);
1006
1007         uxsock_listen(&uxsock_trigger, ap);
1008
1009         return NULL;
1010 }
1011
1012 static int
1013 exit_daemon (int status)
1014 {
1015         if (status != 0)
1016                 fprintf(stderr, "bad exit status. see daemon.log\n");
1017
1018         condlog(3, "unlink pidfile");
1019         unlink(DEFAULT_PIDFILE);
1020
1021         lock(&exit_mutex);
1022         pthread_cond_signal(&exit_cond);
1023         unlock(&exit_mutex);
1024
1025         return status;
1026 }
1027
1028 static void
1029 fail_path (struct path * pp)
1030 {
1031         if (!pp->mpp)
1032                 return;
1033
1034         condlog(2, "checker failed path %s in map %s",
1035                  pp->dev_t, pp->mpp->alias);
1036
1037         dm_fail_path(pp->mpp->alias, pp->dev_t);
1038         update_queue_mode_del_path(pp->mpp);
1039 }
1040
1041 /*
1042  * caller must have locked the path list before calling that function
1043  */
1044 static void
1045 reinstate_path (struct path * pp)
1046 {
1047         if (!pp->mpp)
1048                 return;
1049
1050         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
1051                 condlog(0, "%s: reinstate failed", pp->dev_t);
1052         else {
1053                 condlog(2, "%s: reinstated", pp->dev_t);
1054                 update_queue_mode_add_path(pp->mpp);
1055         }
1056 }
1057
1058 static void
1059 enable_group(struct path * pp)
1060 {
1061         struct pathgroup * pgp;
1062
1063         /*
1064          * if path is added through uev_add_path, pgindex can be unset.
1065          * next update_strings() will set it, upon map reload event.
1066          *
1067          * we can safely return here, because upon map reload, all
1068          * PG will be enabled.
1069          */
1070         if (!pp->mpp->pg || !pp->pgindex)
1071                 return;
1072
1073         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1074         
1075         if (pgp->status == PGSTATE_DISABLED) {
1076                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
1077                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
1078         }
1079 }
1080
1081 static void
1082 mpvec_garbage_collector (struct vectors * vecs)
1083 {
1084         struct multipath * mpp;
1085         int i;
1086
1087         vector_foreach_slot (vecs->mpvec, mpp, i) {
1088                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
1089                         condlog(2, "%s: remove dead map", mpp->alias);
1090                         remove_map(mpp, vecs, stop_waiter_thread, 1);
1091                         i--;
1092                 }
1093         }
1094 }
1095
1096 static void
1097 defered_failback_tick (vector mpvec)
1098 {
1099         struct multipath * mpp;
1100         int i;
1101
1102         vector_foreach_slot (mpvec, mpp, i) {
1103                 /*
1104                  * defered failback getting sooner
1105                  */
1106                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1107                         mpp->failback_tick--;
1108
1109                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1110                                 switch_pathgroup(mpp);
1111                 }
1112         }
1113 }
1114
1115 static void
1116 retry_count_tick(vector mpvec)
1117 {
1118         struct multipath *mpp;
1119         int i;
1120
1121         vector_foreach_slot (mpvec, mpp, i) {
1122                 if (mpp->retry_tick) {
1123                         mpp->stat_total_queueing_time++;
1124                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1125                         if(--mpp->retry_tick == 0) {
1126                                 dm_queue_if_no_path(mpp->alias, 0);
1127                                 condlog(2, "%s: Disable queueing", mpp->alias);
1128                         }
1129                 }
1130         }
1131 }
1132
1133 static void *
1134 checkerloop (void *ap)
1135 {
1136         struct vectors *vecs;
1137         struct path *pp;
1138         int i, count = 0;
1139         int newstate;
1140         char checker_msg[MAX_CHECKER_MSG_SIZE];
1141
1142         mlockall(MCL_CURRENT | MCL_FUTURE);
1143
1144         memset(checker_msg, 0, MAX_CHECKER_MSG_SIZE);
1145         vecs = (struct vectors *)ap;
1146
1147         condlog(2, "path checkers start up");
1148
1149         /*
1150          * init the path check interval
1151          */
1152         vector_foreach_slot (vecs->pathvec, pp, i) {
1153                 pp->checkint = conf->checkint;
1154         }
1155
1156         while (1) {
1157                 pthread_cleanup_push(cleanup_lock, vecs->lock);
1158                 lock(vecs->lock);
1159                 condlog(4, "tick");
1160
1161                 vector_foreach_slot (vecs->pathvec, pp, i) {
1162                         if (!pp->mpp)
1163                                 continue;
1164
1165                         if (pp->tick && --pp->tick)
1166                                 continue; /* don't check this path yet */
1167
1168                         /*
1169                          * provision a next check soonest,
1170                          * in case we exit abnormaly from here
1171                          */
1172                         pp->tick = conf->checkint;
1173                         
1174                         if (!pp->checkfn) {
1175                                 pathinfo(pp, conf->hwtable, DI_SYSFS);
1176                                 select_checkfn(pp);
1177                         }
1178
1179                         if (!pp->checkfn) {
1180                                 condlog(0, "%s: checkfn is void", pp->dev);
1181                                 continue;
1182                         }
1183                         newstate = pp->checkfn(pp->fd, checker_msg,
1184                                                &pp->checker_context);
1185                         
1186                         if (newstate < 0) {
1187                                 condlog(2, "%s: unusable path", pp->dev);
1188                                 pathinfo(pp, conf->hwtable, 0);
1189                                 continue;
1190                         }
1191
1192                         if (newstate != pp->state) {
1193                                 pp->state = newstate;
1194                                 LOG_MSG(1, checker_msg);
1195
1196                                 /*
1197                                  * upon state change, reset the checkint
1198                                  * to the shortest delay
1199                                  */
1200                                 pp->checkint = conf->checkint;
1201
1202                                 if (newstate == PATH_DOWN ||
1203                                     newstate == PATH_SHAKY ||
1204                                     update_multipath_strings(pp->mpp,
1205                                                              vecs->pathvec)) {
1206                                         /*
1207                                          * proactively fail path in the DM
1208                                          */
1209                                         fail_path(pp);
1210
1211                                         /*
1212                                          * cancel scheduled failback
1213                                          */
1214                                         pp->mpp->failback_tick = 0;
1215
1216                                         pp->mpp->stat_path_failures++;
1217                                         continue;
1218                                 }
1219
1220                                 /*
1221                                  * reinstate this path
1222                                  */
1223                                 reinstate_path(pp);
1224
1225                                 /*
1226                                  * schedule [defered] failback
1227                                  */
1228                                 if (pp->mpp->pgfailback > 0)
1229                                         pp->mpp->failback_tick =
1230                                                 pp->mpp->pgfailback + 1;
1231                                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
1232                                     need_switch_pathgroup(pp->mpp, 1))
1233                                         switch_pathgroup(pp->mpp);
1234
1235                                 /*
1236                                  * if at least one path is up in a group, and
1237                                  * the group is disabled, re-enable it
1238                                  */
1239                                 if (newstate == PATH_UP)
1240                                         enable_group(pp);
1241                         }
1242                         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1243                                 LOG_MSG(4, checker_msg);
1244                                 /*
1245                                  * double the next check delay.
1246                                  * max at conf->max_checkint
1247                                  */
1248                                 if (pp->checkint < (conf->max_checkint / 2))
1249                                         pp->checkint = 2 * pp->checkint;
1250                                 else
1251                                         pp->checkint = conf->max_checkint;
1252
1253                                 pp->tick = pp->checkint;
1254                                 condlog(4, "%s: delay next check %is",
1255                                                 pp->dev_t, pp->tick);
1256
1257                         }
1258                         pp->state = newstate;
1259
1260                         /*
1261                          * path prio refreshing
1262                          */
1263                         condlog(4, "path prio refresh");
1264                         pathinfo(pp, conf->hwtable, DI_PRIO);
1265
1266                         if (need_switch_pathgroup(pp->mpp, 0)) {
1267                                 if (pp->mpp->pgfailback > 0)
1268                                         pp->mpp->failback_tick =
1269                                                 pp->mpp->pgfailback + 1;
1270                                 else if (pp->mpp->pgfailback ==
1271                                                 -FAILBACK_IMMEDIATE)
1272                                         switch_pathgroup(pp->mpp);
1273                         }
1274                 }
1275                 defered_failback_tick(vecs->mpvec);
1276                 retry_count_tick(vecs->mpvec);
1277
1278                 if (count)
1279                         count--;
1280                 else {
1281                         condlog(4, "map garbage collection");
1282                         mpvec_garbage_collector(vecs);
1283                         count = MAPGCINT;
1284                 }
1285                 
1286                 lock_cleanup_pop(vecs->lock);
1287                 sleep(1);
1288         }
1289         return NULL;
1290 }
1291
1292 int
1293 configure (struct vectors * vecs, int start_waiters)
1294 {
1295         struct multipath * mpp;
1296         struct path * pp;
1297         vector mpvec;
1298         int i;
1299
1300         if (!(vecs->pathvec = vector_alloc()))
1301                 return 1;
1302         
1303         if (!(vecs->mpvec = vector_alloc()))
1304                 return 1;
1305         
1306         if (!(mpvec = vector_alloc()))
1307                 return 1;
1308
1309         /*
1310          * probe for current path (from sysfs) and map (from dm) sets
1311          */
1312         path_discovery(vecs->pathvec, conf, DI_ALL);
1313
1314         vector_foreach_slot (vecs->pathvec, pp, i)
1315                 pp->checkint = conf->checkint;
1316
1317         if (map_discovery(vecs))
1318                 return 1;
1319
1320         /*
1321          * create new set of maps & push changed ones into dm
1322          */
1323         if (coalesce_paths(vecs, mpvec, NULL))
1324                 return 1;
1325
1326         /*
1327          * may need to remove some maps which are no longer relevant
1328          * e.g., due to blacklist changes in conf file
1329          */
1330         if (coalesce_maps(vecs, mpvec))
1331                 return 1;
1332
1333         dm_lib_release();
1334
1335         if (conf->verbosity > 2)
1336                 vector_foreach_slot(mpvec, mpp, i)
1337                         print_map(mpp);
1338
1339         /*
1340          * purge dm of old maps
1341          */
1342         remove_maps(vecs, NULL);
1343
1344         /*
1345          * save new set of maps formed by considering current path state
1346          */
1347         vecs->mpvec = mpvec;
1348
1349         /*
1350          * start dm event waiter threads for these new maps
1351          */
1352         vector_foreach_slot(vecs->mpvec, mpp, i) {
1353                 if (setup_multipath(vecs, mpp))
1354                         return 1;
1355                 if (start_waiters)
1356                         if (start_waiter_thread(mpp, vecs))
1357                                 return 1;
1358         }
1359         return 0;
1360 }
1361
1362 int
1363 reconfigure (struct vectors * vecs)
1364 {
1365         struct config * old = conf;
1366
1367         /*
1368          * free old map and path vectors ... they use old conf state
1369          */
1370         if (VECTOR_SIZE(vecs->mpvec))
1371                 remove_maps(vecs, stop_waiter_thread);
1372
1373         if (VECTOR_SIZE(vecs->pathvec))
1374                 free_pathvec(vecs->pathvec, FREE_PATHS);
1375
1376         conf = NULL;
1377
1378         if (load_config(DEFAULT_CONFIGFILE))
1379                 return 1;
1380
1381         conf->verbosity = old->verbosity;
1382
1383         if (!conf->checkint) {
1384                 conf->checkint = CHECKINT;
1385                 conf->max_checkint = MAX_CHECKINT;
1386         }
1387         configure(vecs, 1);
1388         free_config(old);
1389         return 0;
1390 }
1391
1392 static struct vectors *
1393 init_vecs (void)
1394 {
1395         struct vectors * vecs;
1396
1397         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1398
1399         if (!vecs)
1400                 return NULL;
1401
1402         vecs->lock = 
1403                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1404
1405         if (!vecs->lock)
1406                 goto out;
1407
1408         vecs->pathvec = vector_alloc();
1409
1410         if (!vecs->pathvec)
1411                 goto out1;
1412                 
1413         vecs->mpvec = vector_alloc();
1414
1415         if (!vecs->mpvec)
1416                 goto out2;
1417         
1418         pthread_mutex_init(vecs->lock, NULL);
1419
1420         return vecs;
1421
1422 out2:
1423         vector_free(vecs->pathvec);
1424 out1:
1425         FREE(vecs->lock);
1426 out:
1427         FREE(vecs);
1428         condlog(0, "failed to init paths");
1429         return NULL;
1430 }
1431
1432 static void *
1433 signal_set(int signo, void (*func) (int))
1434 {
1435         int r;
1436         struct sigaction sig;
1437         struct sigaction osig;
1438
1439         sig.sa_handler = func;
1440         sigemptyset(&sig.sa_mask);
1441         sig.sa_flags = 0;
1442
1443         r = sigaction(signo, &sig, &osig);
1444
1445         if (r < 0)
1446                 return (SIG_ERR);
1447         else
1448                 return (osig.sa_handler);
1449 }
1450
1451 static void
1452 sighup (int sig)
1453 {
1454         condlog(2, "reconfigure (SIGHUP)");
1455
1456         lock(gvecs->lock);
1457         reconfigure(gvecs);
1458         unlock(gvecs->lock);
1459
1460 #ifdef _DEBUG_
1461         dbg_free_final(NULL);
1462 #endif
1463 }
1464
1465 static void
1466 sigend (int sig)
1467 {
1468         exit_daemon(0);
1469 }
1470
1471 static void
1472 sigusr1 (int sig)
1473 {
1474         condlog(3, "SIGUSR1 received");
1475 }
1476
1477 static void
1478 signal_init(void)
1479 {
1480         signal_set(SIGHUP, sighup);
1481         signal_set(SIGUSR1, sigusr1);
1482         signal_set(SIGINT, sigend);
1483         signal_set(SIGTERM, sigend);
1484         signal_set(SIGKILL, sigend);
1485 }
1486
1487 static void
1488 setscheduler (void)
1489 {
1490         int res;
1491         static struct sched_param sched_param = {
1492                 sched_priority: 99
1493         };
1494
1495         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1496
1497         if (res == -1)
1498                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1499         return;
1500 }
1501
1502 static void
1503 set_oom_adj (int val)
1504 {
1505         FILE *fp;
1506
1507         fp = fopen("/proc/self/oom_adj", "w");
1508
1509         if (!fp)
1510                 return;
1511
1512         fprintf(fp, "%i", val);
1513         fclose(fp);
1514 }
1515         
1516 static int
1517 child (void * param)
1518 {
1519         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1520         pthread_attr_t attr;
1521         struct vectors * vecs;
1522
1523         mlockall(MCL_CURRENT | MCL_FUTURE);
1524
1525         if (logsink)
1526                 log_thread_start();
1527
1528         condlog(2, "--------start up--------");
1529         condlog(2, "read " DEFAULT_CONFIGFILE);
1530
1531         if (load_config(DEFAULT_CONFIGFILE))
1532                 exit(1);
1533
1534         setlogmask(LOG_UPTO(conf->verbosity + 3));
1535
1536         /*
1537          * fill the voids left in the config file
1538          */
1539         if (!conf->checkint) {
1540                 conf->checkint = CHECKINT;
1541                 conf->max_checkint = MAX_CHECKINT;
1542         }
1543
1544         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1545                 if (logsink)
1546                         log_thread_stop();
1547
1548                 exit(1);
1549         }
1550         signal_init();
1551         setscheduler();
1552         set_oom_adj(-16);
1553         vecs = gvecs = init_vecs();
1554
1555         if (!vecs)
1556                 exit(1);
1557
1558         if (sysfs_get_mnt_path(sysfs_path, FILE_NAME_SIZE)) {
1559                 condlog(0, "can not find sysfs mount point");
1560                 exit(1);
1561         }
1562
1563         /*
1564          * fetch and configure both paths and multipaths
1565          */
1566         if (configure(vecs, 1)) {
1567                 condlog(0, "failure during configuration");
1568                 exit(1);
1569         }
1570
1571         /*
1572          * start threads
1573          */
1574         pthread_attr_init(&attr);
1575         pthread_attr_setstacksize(&attr, 64 * 1024);
1576         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1577         
1578         pthread_create(&check_thr, &attr, checkerloop, vecs);
1579         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1580         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1581
1582         pthread_cond_wait(&exit_cond, &exit_mutex);
1583
1584         /*
1585          * exit path
1586          */
1587         lock(vecs->lock);
1588         remove_maps(vecs, stop_waiter_thread);
1589         free_pathvec(vecs->pathvec, FREE_PATHS);
1590
1591         pthread_cancel(check_thr);
1592         pthread_cancel(uevent_thr);
1593         pthread_cancel(uxlsnr_thr);
1594
1595         free_keys(keys);
1596         keys = NULL;
1597         free_handlers(handlers);
1598         handlers = NULL;
1599         free_polls();
1600
1601         unlock(vecs->lock);
1602         pthread_mutex_destroy(vecs->lock);
1603         FREE(vecs->lock);
1604         vecs->lock = NULL;
1605         FREE(vecs);
1606         vecs = NULL;
1607         free_config(conf);
1608         conf = NULL;
1609
1610         condlog(2, "--------shut down-------");
1611         
1612         if (logsink)
1613                 log_thread_stop();
1614
1615         dm_lib_release();
1616         dm_lib_exit();
1617
1618 #ifdef _DEBUG_
1619         dbg_free_final(NULL);
1620 #endif
1621
1622         exit(0);
1623 }
1624
1625 static int
1626 daemonize(void)
1627 {
1628         int pid;
1629         int in_fd, out_fd;
1630
1631         if( (pid = fork()) < 0){
1632                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1633                 return -1;
1634         }
1635         else if (pid != 0)
1636                 return pid;
1637
1638         setsid();
1639
1640         if ( (pid = fork()) < 0)
1641                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1642         else if (pid != 0)
1643                 _exit(0);
1644
1645         in_fd = open("/dev/null", O_RDONLY);
1646         if (in_fd < 0){
1647                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1648                         strerror(errno));
1649                 _exit(0);
1650         }
1651         out_fd = open("/dev/console", O_WRONLY);
1652         if (out_fd < 0){
1653                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1654                         strerror(errno));
1655                 _exit(0);
1656         }
1657
1658         close(STDIN_FILENO);
1659         dup(in_fd);
1660         close(STDOUT_FILENO);
1661         dup(out_fd);
1662         close(STDERR_FILENO);
1663         dup(out_fd);
1664
1665         close(in_fd);
1666         close(out_fd);
1667         chdir("/");
1668         umask(0);
1669         return 0;
1670 }
1671
1672 int
1673 main (int argc, char *argv[])
1674 {
1675         extern char *optarg;
1676         extern int optind;
1677         int arg;
1678         int err;
1679         
1680         logsink = 1;
1681
1682         if (getuid() != 0) {
1683                 fprintf(stderr, "need to be root\n");
1684                 exit(1);
1685         }
1686
1687         /* make sure we don't lock any path */
1688         chdir("/");
1689         umask(umask(077) | 022);
1690
1691         conf = alloc_config();
1692
1693         if (!conf)
1694                 exit(1);
1695
1696         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1697         switch(arg) {
1698                 case 'd':
1699                         logsink = 0;
1700                         //debug=1; /* ### comment me out ### */
1701                         break;
1702                 case 'v':
1703                         if (sizeof(optarg) > sizeof(char *) ||
1704                             !isdigit(optarg[0]))
1705                                 exit(1);
1706
1707                         conf->verbosity = atoi(optarg);
1708                         break;
1709                 case 'k':
1710                         uxclnt(optarg);
1711                         exit(0);
1712                 default:
1713                         ;
1714                 }
1715         }
1716
1717         if (!logsink)
1718                 err = 0;
1719         else
1720                 err = daemonize();
1721         
1722         if (err < 0)
1723                 /* error */
1724                 exit(1);
1725         else if (err > 0)
1726                 /* parent dies */
1727                 exit(0);
1728         else
1729                 /* child lives */
1730                 return (child(NULL));
1731 }
1732