3b686426a56261ddce3515ba701883809504cd2d
[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                 if (conf->log_checker_err == LOG_CHKR_ERR_ONCE)
1198                         LOG_MSG(3, checker_message(&pp->checker));
1199                 else
1200                         LOG_MSG(2, checker_message(&pp->checker));
1201         }
1202
1203         pp->state = newstate;
1204
1205         /*
1206          * path prio refreshing
1207          */
1208         condlog(4, "path prio refresh");
1209
1210         if (update_prio(pp, new_path_up) &&
1211             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
1212              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1213                 update_path_groups(pp->mpp, vecs, !new_path_up);
1214         else if (need_switch_pathgroup(pp->mpp, 0)) {
1215                 if (pp->mpp->pgfailback > 0 &&
1216                     (new_path_up || pp->mpp->failback_tick <= 0))
1217                         pp->mpp->failback_tick =
1218                                 pp->mpp->pgfailback + 1;
1219                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1220                         switch_pathgroup(pp->mpp);
1221         }
1222 }
1223
1224 static void *
1225 checkerloop (void *ap)
1226 {
1227         struct vectors *vecs;
1228         struct path *pp;
1229         int count = 0;
1230         unsigned int i;
1231         sigset_t old;
1232
1233         mlockall(MCL_CURRENT | MCL_FUTURE);
1234         vecs = (struct vectors *)ap;
1235         condlog(2, "path checkers start up");
1236
1237         /*
1238          * init the path check interval
1239          */
1240         vector_foreach_slot (vecs->pathvec, pp, i) {
1241                 pp->checkint = conf->checkint;
1242         }
1243
1244         while (1) {
1245                 block_signal(SIGHUP, &old);
1246                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1247                 lock(vecs->lock);
1248                 condlog(4, "tick");
1249
1250                 if (vecs->pathvec) {
1251                         vector_foreach_slot (vecs->pathvec, pp, i) {
1252                                 check_path(vecs, pp);
1253                         }
1254                 }
1255                 if (vecs->mpvec) {
1256                         defered_failback_tick(vecs->mpvec);
1257                         retry_count_tick(vecs->mpvec);
1258                 }
1259                 if (count)
1260                         count--;
1261                 else {
1262                         condlog(4, "map garbage collection");
1263                         mpvec_garbage_collector(vecs);
1264                         count = MAPGCINT;
1265                 }
1266
1267                 lock_cleanup_pop(vecs->lock);
1268                 pthread_sigmask(SIG_SETMASK, &old, NULL);
1269                 sleep(1);
1270         }
1271         return NULL;
1272 }
1273
1274 int
1275 configure (struct vectors * vecs, int start_waiters)
1276 {
1277         struct multipath * mpp;
1278         struct path * pp;
1279         vector mpvec;
1280         int i;
1281
1282         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1283                 return 1;
1284
1285         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1286                 return 1;
1287
1288         if (!(mpvec = vector_alloc()))
1289                 return 1;
1290
1291         /*
1292          * probe for current path (from sysfs) and map (from dm) sets
1293          */
1294         path_discovery(vecs->pathvec, conf, DI_ALL);
1295
1296         vector_foreach_slot (vecs->pathvec, pp, i){
1297                 if (filter_path(conf, pp) > 0){
1298                         vector_del_slot(vecs->pathvec, i);
1299                         free_path(pp);
1300                         i--;
1301                 }
1302                 else
1303                         pp->checkint = conf->checkint;
1304         }
1305         if (map_discovery(vecs))
1306                 return 1;
1307
1308         /*
1309          * create new set of maps & push changed ones into dm
1310          */
1311         if (coalesce_paths(vecs, mpvec, NULL, 1))
1312                 return 1;
1313
1314         /*
1315          * may need to remove some maps which are no longer relevant
1316          * e.g., due to blacklist changes in conf file
1317          */
1318         if (coalesce_maps(vecs, mpvec))
1319                 return 1;
1320
1321         dm_lib_release();
1322
1323         sync_maps_state(mpvec);
1324
1325         /*
1326          * purge dm of old maps
1327          */
1328         remove_maps(vecs);
1329
1330         /*
1331          * save new set of maps formed by considering current path state
1332          */
1333         vector_free(vecs->mpvec);
1334         vecs->mpvec = mpvec;
1335
1336         /*
1337          * start dm event waiter threads for these new maps
1338          */
1339         vector_foreach_slot(vecs->mpvec, mpp, i) {
1340                 if (setup_multipath(vecs, mpp))
1341                         return 1;
1342                 if (start_waiters)
1343                         if (start_waiter_thread(mpp, vecs))
1344                                 return 1;
1345         }
1346         return 0;
1347 }
1348
1349 int
1350 reconfigure (struct vectors * vecs)
1351 {
1352         struct config * old = conf;
1353         int retval = 1;
1354
1355         /*
1356          * free old map and path vectors ... they use old conf state
1357          */
1358         if (VECTOR_SIZE(vecs->mpvec))
1359                 remove_maps_and_stop_waiters(vecs);
1360
1361         if (VECTOR_SIZE(vecs->pathvec))
1362                 free_pathvec(vecs->pathvec, FREE_PATHS);
1363
1364         vecs->pathvec = NULL;
1365         conf = NULL;
1366
1367         if (!load_config(DEFAULT_CONFIGFILE)) {
1368                 conf->verbosity = old->verbosity;
1369                 conf->daemon = 1;
1370                 configure(vecs, 1);
1371                 free_config(old);
1372                 retval = 0;
1373         }
1374
1375         return retval;
1376 }
1377
1378 static struct vectors *
1379 init_vecs (void)
1380 {
1381         struct vectors * vecs;
1382
1383         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1384
1385         if (!vecs)
1386                 return NULL;
1387
1388         vecs->lock.mutex =
1389                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1390
1391         if (!vecs->lock.mutex)
1392                 goto out;
1393
1394         pthread_mutex_init(vecs->lock.mutex, NULL);
1395         vecs->lock.depth = 0;
1396
1397         return vecs;
1398
1399 out:
1400         FREE(vecs);
1401         condlog(0, "failed to init paths");
1402         return NULL;
1403 }
1404
1405 static void *
1406 signal_set(int signo, void (*func) (int))
1407 {
1408         int r;
1409         struct sigaction sig;
1410         struct sigaction osig;
1411
1412         sig.sa_handler = func;
1413         sigemptyset(&sig.sa_mask);
1414         sig.sa_flags = 0;
1415
1416         r = sigaction(signo, &sig, &osig);
1417
1418         if (r < 0)
1419                 return (SIG_ERR);
1420         else
1421                 return (osig.sa_handler);
1422 }
1423
1424 static void
1425 sighup (int sig)
1426 {
1427         condlog(2, "reconfigure (SIGHUP)");
1428
1429         if (running_state != DAEMON_RUNNING)
1430                 return;
1431
1432         lock(gvecs->lock);
1433         reconfigure(gvecs);
1434         unlock(gvecs->lock);
1435
1436 #ifdef _DEBUG_
1437         dbg_free_final(NULL);
1438 #endif
1439 }
1440
1441 static void
1442 sigend (int sig)
1443 {
1444         exit_daemon(0);
1445 }
1446
1447 static void
1448 sigusr1 (int sig)
1449 {
1450         condlog(3, "SIGUSR1 received");
1451 }
1452
1453 static void
1454 signal_init(void)
1455 {
1456         signal_set(SIGHUP, sighup);
1457         signal_set(SIGUSR1, sigusr1);
1458         signal_set(SIGINT, sigend);
1459         signal_set(SIGTERM, sigend);
1460         signal(SIGPIPE, SIG_IGN);
1461 }
1462
1463 static void
1464 setscheduler (void)
1465 {
1466         int res;
1467         static struct sched_param sched_param = {
1468                 .sched_priority = 99
1469         };
1470
1471         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1472
1473         if (res == -1)
1474                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1475         return;
1476 }
1477
1478 static void
1479 set_oom_adj (void)
1480 {
1481         int retry = 1;
1482         char *file = "/proc/self/oom_score_adj";
1483         int score = OOM_SCORE_ADJ_MIN;
1484         FILE *fp;
1485         struct stat st;
1486
1487         do {
1488                 if (stat(file, &st) == 0){
1489                         fp = fopen(file, "w");
1490                         if (!fp) {
1491                                 condlog(0, "couldn't fopen %s : %s", file,
1492                                         strerror(errno));
1493                                 return;
1494                         }
1495                         fprintf(fp, "%i", score);
1496                         fclose(fp);
1497                         return;
1498                 }
1499                 if (errno != ENOENT) {
1500                         condlog(0, "couldn't stat %s : %s", file,
1501                                 strerror(errno));
1502                         return;
1503                 }
1504                 file = "/proc/self/oom_adj";
1505                 score = OOM_ADJUST_MIN;
1506         } while (retry--);
1507         condlog(0, "couldn't adjust oom score");
1508 }
1509
1510 static int
1511 child (void * param)
1512 {
1513         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1514         pthread_attr_t log_attr, misc_attr;
1515         struct vectors * vecs;
1516         struct multipath * mpp;
1517         int i;
1518         int rc;
1519
1520         mlockall(MCL_CURRENT | MCL_FUTURE);
1521
1522         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1523         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1524
1525         if (logsink) {
1526                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1527                 log_thread_start(&log_attr);
1528                 pthread_attr_destroy(&log_attr);
1529         }
1530
1531         running_state = DAEMON_START;
1532
1533         condlog(2, "--------start up--------");
1534         condlog(2, "read " DEFAULT_CONFIGFILE);
1535
1536         if (load_config(DEFAULT_CONFIGFILE))
1537                 exit(1);
1538
1539         if (init_checkers()) {
1540                 condlog(0, "failed to initialize checkers");
1541                 exit(1);
1542         }
1543         if (init_prio()) {
1544                 condlog(0, "failed to initialize prioritizers");
1545                 exit(1);
1546         }
1547
1548         setlogmask(LOG_UPTO(conf->verbosity + 3));
1549
1550         if (conf->max_fds) {
1551                 struct rlimit fd_limit;
1552
1553                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1554                         condlog(0, "can't get open fds limit: %s\n",
1555                                 strerror(errno));
1556                         fd_limit.rlim_cur = 0;
1557                         fd_limit.rlim_max = 0;
1558                 }
1559                 if (fd_limit.rlim_cur < conf->max_fds) {
1560                         fd_limit.rlim_cur = conf->max_fds;
1561                         if (fd_limit.rlim_max < conf->max_fds)
1562                                 fd_limit.rlim_max = conf->max_fds;
1563                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1564                                 condlog(0, "can't set open fds limit to "
1565                                         "%lu/%lu : %s\n",
1566                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1567                                         strerror(errno));
1568                         } else {
1569                                 condlog(3, "set open fds limit to %lu/%lu\n",
1570                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1571                         }
1572                 }
1573
1574         }
1575
1576         signal_init();
1577         setscheduler();
1578         set_oom_adj();
1579         vecs = gvecs = init_vecs();
1580
1581         if (!vecs)
1582                 exit(1);
1583
1584         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1585                 condlog(0, "can not find sysfs mount point");
1586                 exit(1);
1587         }
1588         conf->daemon = 1;
1589         udev_set_sync_support(0);
1590         /*
1591          * Start uevent listener early to catch events
1592          */
1593         if ((rc = pthread_create(&uevent_thr, &misc_attr, ueventloop, vecs))) {
1594                 condlog(0, "failed to create uevent thread: %d", rc);
1595                 exit(1);
1596         }
1597         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1598                 condlog(0, "failed to create cli listener: %d", rc);
1599                 exit(1);
1600         }
1601         /*
1602          * fetch and configure both paths and multipaths
1603          */
1604         lock(vecs->lock);
1605         running_state = DAEMON_CONFIGURE;
1606
1607         if (configure(vecs, 1)) {
1608                 unlock(vecs->lock);
1609                 condlog(0, "failure during configuration");
1610                 exit(1);
1611         }
1612         unlock(vecs->lock);
1613
1614         /*
1615          * start threads
1616          */
1617         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1618                 condlog(0,"failed to create checker loop thread: %d", rc);
1619                 exit(1);
1620         }
1621         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1622                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1623                 exit(1);
1624         }
1625         pthread_attr_destroy(&misc_attr);
1626
1627         pthread_mutex_lock(&exit_mutex);
1628         /* Startup complete, create logfile */
1629         if (pidfile_create(DEFAULT_PIDFILE, daemon_pid))
1630                 /* Ignore errors, we can live without */
1631                 condlog(1, "failed to create pidfile");
1632
1633         running_state = DAEMON_RUNNING;
1634         pthread_cond_wait(&exit_cond, &exit_mutex);
1635
1636         /*
1637          * exit path
1638          */
1639         running_state = DAEMON_SHUTDOWN;
1640         block_signal(SIGHUP, NULL);
1641         lock(vecs->lock);
1642         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1643                 vector_foreach_slot(vecs->mpvec, mpp, i)
1644                         dm_queue_if_no_path(mpp->alias, 0);
1645         remove_maps_and_stop_waiters(vecs);
1646         unlock(vecs->lock);
1647
1648         pthread_cancel(check_thr);
1649         pthread_cancel(uevent_thr);
1650         pthread_cancel(uxlsnr_thr);
1651         pthread_cancel(uevq_thr);
1652
1653         sysfs_cleanup();
1654
1655         lock(vecs->lock);
1656         free_pathvec(vecs->pathvec, FREE_PATHS);
1657         vecs->pathvec = NULL;
1658         unlock(vecs->lock);
1659         /* Now all the waitevent threads will start rushing in. */
1660         while (vecs->lock.depth > 0) {
1661                 sleep (1); /* This is weak. */
1662                 condlog(3,"Have %d wait event checkers threads to de-alloc, waiting..\n", vecs->lock.depth);
1663         }
1664         pthread_mutex_destroy(vecs->lock.mutex);
1665         FREE(vecs->lock.mutex);
1666         vecs->lock.depth = 0;
1667         vecs->lock.mutex = NULL;
1668         FREE(vecs);
1669         vecs = NULL;
1670
1671         cleanup_checkers();
1672         cleanup_prio();
1673
1674         dm_lib_release();
1675         dm_lib_exit();
1676
1677         /* We're done here */
1678         condlog(3, "unlink pidfile");
1679         unlink(DEFAULT_PIDFILE);
1680
1681         condlog(2, "--------shut down-------");
1682
1683         if (logsink)
1684                 log_thread_stop();
1685
1686         /*
1687          * Freeing config must be done after condlog() and dm_lib_exit(),
1688          * because logging functions like dlog() and dm_write_log()
1689          * reference the config.
1690          */
1691         free_config(conf);
1692         conf = NULL;
1693
1694 #ifdef _DEBUG_
1695         dbg_free_final(NULL);
1696 #endif
1697
1698         exit(0);
1699 }
1700
1701 static int
1702 daemonize(void)
1703 {
1704         int pid;
1705         int dev_null_fd;
1706
1707         if( (pid = fork()) < 0){
1708                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1709                 return -1;
1710         }
1711         else if (pid != 0)
1712                 return pid;
1713
1714         setsid();
1715
1716         if ( (pid = fork()) < 0)
1717                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1718         else if (pid != 0)
1719                 _exit(0);
1720
1721         if (chdir("/") < 0)
1722                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1723
1724         dev_null_fd = open("/dev/null", O_RDWR);
1725         if (dev_null_fd < 0){
1726                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
1727                         strerror(errno));
1728                 _exit(0);
1729         }
1730
1731         close(STDIN_FILENO);
1732         dup(dev_null_fd);
1733         close(STDOUT_FILENO);
1734         dup(dev_null_fd);
1735         close(STDERR_FILENO);
1736         dup(dev_null_fd);
1737         close(dev_null_fd);
1738         daemon_pid = getpid();
1739         return 0;
1740 }
1741
1742 int
1743 main (int argc, char *argv[])
1744 {
1745         extern char *optarg;
1746         extern int optind;
1747         int arg;
1748         int err;
1749
1750         logsink = 1;
1751         running_state = DAEMON_INIT;
1752         dm_init();
1753
1754         if (getuid() != 0) {
1755                 fprintf(stderr, "need to be root\n");
1756                 exit(1);
1757         }
1758
1759         /* make sure we don't lock any path */
1760         chdir("/");
1761         umask(umask(077) | 022);
1762
1763         conf = alloc_config();
1764
1765         if (!conf)
1766                 exit(1);
1767
1768         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1769         switch(arg) {
1770                 case 'd':
1771                         logsink = 0;
1772                         //debug=1; /* ### comment me out ### */
1773                         break;
1774                 case 'v':
1775                         if (sizeof(optarg) > sizeof(char *) ||
1776                             !isdigit(optarg[0]))
1777                                 exit(1);
1778
1779                         conf->verbosity = atoi(optarg);
1780                         break;
1781                 case 'k':
1782                         uxclnt(optarg);
1783                         exit(0);
1784                 default:
1785                         ;
1786                 }
1787         }
1788         if (optind < argc) {
1789                 char cmd[CMDSIZE];
1790                 char * s = cmd;
1791                 char * c = s;
1792
1793                 while (optind < argc) {
1794                         if (strchr(argv[optind], ' '))
1795                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1796                         else
1797                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1798                         optind++;
1799                 }
1800                 c += snprintf(c, s + CMDSIZE - c, "\n");
1801                 uxclnt(s);
1802                 exit(0);
1803         }
1804
1805         if (!logsink)
1806                 err = 0;
1807         else
1808                 err = daemonize();
1809
1810         if (err < 0)
1811                 /* error */
1812                 exit(1);
1813         else if (err > 0)
1814                 /* parent dies */
1815                 exit(0);
1816         else
1817                 /* child lives */
1818                 return (child(NULL));
1819 }
1820