Reassign existing device-mapper maps
[platform/upstream/multipath-tools.git] / multipathd / main.c
1 /*
2  * Copyright (c) 2004, 2005 Christophe Varoqui
3  * Copyright (c) 2005 Kiyoshi Ueda, NEC
4  * Copyright (c) 2005 Benjamin Marzinski, Redhat
5  * Copyright (c) 2005 Edward Goggin, EMC
6  */
7 #include <unistd.h>
8 #include <sys/stat.h>
9 #include <libdevmapper.h>
10 #include <wait.h>
11 #include <sys/mman.h>
12 #include <sys/types.h>
13 #include <fcntl.h>
14 #include <errno.h>
15 #include <sys/time.h>
16 #include <sys/resource.h>
17 #include <limits.h>
18
19 /*
20  * libcheckers
21  */
22 #include <checkers.h>
23
24 /*
25  * libmultipath
26  */
27 #include <parser.h>
28 #include <vector.h>
29 #include <memory.h>
30 #include <config.h>
31 #include <util.h>
32 #include <hwtable.h>
33 #include <defaults.h>
34 #include <structs.h>
35 #include <callout.h>
36 #include <blacklist.h>
37 #include <structs_vec.h>
38 #include <dmparser.h>
39 #include <devmapper.h>
40 #include <sysfs.h>
41 #include <dict.h>
42 #include <discovery.h>
43 #include <debug.h>
44 #include <propsel.h>
45 #include <uevent.h>
46 #include <switchgroup.h>
47 #include <print.h>
48 #include <configure.h>
49 #include <prio.h>
50 #include <pgpolicies.h>
51 #include <uevent.h>
52
53 #include "main.h"
54 #include "pidfile.h"
55 #include "uxlsnr.h"
56 #include "uxclnt.h"
57 #include "cli.h"
58 #include "cli_handlers.h"
59 #include "lock.h"
60 #include "waiter.h"
61
62 #define FILE_NAME_SIZE 256
63 #define CMDSIZE 160
64
65 #define LOG_MSG(a,b) \
66         if (strlen(b)) condlog(a, "%s: %s - %s", pp->mpp->alias, pp->dev, b);
67
68 pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
69 pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
70
71 int logsink;
72 enum daemon_status running_state;
73 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 map_discovery (struct vectors * vecs)
640 {
641         struct multipath * mpp;
642         unsigned int i;
643
644         if (dm_get_maps(vecs->mpvec))
645                 return 1;
646
647         vector_foreach_slot (vecs->mpvec, mpp, i)
648                 if (setup_multipath(vecs, mpp))
649                         return 1;
650
651         return 0;
652 }
653
654 int
655 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
656 {
657         struct vectors * vecs;
658         int r;
659
660         *reply = NULL;
661         *len = 0;
662         vecs = (struct vectors *)trigger_data;
663
664         pthread_cleanup_push(cleanup_lock, &vecs->lock);
665         lock(vecs->lock);
666
667         r = parse_cmd(str, reply, len, vecs);
668
669         if (r > 0) {
670                 *reply = STRDUP("fail\n");
671                 *len = strlen(*reply) + 1;
672                 r = 1;
673         }
674         else if (!r && *len == 0) {
675                 *reply = STRDUP("ok\n");
676                 *len = strlen(*reply) + 1;
677                 r = 0;
678         }
679         /* else if (r < 0) leave *reply alone */
680
681         lock_cleanup_pop(vecs->lock);
682         return r;
683 }
684
685 static int
686 uev_discard(char * devpath)
687 {
688         char *tmp;
689         char a[11], b[11];
690
691         /*
692          * keep only block devices, discard partitions
693          */
694         tmp = strstr(devpath, "/block/");
695         if (tmp == NULL){
696                 condlog(4, "no /block/ in '%s'", devpath);
697                 return 1;
698         }
699         if (sscanf(tmp, "/block/%10s", a) != 1 ||
700             sscanf(tmp, "/block/%10[^/]/%10s", a, b) == 2) {
701                 condlog(4, "discard event on %s", devpath);
702                 return 1;
703         }
704         return 0;
705 }
706
707 int
708 uev_trigger (struct uevent * uev, void * trigger_data)
709 {
710         int r = 0;
711         struct vectors * vecs;
712
713         vecs = (struct vectors *)trigger_data;
714
715         if (uev_discard(uev->devpath))
716                 return 0;
717
718         lock(vecs->lock);
719
720         /*
721          * device map event
722          * Add events are ignored here as the tables
723          * are not fully initialised then.
724          */
725         if (!strncmp(uev->kernel, "dm-", 3)) {
726                 if (!strncmp(uev->action, "change", 6)) {
727                         r = uev_add_map(uev, vecs);
728                         goto out;
729                 }
730                 if (!strncmp(uev->action, "remove", 6)) {
731                         r = uev_remove_map(uev, vecs);
732                         goto out;
733                 }
734                 goto out;
735         }
736
737         /*
738          * path add/remove event
739          */
740         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
741                            uev->kernel) > 0)
742                 goto out;
743
744         if (!strncmp(uev->action, "add", 3)) {
745                 r = uev_add_path(uev, vecs);
746                 goto out;
747         }
748         if (!strncmp(uev->action, "remove", 6)) {
749                 r = uev_remove_path(uev, vecs);
750                 goto out;
751         }
752
753 out:
754         unlock(vecs->lock);
755         return r;
756 }
757
758 static void *
759 ueventloop (void * ap)
760 {
761         block_signal(SIGUSR1, NULL);
762         block_signal(SIGHUP, NULL);
763
764         if (uevent_listen())
765                 condlog(0, "error starting uevent listener");
766
767         return NULL;
768 }
769
770 static void *
771 uevqloop (void * ap)
772 {
773         block_signal(SIGUSR1, NULL);
774         block_signal(SIGHUP, NULL);
775
776         if (uevent_dispatch(&uev_trigger, ap))
777                 condlog(0, "error starting uevent dispatcher");
778
779         return NULL;
780 }
781 static void *
782 uxlsnrloop (void * ap)
783 {
784         block_signal(SIGUSR1, NULL);
785         block_signal(SIGHUP, NULL);
786
787         if (cli_init())
788                 return NULL;
789
790         set_handler_callback(LIST+PATHS, cli_list_paths);
791         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
792         set_handler_callback(LIST+MAPS, cli_list_maps);
793         set_handler_callback(LIST+STATUS, cli_list_status);
794         set_handler_callback(LIST+DAEMON, cli_list_daemon);
795         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
796         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
797         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
798         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
799         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
800         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
801         set_handler_callback(LIST+CONFIG, cli_list_config);
802         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
803         set_handler_callback(LIST+DEVICES, cli_list_devices);
804         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
805         set_handler_callback(ADD+PATH, cli_add_path);
806         set_handler_callback(DEL+PATH, cli_del_path);
807         set_handler_callback(ADD+MAP, cli_add_map);
808         set_handler_callback(DEL+MAP, cli_del_map);
809         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
810         set_handler_callback(RECONFIGURE, cli_reconfigure);
811         set_handler_callback(SUSPEND+MAP, cli_suspend);
812         set_handler_callback(RESUME+MAP, cli_resume);
813         set_handler_callback(RESIZE+MAP, cli_resize);
814         set_handler_callback(RESET+MAP, cli_reassign);
815         set_handler_callback(REINSTATE+PATH, cli_reinstate);
816         set_handler_callback(FAIL+PATH, cli_fail);
817         set_handler_callback(DISABLEQ+MAP, cli_disable_queueing);
818         set_handler_callback(RESTOREQ+MAP, cli_restore_queueing);
819         set_handler_callback(DISABLEQ+MAPS, cli_disable_all_queueing);
820         set_handler_callback(RESTOREQ+MAPS, cli_restore_all_queueing);
821         set_handler_callback(QUIT, cli_quit);
822         set_handler_callback(SHUTDOWN, cli_shutdown);
823
824         umask(077);
825         uxsock_listen(&uxsock_trigger, ap);
826
827         return NULL;
828 }
829
830 int
831 exit_daemon (int status)
832 {
833         if (status != 0)
834                 fprintf(stderr, "bad exit status. see daemon.log\n");
835
836         condlog(3, "unlink pidfile");
837         unlink(DEFAULT_PIDFILE);
838
839         pthread_mutex_lock(&exit_mutex);
840         pthread_cond_signal(&exit_cond);
841         pthread_mutex_unlock(&exit_mutex);
842
843         return status;
844 }
845
846 const char *
847 daemon_status(void)
848 {
849         switch (running_state) {
850         case DAEMON_INIT:
851                 return "init";
852         case DAEMON_START:
853                 return "startup";
854         case DAEMON_CONFIGURE:
855                 return "configure";
856         case DAEMON_RUNNING:
857                 return "running";
858         case DAEMON_SHUTDOWN:
859                 return "shutdown";
860         }
861         return NULL;
862 }
863
864 static void
865 fail_path (struct path * pp, int del_active)
866 {
867         if (!pp->mpp)
868                 return;
869
870         condlog(2, "checker failed path %s in map %s",
871                  pp->dev_t, pp->mpp->alias);
872
873         dm_fail_path(pp->mpp->alias, pp->dev_t);
874         if (del_active)
875                 update_queue_mode_del_path(pp->mpp);
876 }
877
878 /*
879  * caller must have locked the path list before calling that function
880  */
881 static void
882 reinstate_path (struct path * pp, int add_active)
883 {
884         if (!pp->mpp)
885                 return;
886
887         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
888                 condlog(0, "%s: reinstate failed", pp->dev_t);
889         else {
890                 condlog(2, "%s: reinstated", pp->dev_t);
891                 if (add_active)
892                         update_queue_mode_add_path(pp->mpp);
893         }
894 }
895
896 static void
897 enable_group(struct path * pp)
898 {
899         struct pathgroup * pgp;
900
901         /*
902          * if path is added through uev_add_path, pgindex can be unset.
903          * next update_strings() will set it, upon map reload event.
904          *
905          * we can safely return here, because upon map reload, all
906          * PG will be enabled.
907          */
908         if (!pp->mpp->pg || !pp->pgindex)
909                 return;
910
911         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
912
913         if (pgp->status == PGSTATE_DISABLED) {
914                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
915                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
916         }
917 }
918
919 static void
920 mpvec_garbage_collector (struct vectors * vecs)
921 {
922         struct multipath * mpp;
923         unsigned int i;
924
925         if (!vecs->mpvec)
926                 return;
927
928         vector_foreach_slot (vecs->mpvec, mpp, i) {
929                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
930                         condlog(2, "%s: remove dead map", mpp->alias);
931                         remove_map_and_stop_waiter(mpp, vecs, 1);
932                         i--;
933                 }
934         }
935 }
936
937 static void
938 defered_failback_tick (vector mpvec)
939 {
940         struct multipath * mpp;
941         unsigned int i;
942
943         vector_foreach_slot (mpvec, mpp, i) {
944                 /*
945                  * defered failback getting sooner
946                  */
947                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
948                         mpp->failback_tick--;
949
950                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
951                                 switch_pathgroup(mpp);
952                 }
953         }
954 }
955
956 static void
957 retry_count_tick(vector mpvec)
958 {
959         struct multipath *mpp;
960         unsigned int i;
961
962         vector_foreach_slot (mpvec, mpp, i) {
963                 if (mpp->retry_tick) {
964                         mpp->stat_total_queueing_time++;
965                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
966                         if(--mpp->retry_tick == 0) {
967                                 dm_queue_if_no_path(mpp->alias, 0);
968                                 condlog(2, "%s: Disable queueing", mpp->alias);
969                         }
970                 }
971         }
972 }
973
974 int update_prio(struct path *pp, int refresh_all)
975 {
976         int oldpriority;
977         struct path *pp1;
978         struct pathgroup * pgp;
979         int i, j, changed = 0;
980
981         if (refresh_all) {
982                 vector_foreach_slot (pp->mpp->pg, pgp, i) {
983                         vector_foreach_slot (pgp->paths, pp1, j) {
984                                 oldpriority = pp1->priority;
985                                 pathinfo(pp1, conf->hwtable, DI_PRIO);
986                                 if (pp1->priority != oldpriority)
987                                         changed = 1;
988                         }
989                 }
990                 return changed;
991         }
992         oldpriority = pp->priority;
993         pathinfo(pp, conf->hwtable, DI_PRIO);
994
995         if (pp->priority == oldpriority)
996                 return 0;
997         return 1;
998 }
999
1000 int update_path_groups(struct multipath *mpp, struct vectors *vecs, int refresh)
1001 {
1002         int i;
1003         struct path * pp;
1004         char params[PARAMS_SIZE];
1005
1006         update_mpp_paths(mpp, vecs->pathvec);
1007         if (refresh) {
1008                 vector_foreach_slot (mpp->paths, pp, i)
1009                         pathinfo(pp, conf->hwtable, DI_PRIO);
1010         }
1011         params[0] = '\0';
1012         if (setup_map(mpp, params, PARAMS_SIZE))
1013                 return 1;
1014
1015         mpp->action = ACT_RELOAD;
1016         if (domap(mpp, params) <= 0) {
1017                 condlog(0, "%s: failed to update map : %s", mpp->alias,
1018                         strerror(errno));
1019                 return 1;
1020         }
1021         dm_lib_release();
1022         setup_multipath(vecs, mpp);
1023         sync_map_state(mpp);
1024
1025         return 0;
1026 }
1027
1028 void
1029 check_path (struct vectors * vecs, struct path * pp)
1030 {
1031         int newstate;
1032         int new_path_up = 0;
1033
1034         if (!pp->mpp)
1035                 return;
1036
1037         if (pp->tick && --pp->tick)
1038                 return; /* don't check this path yet */
1039
1040         /*
1041          * provision a next check soonest,
1042          * in case we exit abnormaly from here
1043          */
1044         pp->tick = conf->checkint;
1045
1046         newstate = path_offline(pp);
1047         if (newstate == PATH_UP)
1048                 newstate = get_state(pp, 1);
1049
1050         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1051                 condlog(2, "%s: unusable path", pp->dev);
1052                 pathinfo(pp, conf->hwtable, 0);
1053                 return;
1054         }
1055         /*
1056          * Async IO in flight. Keep the previous path state
1057          * and reschedule as soon as possible
1058          */
1059         if (newstate == PATH_PENDING) {
1060                 pp->tick = 1;
1061                 return;
1062         }
1063         /*
1064          * Synchronize with kernel state
1065          */
1066         if (update_multipath_strings(pp->mpp, vecs->pathvec)) {
1067                 condlog(1, "%s: Could not synchronize with kernel state\n",
1068                         pp->dev);
1069                 pp->dmstate = PSTATE_UNDEF;
1070         }
1071         if (newstate != pp->state) {
1072                 int oldstate = pp->state;
1073                 pp->state = newstate;
1074                 LOG_MSG(1, checker_message(&pp->checker));
1075
1076                 /*
1077                  * upon state change, reset the checkint
1078                  * to the shortest delay
1079                  */
1080                 pp->checkint = conf->checkint;
1081
1082                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY) {
1083                         /*
1084                          * proactively fail path in the DM
1085                          */
1086                         if (oldstate == PATH_UP ||
1087                             oldstate == PATH_GHOST)
1088                                 fail_path(pp, 1);
1089                         else
1090                                 fail_path(pp, 0);
1091
1092                         /*
1093                          * cancel scheduled failback
1094                          */
1095                         pp->mpp->failback_tick = 0;
1096
1097                         pp->mpp->stat_path_failures++;
1098                         return;
1099                 }
1100
1101                 /*
1102                  * reinstate this path
1103                  */
1104                 if (oldstate != PATH_UP &&
1105                     oldstate != PATH_GHOST)
1106                         reinstate_path(pp, 1);
1107                 else
1108                         reinstate_path(pp, 0);
1109
1110                 new_path_up = 1;
1111
1112                 /*
1113                  * if at least one path is up in a group, and
1114                  * the group is disabled, re-enable it
1115                  */
1116                 if (newstate == PATH_UP)
1117                         enable_group(pp);
1118         }
1119         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1120                 if (pp->dmstate == PSTATE_FAILED ||
1121                     pp->dmstate == PSTATE_UNDEF) {
1122                         /* Clear IO errors */
1123                         reinstate_path(pp, 0);
1124                 } else {
1125                         LOG_MSG(4, checker_message(&pp->checker));
1126                         /*
1127                          * double the next check delay.
1128                          * max at conf->max_checkint
1129                          */
1130                         if (pp->checkint < (conf->max_checkint / 2))
1131                             pp->checkint = 2 * pp->checkint;
1132                         else
1133                             pp->checkint = conf->max_checkint;
1134
1135                         pp->tick = pp->checkint;
1136                         condlog(4, "%s: delay next check %is",
1137                                 pp->dev_t, pp->tick);
1138                 }
1139         }
1140         else if (newstate == PATH_DOWN)
1141                 LOG_MSG(2, checker_message(&pp->checker));
1142
1143         pp->state = newstate;
1144
1145         /*
1146          * path prio refreshing
1147          */
1148         condlog(4, "path prio refresh");
1149
1150         if (update_prio(pp, new_path_up) &&
1151             pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio)
1152                 update_path_groups(pp->mpp, vecs, !new_path_up);
1153         else if (need_switch_pathgroup(pp->mpp, 0)) {
1154                 if (pp->mpp->pgfailback > 0 &&
1155                     (new_path_up || pp->mpp->failback_tick <= 0))
1156                         pp->mpp->failback_tick =
1157                                 pp->mpp->pgfailback + 1;
1158                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1159                         switch_pathgroup(pp->mpp);
1160         }
1161 }
1162
1163 static void *
1164 checkerloop (void *ap)
1165 {
1166         struct vectors *vecs;
1167         struct path *pp;
1168         int count = 0;
1169         unsigned int i;
1170         sigset_t old;
1171
1172         mlockall(MCL_CURRENT | MCL_FUTURE);
1173         vecs = (struct vectors *)ap;
1174         condlog(2, "path checkers start up");
1175
1176         /*
1177          * init the path check interval
1178          */
1179         vector_foreach_slot (vecs->pathvec, pp, i) {
1180                 pp->checkint = conf->checkint;
1181         }
1182
1183         while (1) {
1184                 block_signal(SIGHUP, &old);
1185                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1186                 lock(vecs->lock);
1187                 condlog(4, "tick");
1188
1189                 if (vecs->pathvec) {
1190                         vector_foreach_slot (vecs->pathvec, pp, i) {
1191                                 check_path(vecs, pp);
1192                         }
1193                 }
1194                 if (vecs->mpvec) {
1195                         defered_failback_tick(vecs->mpvec);
1196                         retry_count_tick(vecs->mpvec);
1197                 }
1198                 if (count)
1199                         count--;
1200                 else {
1201                         condlog(4, "map garbage collection");
1202                         mpvec_garbage_collector(vecs);
1203                         count = MAPGCINT;
1204                 }
1205
1206                 lock_cleanup_pop(vecs->lock);
1207                 pthread_sigmask(SIG_SETMASK, &old, NULL);
1208                 sleep(1);
1209         }
1210         return NULL;
1211 }
1212
1213 int
1214 configure (struct vectors * vecs, int start_waiters)
1215 {
1216         struct multipath * mpp;
1217         struct path * pp;
1218         vector mpvec;
1219         int i;
1220
1221         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1222                 return 1;
1223
1224         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1225                 return 1;
1226
1227         if (!(mpvec = vector_alloc()))
1228                 return 1;
1229
1230         /*
1231          * probe for current path (from sysfs) and map (from dm) sets
1232          */
1233         path_discovery(vecs->pathvec, conf, DI_ALL);
1234
1235         vector_foreach_slot (vecs->pathvec, pp, i){
1236                 if (filter_path(conf, pp) > 0){
1237                         vector_del_slot(vecs->pathvec, i);
1238                         free_path(pp);
1239                         i--;
1240                 }
1241                 else
1242                         pp->checkint = conf->checkint;
1243         }
1244         if (map_discovery(vecs))
1245                 return 1;
1246
1247         /*
1248          * create new set of maps & push changed ones into dm
1249          */
1250         if (coalesce_paths(vecs, mpvec, NULL, 1))
1251                 return 1;
1252
1253         /*
1254          * may need to remove some maps which are no longer relevant
1255          * e.g., due to blacklist changes in conf file
1256          */
1257         if (coalesce_maps(vecs, mpvec))
1258                 return 1;
1259
1260         dm_lib_release();
1261
1262         sync_maps_state(mpvec);
1263
1264         /*
1265          * purge dm of old maps
1266          */
1267         remove_maps(vecs);
1268
1269         /*
1270          * save new set of maps formed by considering current path state
1271          */
1272         vector_free(vecs->mpvec);
1273         vecs->mpvec = mpvec;
1274
1275         /*
1276          * start dm event waiter threads for these new maps
1277          */
1278         vector_foreach_slot(vecs->mpvec, mpp, i) {
1279                 if (setup_multipath(vecs, mpp))
1280                         return 1;
1281                 if (start_waiters)
1282                         if (start_waiter_thread(mpp, vecs))
1283                                 return 1;
1284         }
1285         return 0;
1286 }
1287
1288 int
1289 reconfigure (struct vectors * vecs)
1290 {
1291         struct config * old = conf;
1292         int retval = 1;
1293
1294         lock(vecs->lock);
1295         /*
1296          * free old map and path vectors ... they use old conf state
1297          */
1298         if (VECTOR_SIZE(vecs->mpvec))
1299                 remove_maps_and_stop_waiters(vecs);
1300
1301         if (VECTOR_SIZE(vecs->pathvec))
1302                 free_pathvec(vecs->pathvec, FREE_PATHS);
1303
1304         vecs->pathvec = NULL;
1305         conf = NULL;
1306
1307         if (!load_config(DEFAULT_CONFIGFILE)) {
1308                 conf->verbosity = old->verbosity;
1309                 conf->daemon = 1;
1310                 configure(vecs, 1);
1311                 free_config(old);
1312                 retval = 0;
1313         }
1314
1315         unlock(vecs->lock);
1316         return retval;
1317 }
1318
1319 static struct vectors *
1320 init_vecs (void)
1321 {
1322         struct vectors * vecs;
1323
1324         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1325
1326         if (!vecs)
1327                 return NULL;
1328
1329         vecs->lock.mutex =
1330                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1331
1332         if (!vecs->lock.mutex)
1333                 goto out;
1334
1335         pthread_mutex_init(vecs->lock.mutex, NULL);
1336         vecs->lock.depth = 0;
1337
1338         return vecs;
1339
1340 out:
1341         FREE(vecs);
1342         condlog(0, "failed to init paths");
1343         return NULL;
1344 }
1345
1346 static void *
1347 signal_set(int signo, void (*func) (int))
1348 {
1349         int r;
1350         struct sigaction sig;
1351         struct sigaction osig;
1352
1353         sig.sa_handler = func;
1354         sigemptyset(&sig.sa_mask);
1355         sig.sa_flags = 0;
1356
1357         r = sigaction(signo, &sig, &osig);
1358
1359         if (r < 0)
1360                 return (SIG_ERR);
1361         else
1362                 return (osig.sa_handler);
1363 }
1364
1365 static void
1366 sighup (int sig)
1367 {
1368         condlog(2, "reconfigure (SIGHUP)");
1369
1370         if (running_state != DAEMON_RUNNING)
1371                 return;
1372
1373         reconfigure(gvecs);
1374
1375 #ifdef _DEBUG_
1376         dbg_free_final(NULL);
1377 #endif
1378 }
1379
1380 static void
1381 sigend (int sig)
1382 {
1383         exit_daemon(0);
1384 }
1385
1386 static void
1387 sigusr1 (int sig)
1388 {
1389         condlog(3, "SIGUSR1 received");
1390 }
1391
1392 static void
1393 signal_init(void)
1394 {
1395         signal_set(SIGHUP, sighup);
1396         signal_set(SIGUSR1, sigusr1);
1397         signal_set(SIGINT, sigend);
1398         signal_set(SIGTERM, sigend);
1399         signal(SIGPIPE, SIG_IGN);
1400 }
1401
1402 static void
1403 setscheduler (void)
1404 {
1405         int res;
1406         static struct sched_param sched_param = {
1407                 .sched_priority = 99
1408         };
1409
1410         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1411
1412         if (res == -1)
1413                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1414         return;
1415 }
1416
1417 static void
1418 set_oom_adj (int val)
1419 {
1420         FILE *fp;
1421
1422         fp = fopen("/proc/self/oom_adj", "w");
1423
1424         if (!fp)
1425                 return;
1426
1427         fprintf(fp, "%i", val);
1428         fclose(fp);
1429 }
1430
1431 static int
1432 child (void * param)
1433 {
1434         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1435         pthread_attr_t log_attr, misc_attr;
1436         struct vectors * vecs;
1437         struct multipath * mpp;
1438         int i;
1439         int rc;
1440
1441         mlockall(MCL_CURRENT | MCL_FUTURE);
1442
1443         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1444         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1445
1446         if (logsink) {
1447                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1448                 log_thread_start(&log_attr);
1449                 pthread_attr_destroy(&log_attr);
1450         }
1451
1452         running_state = DAEMON_START;
1453
1454         condlog(2, "--------start up--------");
1455         condlog(2, "read " DEFAULT_CONFIGFILE);
1456
1457         if (load_config(DEFAULT_CONFIGFILE))
1458                 exit(1);
1459
1460         if (init_checkers()) {
1461                 condlog(0, "failed to initialize checkers");
1462                 exit(1);
1463         }
1464         if (init_prio()) {
1465                 condlog(0, "failed to initialize prioritizers");
1466                 exit(1);
1467         }
1468
1469         setlogmask(LOG_UPTO(conf->verbosity + 3));
1470
1471         /*
1472          * fill the voids left in the config file
1473          */
1474         if (!conf->checkint) {
1475                 conf->checkint = DEFAULT_CHECKINT;
1476                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1477         }
1478
1479         if (conf->max_fds) {
1480                 struct rlimit fd_limit;
1481
1482                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1483                         condlog(0, "can't get open fds limit: %s\n",
1484                                 strerror(errno));
1485                         fd_limit.rlim_cur = 0;
1486                         fd_limit.rlim_max = 0;
1487                 }
1488                 if (fd_limit.rlim_cur < conf->max_fds) {
1489                         fd_limit.rlim_cur = conf->max_fds;
1490                         if (fd_limit.rlim_max < conf->max_fds)
1491                                 fd_limit.rlim_max = conf->max_fds;
1492                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1493                                 condlog(0, "can't set open fds limit to "
1494                                         "%lu/%lu : %s\n",
1495                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1496                                         strerror(errno));
1497                         } else {
1498                                 condlog(3, "set open fds limit to %lu/%lu\n",
1499                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1500                         }
1501                 }
1502
1503         }
1504
1505         signal_init();
1506         setscheduler();
1507         set_oom_adj(-16);
1508         vecs = gvecs = init_vecs();
1509
1510         if (!vecs)
1511                 exit(1);
1512
1513         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1514                 condlog(0, "can not find sysfs mount point");
1515                 exit(1);
1516         }
1517         conf->daemon = 1;
1518         udev_set_sync_support(0);
1519         /*
1520          * Start uevent listener early to catch events
1521          */
1522         if ((rc = pthread_create(&uevent_thr, &misc_attr, ueventloop, vecs))) {
1523                 condlog(0, "failed to create uevent thread: %d", rc);
1524                 exit(1);
1525         }
1526         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1527                 condlog(0, "failed to create cli listener: %d", rc);
1528                 exit(1);
1529         }
1530         /*
1531          * fetch and configure both paths and multipaths
1532          */
1533         lock(vecs->lock);
1534         running_state = DAEMON_CONFIGURE;
1535
1536         if (configure(vecs, 1)) {
1537                 unlock(vecs->lock);
1538                 condlog(0, "failure during configuration");
1539                 exit(1);
1540         }
1541         unlock(vecs->lock);
1542
1543         /*
1544          * start threads
1545          */
1546         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1547                 condlog(0,"failed to create checker loop thread: %d", rc);
1548                 exit(1);
1549         }
1550         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1551                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1552                 exit(1);
1553         }
1554         pthread_attr_destroy(&misc_attr);
1555
1556         pthread_mutex_lock(&exit_mutex);
1557         /* Startup complete, create logfile */
1558         if (pidfile_create(DEFAULT_PIDFILE, daemon_pid))
1559                 /* Ignore errors, we can live without */
1560                 condlog(1, "failed to create pidfile");
1561
1562         running_state = DAEMON_RUNNING;
1563         pthread_cond_wait(&exit_cond, &exit_mutex);
1564
1565         /*
1566          * exit path
1567          */
1568         running_state = DAEMON_SHUTDOWN;
1569         block_signal(SIGHUP, NULL);
1570         lock(vecs->lock);
1571         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1572                 vector_foreach_slot(vecs->mpvec, mpp, i)
1573                         dm_queue_if_no_path(mpp->alias, 0);
1574         remove_maps_and_stop_waiters(vecs);
1575         unlock(vecs->lock);
1576
1577         pthread_cancel(check_thr);
1578         pthread_cancel(uevent_thr);
1579         pthread_cancel(uxlsnr_thr);
1580         pthread_cancel(uevq_thr);
1581
1582         sysfs_cleanup();
1583
1584         lock(vecs->lock);
1585         free_pathvec(vecs->pathvec, FREE_PATHS);
1586         vecs->pathvec = NULL;
1587         unlock(vecs->lock);
1588         /* Now all the waitevent threads will start rushing in. */
1589         while (vecs->lock.depth > 0) {
1590                 sleep (1); /* This is weak. */
1591                 condlog(3,"Have %d wait event checkers threads to de-alloc, waiting..\n", vecs->lock.depth);
1592         }
1593         pthread_mutex_destroy(vecs->lock.mutex);
1594         FREE(vecs->lock.mutex);
1595         vecs->lock.depth = 0;
1596         vecs->lock.mutex = NULL;
1597         FREE(vecs);
1598         vecs = NULL;
1599
1600         cleanup_checkers();
1601         cleanup_prio();
1602
1603         dm_lib_release();
1604         dm_lib_exit();
1605
1606         /* We're done here */
1607         condlog(3, "unlink pidfile");
1608         unlink(DEFAULT_PIDFILE);
1609
1610         condlog(2, "--------shut down-------");
1611
1612         if (logsink)
1613                 log_thread_stop();
1614
1615         /*
1616          * Freeing config must be done after condlog() and dm_lib_exit(),
1617          * because logging functions like dlog() and dm_write_log()
1618          * reference the config.
1619          */
1620         free_config(conf);
1621         conf = NULL;
1622
1623 #ifdef _DEBUG_
1624         dbg_free_final(NULL);
1625 #endif
1626
1627         exit(0);
1628 }
1629
1630 static int
1631 daemonize(void)
1632 {
1633         int pid;
1634         int in_fd, out_fd;
1635
1636         if( (pid = fork()) < 0){
1637                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1638                 return -1;
1639         }
1640         else if (pid != 0)
1641                 return pid;
1642
1643         setsid();
1644
1645         if ( (pid = fork()) < 0)
1646                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1647         else if (pid != 0)
1648                 _exit(0);
1649
1650         daemon_pid = getpid();
1651         in_fd = open("/dev/null", O_RDONLY);
1652         if (in_fd < 0){
1653                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1654                         strerror(errno));
1655                 _exit(0);
1656         }
1657         out_fd = open("/dev/console", O_WRONLY);
1658         if (out_fd < 0){
1659                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1660                         strerror(errno));
1661                 _exit(0);
1662         }
1663
1664         close(STDIN_FILENO);
1665         dup(in_fd);
1666         close(STDOUT_FILENO);
1667         dup(out_fd);
1668         close(STDERR_FILENO);
1669         dup(out_fd);
1670
1671         close(in_fd);
1672         close(out_fd);
1673         if (chdir("/") < 0)
1674                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1675
1676         return 0;
1677 }
1678
1679 int
1680 main (int argc, char *argv[])
1681 {
1682         extern char *optarg;
1683         extern int optind;
1684         int arg;
1685         int err;
1686
1687         logsink = 1;
1688         running_state = DAEMON_INIT;
1689         dm_init();
1690
1691         if (getuid() != 0) {
1692                 fprintf(stderr, "need to be root\n");
1693                 exit(1);
1694         }
1695
1696         /* make sure we don't lock any path */
1697         chdir("/");
1698         umask(umask(077) | 022);
1699
1700         conf = alloc_config();
1701
1702         if (!conf)
1703                 exit(1);
1704
1705         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1706         switch(arg) {
1707                 case 'd':
1708                         logsink = 0;
1709                         //debug=1; /* ### comment me out ### */
1710                         break;
1711                 case 'v':
1712                         if (sizeof(optarg) > sizeof(char *) ||
1713                             !isdigit(optarg[0]))
1714                                 exit(1);
1715
1716                         conf->verbosity = atoi(optarg);
1717                         break;
1718                 case 'k':
1719                         uxclnt(optarg);
1720                         exit(0);
1721                 default:
1722                         ;
1723                 }
1724         }
1725         if (optind < argc) {
1726                 char cmd[CMDSIZE];
1727                 char * s = cmd;
1728                 char * c = s;
1729
1730                 while (optind < argc) {
1731                         if (strchr(argv[optind], ' '))
1732                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1733                         else
1734                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1735                         optind++;
1736                 }
1737                 c += snprintf(c, s + CMDSIZE - c, "\n");
1738                 uxclnt(s);
1739                 exit(0);
1740         }
1741
1742         if (!logsink)
1743                 err = 0;
1744         else
1745                 err = daemonize();
1746
1747         if (err < 0)
1748                 /* error */
1749                 exit(1);
1750         else if (err > 0)
1751                 /* parent dies */
1752                 exit(0);
1753         else
1754                 /* child lives */
1755                 return (child(NULL));
1756 }
1757