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