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