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