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