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