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