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