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