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