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