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