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