[multipathd] Fix segfault on disappearing paths
[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
16 /*
17  * libcheckers
18  */
19 #include <checkers.h>
20
21 /*
22  * libmultipath
23  */
24 #include <parser.h>
25 #include <vector.h>
26 #include <memory.h>
27 #include <config.h>
28 #include <util.h>
29 #include <hwtable.h>
30 #include <defaults.h>
31 #include <structs.h>
32 #include <callout.h>
33 #include <blacklist.h>
34 #include <structs_vec.h>
35 #include <dmparser.h>
36 #include <devmapper.h>
37 #include <sysfs.h>
38 #include <dict.h>
39 #include <discovery.h>
40 #include <debug.h>
41 #include <propsel.h>
42 #include <uevent.h>
43 #include <switchgroup.h>
44 #include <print.h>
45 #include <configure.h>
46
47 #include "main.h"
48 #include "pidfile.h"
49 #include "uxlsnr.h"
50 #include "uxclnt.h"
51 #include "cli.h"
52 #include "cli_handlers.h"
53 #include "lock.h"
54 #include "waiter.h"
55
56 #define FILE_NAME_SIZE 256
57 #define CMDSIZE 160
58
59 #define LOG_MSG(a,b) \
60         if (strlen(b)) condlog(a, "%s: %s", pp->dev, b);
61
62 pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
63 pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
64
65 /*
66  * global copy of vecs for use in sig handlers
67  */
68 struct vectors * gvecs;
69
70 static int
71 need_switch_pathgroup (struct multipath * mpp, int refresh)
72 {
73         struct pathgroup * pgp;
74         struct path * pp;
75         unsigned int i, j;
76
77         if (!mpp || mpp->pgfailback == -FAILBACK_MANUAL)
78                 return 0;
79
80         /*
81          * Refresh path priority values
82          */
83         if (refresh)
84                 vector_foreach_slot (mpp->pg, pgp, i)
85                         vector_foreach_slot (pgp->paths, pp, j)
86                                 pathinfo(pp, conf->hwtable, DI_PRIO);
87
88         mpp->bestpg = select_path_group(mpp);
89
90         if (mpp->bestpg != mpp->nextpg)
91                 return 1;
92
93         return 0;
94 }
95
96 static void
97 switch_pathgroup (struct multipath * mpp)
98 {
99         mpp->stat_switchgroup++;
100         dm_switchgroup(mpp->alias, mpp->bestpg);
101         condlog(2, "%s: switch to path group #%i",
102                  mpp->alias, mpp->bestpg);
103 }
104
105 static int
106 coalesce_maps(struct vectors *vecs, vector nmpv)
107 {
108         struct multipath * ompp;
109         vector ompv = vecs->mpvec;
110         unsigned int i;
111         int j;
112
113         vector_foreach_slot (ompv, ompp, i) {
114                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
115                         /*
116                          * remove all current maps not allowed by the
117                          * current configuration
118                          */
119                         if (dm_flush_map(ompp->alias, DEFAULT_TARGET)) {
120                                 condlog(0, "%s: unable to flush devmap",
121                                         ompp->alias);
122                                 /*
123                                  * may be just because the device is open
124                                  */
125                                 if (!vector_alloc_slot(nmpv))
126                                         return 1;
127
128                                 vector_set_slot(nmpv, ompp);
129                                 setup_multipath(vecs, ompp);
130
131                                 if ((j = find_slot(ompv, (void *)ompp)) != -1)
132                                         vector_del_slot(ompv, j);
133
134                                 continue;
135                         }
136                         else {
137                                 dm_lib_release();
138                                 condlog(3, "%s devmap removed", ompp->alias);
139                         }
140                 }
141         }
142         return 0;
143 }
144
145 static void
146 sync_map_state(struct multipath *mpp)
147 {
148         struct pathgroup *pgp;
149         struct path *pp;
150         unsigned int i, j;
151
152         vector_foreach_slot (mpp->pg, pgp, i){
153                 vector_foreach_slot (pgp->paths, pp, j){
154                         if (pp->state <= PATH_UNCHECKED)
155                                 continue;
156                         if ((pp->dmstate == PSTATE_FAILED ||
157                              pp->dmstate == PSTATE_UNDEF) &&
158                             (pp->state == PATH_UP || pp->state == PATH_GHOST))
159                                 dm_reinstate_path(mpp->alias, pp->dev_t);
160                         else if ((pp->dmstate == PSTATE_ACTIVE ||
161                                   pp->dmstate == PSTATE_UNDEF) &&
162                                  (pp->state == PATH_DOWN ||
163                                   pp->state == PATH_SHAKY))
164                                 dm_fail_path(mpp->alias, pp->dev_t);
165                 }
166         }
167 }
168
169 static void
170 sync_maps_state(vector mpvec)
171 {
172         unsigned int i;
173         struct multipath *mpp;
174
175         vector_foreach_slot (mpvec, mpp, i) 
176                 sync_map_state(mpp);
177 }
178
179 static int
180 flush_map(struct multipath * mpp, struct vectors * vecs)
181 {
182         /*
183          * clear references to this map before flushing so we can ignore
184          * the spurious uevent we may generate with the dm_flush_map call below
185          */
186         if (dm_flush_map(mpp->alias, DEFAULT_TARGET)) {
187                 /*
188                  * May not really be an error -- if the map was already flushed
189                  * from the device mapper by dmsetup(8) for instance.
190                  */
191                 condlog(0, "%s: can't flush", mpp->alias);
192                 return 1;
193         }
194         else {
195                 dm_lib_release();
196                 condlog(3, "%s: devmap removed", mpp->alias);
197         }
198
199         orphan_paths(vecs->pathvec, mpp);
200         remove_map(mpp, vecs, stop_waiter_thread, 1);
201
202         return 0;
203 }
204
205 static int
206 uev_add_map (struct sysfs_device * dev, struct vectors * vecs)
207 {
208         condlog(2, "%s: add map (uevent)", dev->kernel);
209         return ev_add_map(dev, vecs);
210 }
211
212 int
213 ev_add_map (struct sysfs_device * dev, struct vectors * vecs)
214 {
215         char * alias;
216         char *dev_t;
217         int major, minor;
218         char * refwwid;
219         struct multipath * mpp;
220         int map_present;
221         int r = 1;
222
223         dev_t = sysfs_attr_get_value(dev->devpath, "dev");
224
225         if (!dev_t || sscanf(dev_t, "%d:%d", &major, &minor) != 2)
226                 return 1;
227
228         alias = dm_mapname(major, minor);
229                 
230         if (!alias)
231                 return 1;
232         
233         map_present = dm_map_present(alias);
234
235         if (map_present && dm_type(alias, DEFAULT_TARGET) <= 0) {
236                 condlog(4, "%s: not a multipath map", alias);
237                 return 0;
238         }
239
240         mpp = find_mp_by_alias(vecs->mpvec, alias);
241
242         if (mpp) {
243                 /*
244                  * Not really an error -- we generate our own uevent
245                  * if we create a multipath mapped device as a result
246                  * of uev_add_path
247                  */
248                 condlog(0, "%s: devmap already registered",
249                         dev->kernel);
250                 return 0;
251         }
252
253         /*
254          * now we can register the map
255          */
256         if (map_present && (mpp = add_map_without_path(vecs, minor, alias,
257                                         start_waiter_thread))) {
258                 sync_map_state(mpp);
259                 condlog(3, "%s: devmap %s added", alias, dev->kernel);
260                 return 0;
261         }
262         refwwid = get_refwwid(dev->kernel, DEV_DEVMAP, vecs->pathvec);
263
264         if (refwwid) {
265                 r = coalesce_paths(vecs, NULL, refwwid);
266                 dm_lib_release();
267         }
268         
269         if (!r)
270                 condlog(3, "%s: devmap %s added", alias, dev->kernel);
271         else
272                 condlog(0, "%s: uev_add_map %s failed", alias, dev->kernel);
273
274         FREE(refwwid);
275         return r;
276 }
277
278 static int
279 uev_remove_map (struct sysfs_device * dev, struct vectors * vecs)
280 {
281         condlog(2, "%s: remove map (uevent)", dev->kernel);
282         return ev_remove_map(dev->kernel, vecs);
283 }
284
285 int
286 ev_remove_map (char * devname, struct vectors * vecs)
287 {
288         struct multipath * mpp;
289
290         mpp = find_mp_by_str(vecs->mpvec, devname);
291
292         if (!mpp) {
293                 condlog(3, "%s: devmap not registered, can't remove",
294                         devname);
295                 return 0;
296         }
297         flush_map(mpp, vecs);
298
299         return 0;
300 }
301
302 static int
303 uev_umount_map (struct sysfs_device * dev, struct vectors * vecs)
304 {
305         struct multipath * mpp;
306
307         condlog(2, "%s: umount map (uevent)", dev->kernel);
308
309         mpp = find_mp_by_str(vecs->mpvec, dev->kernel);
310
311         if (!mpp)
312                 return 0;
313
314         update_mpp_paths(mpp, vecs->pathvec);
315         verify_paths(mpp, vecs, NULL);
316
317         if (!VECTOR_SIZE(mpp->paths))
318                 flush_map(mpp, vecs);
319
320         return 0;
321 }
322         
323 static int
324 uev_add_path (struct sysfs_device * dev, struct vectors * vecs)
325 {
326         condlog(2, "%s: add path (uevent)", dev->kernel);
327         return (ev_add_path(dev->kernel, vecs) != 1)? 0 : 1;
328 }
329
330
331 /*
332  * returns:
333  * 0: added
334  * 1: error
335  * 2: blacklisted
336  */
337 int
338 ev_add_path (char * devname, struct vectors * vecs)
339 {
340         struct multipath * mpp;
341         struct path * pp;
342         char empty_buff[WWID_SIZE] = {0};
343
344         pp = find_path_by_dev(vecs->pathvec, devname);
345
346         if (pp) {
347                 condlog(0, "%s: spurious uevent, path already in pathvec",
348                         devname);
349                 if (pp->mpp)
350                         return 0;
351         }
352         else {
353                 /*
354                  * get path vital state
355                  */
356                 if (!(pp = store_pathinfo(vecs->pathvec, conf->hwtable,
357                       devname, DI_ALL))) {
358                         condlog(0, "%s: failed to store path info", devname);
359                         return 1;
360                 }
361                 pp->checkint = conf->checkint;
362         }
363
364         /*
365          * need path UID to go any further
366          */
367         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
368                 condlog(0, "%s: failed to get path uid", devname);
369                 return 1; /* leave path added to pathvec */
370         }
371         if (filter_path(conf, pp)){
372                 int i = find_slot(vecs->pathvec, (void *)pp);
373                 if (i != -1)
374                         vector_del_slot(vecs->pathvec, i);
375                 free_path(pp);
376                 return 2;
377         }       
378         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
379 rescan:
380         if (mpp) {
381                 if (adopt_paths(vecs->pathvec, mpp))
382                         return 1; /* leave path added to pathvec */
383
384                 verify_paths(mpp, vecs, NULL);
385                 mpp->action = ACT_RELOAD;
386         }
387         else {
388                 if ((mpp = add_map_with_path(vecs, pp, 1)))
389                         mpp->action = ACT_CREATE;
390                 else
391                         return 1; /* leave path added to pathvec */
392         }
393
394         /*
395          * push the map to the device-mapper
396          */
397         if (setup_map(mpp)) {
398                 condlog(0, "%s: failed to setup map for addition of new "
399                         "path %s", mpp->alias, devname);
400                 goto out;
401         }
402         /*
403          * reload the map for the multipath mapped device
404          */
405         if (domap(mpp) <= 0) {
406                 condlog(0, "%s: failed in domap for addition of new "
407                         "path %s", mpp->alias, devname);
408                 /*
409                  * deal with asynchronous uevents :((
410                  */
411                 if (mpp->action == ACT_RELOAD) {
412                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
413                         sleep(1);
414                         update_mpp_paths(mpp, vecs->pathvec);
415                         goto rescan;
416                 }
417                 else
418                         goto out;
419         }
420         dm_lib_release();
421
422         /*
423          * update our state from kernel regardless of create or reload
424          */
425         if (setup_multipath(vecs, mpp))
426                 goto out;
427
428         sync_map_state(mpp);
429
430         if (mpp->action == ACT_CREATE &&
431             start_waiter_thread(mpp, vecs))
432                         goto out;
433
434         condlog(3, "%s path added to devmap %s", devname, mpp->alias);
435         return 0;
436
437 out:
438         remove_map(mpp, vecs, NULL, 1);
439         return 1;
440 }
441
442 static int
443 uev_remove_path (struct sysfs_device * dev, struct vectors * vecs)
444 {
445         condlog(2, "%s: remove path (uevent)", dev->kernel);
446         return ev_remove_path(dev->kernel, vecs);
447 }
448
449 int
450 ev_remove_path (char * devname, struct vectors * vecs)
451 {
452         struct multipath * mpp;
453         struct path * pp;
454         int i;
455         int rm_path = 1;
456
457         pp = find_path_by_dev(vecs->pathvec, devname);
458
459         if (!pp) {
460                 condlog(0, "%s: spurious uevent, path not in pathvec", devname);
461                 return 1;
462         }
463
464         /*
465          * avoid referring to the map of an orphanned path
466          */
467         if ((mpp = pp->mpp)) {
468
469                 /*
470                  * remove the map IFF removing the last path
471                  */
472                 if (pathcount(mpp, PATH_WILD) > 1) {
473                         vector rpvec = vector_alloc();
474
475                         /*
476                          * transform the mp->pg vector of vectors of paths
477                          * into a mp->params string to feed the device-mapper
478                          */
479                         update_mpp_paths(mpp, vecs->pathvec);
480                         if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
481                                 vector_del_slot(mpp->paths, i);
482
483                         if (VECTOR_SIZE(mpp->paths) == 0) {
484                                 char alias[WWID_SIZE];
485
486                                 /*
487                                  * flush_map will fail if the device is open
488                                  */
489                                 strncpy(alias, mpp->alias, WWID_SIZE);
490                                 if (flush_map(mpp, vecs))
491                                         rm_path = 0;
492                                 else
493                                         condlog(3, "%s: removed map after removing"
494                                                 " multiple paths", alias);
495                         }
496                         else {
497                                 if (setup_map(mpp)) {
498                                         condlog(0, "%s: failed to setup map for"
499                                                 " removal of path %s", mpp->alias, devname);
500                                         free_pathvec(rpvec, KEEP_PATHS);
501                                         goto out;
502                                 }
503                                 /*
504                                  * reload the map
505                                  */
506                                 mpp->action = ACT_RELOAD;
507                                 if (domap(mpp) <= 0) {
508                                         condlog(0, "%s: failed in domap for "
509                                                 "removal of path %s",
510                                                 mpp->alias, devname);
511                                         /*
512                                          * Delete path from pathvec so that
513                                          * update_mpp_paths wont find it later
514                                          * when/if another path is removed.
515                                          */
516                                         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
517                                                 vector_del_slot(vecs->pathvec, i);
518                                         free_path(pp);
519                                         return 1;
520                                 }
521                                 /*
522                                  * update our state from kernel
523                                  */
524                                 if (setup_multipath(vecs, mpp)) {
525                                         free_pathvec(rpvec, KEEP_PATHS);
526                                         goto out;
527                                 }
528                                 sync_map_state(mpp);
529
530                                 condlog(3, "%s: path removed from map %s",
531                                         devname, mpp->alias);
532                         }
533                         free_pathvec(rpvec, KEEP_PATHS);
534                 }
535                 else {
536                         char alias[WWID_SIZE];
537
538                         /*
539                          * flush_map will fail if the device is open
540                          */
541                         strncpy(alias, mpp->alias, WWID_SIZE);
542                         if (flush_map(mpp, vecs))
543                                 rm_path = 0;
544                         else
545                                 condlog(3, "%s: removed map", alias);
546                 }
547         }
548
549         if (rm_path) {
550                 if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
551                         vector_del_slot(vecs->pathvec, i);
552                 free_path(pp);
553         }
554
555         return 0;
556
557 out:
558         remove_map(mpp, vecs, stop_waiter_thread, 1);
559         return 1;
560 }
561
562 static int
563 map_discovery (struct vectors * vecs)
564 {
565         struct multipath * mpp;
566         unsigned int i;
567
568         if (dm_get_maps(vecs->mpvec, "multipath"))
569                 return 1;
570
571         vector_foreach_slot (vecs->mpvec, mpp, i)
572                 if (setup_multipath(vecs, mpp))
573                         return 1;
574
575         return 0;
576 }
577
578 int
579 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
580 {
581         struct vectors * vecs;
582         int r;
583         
584         *reply = NULL;
585         *len = 0;
586         vecs = (struct vectors *)trigger_data;
587
588         pthread_cleanup_push(cleanup_lock, vecs->lock);
589         lock(vecs->lock);
590
591         r = parse_cmd(str, reply, len, vecs);
592
593         if (r > 0) {
594                 *reply = STRDUP("fail\n");
595                 *len = strlen(*reply) + 1;
596                 r = 1;
597         }
598         else if (!r && *len == 0) {
599                 *reply = STRDUP("ok\n");
600                 *len = strlen(*reply) + 1;
601                 r = 0;
602         }
603         /* else if (r < 0) leave *reply alone */
604
605         lock_cleanup_pop(vecs->lock);
606         return r;
607 }
608
609 static int
610 uev_discard(char * devpath)
611 {
612         char a[10], b[10];
613
614         /*
615          * keep only block devices, discard partitions
616          */
617         if (sscanf(devpath, "/block/%10s", a) != 1 ||
618             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
619                 condlog(4, "discard event on %s", devpath);
620                 return 1;
621         }
622         return 0;
623 }
624
625 int 
626 uev_trigger (struct uevent * uev, void * trigger_data)
627 {
628         int r = 0;
629         struct sysfs_device *sysdev;
630         struct vectors * vecs;
631
632         vecs = (struct vectors *)trigger_data;
633
634         if (uev_discard(uev->devpath))
635                 return 0;
636
637         sysdev = sysfs_device_get(uev->devpath);
638         if(!sysdev)
639                 return 0;       
640
641         lock(vecs->lock);
642
643         /*
644          * device map event
645          * Add events are ignored here as the tables
646          * are not fully initialised then.
647          */
648         if (!strncmp(sysdev->kernel, "dm-", 3)) {
649                 if (!strncmp(uev->action, "change", 6)) {
650                         r = uev_add_map(sysdev, vecs);
651                         goto out;
652                 }
653                 if (!strncmp(uev->action, "remove", 6)) {
654                         r = uev_remove_map(sysdev, vecs);
655                         goto out;
656                 }
657                 if (!strncmp(uev->action, "umount", 6)) {
658                         r = uev_umount_map(sysdev, vecs);
659                         goto out;
660                 }
661                 goto out;
662         }
663         
664         /*
665          * path add/remove event
666          */
667         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
668                            sysdev->kernel) > 0)
669                 goto out;
670
671         if (!strncmp(uev->action, "add", 3)) {
672                 r = uev_add_path(sysdev, vecs);
673                 goto out;
674         }
675         if (!strncmp(uev->action, "remove", 6)) {
676                 r = uev_remove_path(sysdev, vecs);
677                 goto out;
678         }
679
680 out:
681         unlock(vecs->lock);
682         return r;
683 }
684
685 static void *
686 ueventloop (void * ap)
687 {
688         if (uevent_listen(&uev_trigger, ap))
689                 fprintf(stderr, "error starting uevent listener");
690                 
691         return NULL;
692 }
693
694 static void *
695 uxlsnrloop (void * ap)
696 {
697         if (cli_init())
698                 return NULL;
699
700         set_handler_callback(LIST+PATHS, cli_list_paths);
701         set_handler_callback(LIST+MAPS, cli_list_maps);
702         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
703         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
704         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
705         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
706         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
707         set_handler_callback(LIST+CONFIG, cli_list_config);
708         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
709         set_handler_callback(LIST+DEVICES, cli_list_devices);
710         set_handler_callback(ADD+PATH, cli_add_path);
711         set_handler_callback(DEL+PATH, cli_del_path);
712         set_handler_callback(ADD+MAP, cli_add_map);
713         set_handler_callback(DEL+MAP, cli_del_map);
714         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
715         set_handler_callback(RECONFIGURE, cli_reconfigure);
716         set_handler_callback(SUSPEND+MAP, cli_suspend);
717         set_handler_callback(RESUME+MAP, cli_resume);
718         set_handler_callback(REINSTATE+PATH, cli_reinstate);
719         set_handler_callback(FAIL+PATH, cli_fail);
720
721         uxsock_listen(&uxsock_trigger, ap);
722
723         return NULL;
724 }
725
726 static int
727 exit_daemon (int status)
728 {
729         if (status != 0)
730                 fprintf(stderr, "bad exit status. see daemon.log\n");
731
732         condlog(3, "unlink pidfile");
733         unlink(DEFAULT_PIDFILE);
734
735         lock(&exit_mutex);
736         pthread_cond_signal(&exit_cond);
737         unlock(&exit_mutex);
738
739         return status;
740 }
741
742 static void
743 fail_path (struct path * pp, int del_active)
744 {
745         if (!pp->mpp)
746                 return;
747
748         condlog(2, "checker failed path %s in map %s",
749                  pp->dev_t, pp->mpp->alias);
750
751         dm_fail_path(pp->mpp->alias, pp->dev_t);
752         if (del_active)
753                 update_queue_mode_del_path(pp->mpp);
754 }
755
756 /*
757  * caller must have locked the path list before calling that function
758  */
759 static void
760 reinstate_path (struct path * pp, int add_active)
761 {
762         if (!pp->mpp)
763                 return;
764
765         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
766                 condlog(0, "%s: reinstate failed", pp->dev_t);
767         else {
768                 condlog(2, "%s: reinstated", pp->dev_t);
769                 if (add_active)
770                         update_queue_mode_add_path(pp->mpp);
771         }
772 }
773
774 static void
775 enable_group(struct path * pp)
776 {
777         struct pathgroup * pgp;
778
779         /*
780          * if path is added through uev_add_path, pgindex can be unset.
781          * next update_strings() will set it, upon map reload event.
782          *
783          * we can safely return here, because upon map reload, all
784          * PG will be enabled.
785          */
786         if (!pp->mpp->pg || !pp->pgindex)
787                 return;
788
789         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
790         
791         if (pgp->status == PGSTATE_DISABLED) {
792                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
793                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
794         }
795 }
796
797 static void
798 mpvec_garbage_collector (struct vectors * vecs)
799 {
800         struct multipath * mpp;
801         unsigned int i;
802
803         vector_foreach_slot (vecs->mpvec, mpp, i) {
804                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
805                         condlog(2, "%s: remove dead map", mpp->alias);
806                         remove_map(mpp, vecs, stop_waiter_thread, 1);
807                         i--;
808                 }
809         }
810 }
811
812 static void
813 defered_failback_tick (vector mpvec)
814 {
815         struct multipath * mpp;
816         unsigned int i;
817
818         vector_foreach_slot (mpvec, mpp, i) {
819                 /*
820                  * defered failback getting sooner
821                  */
822                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
823                         mpp->failback_tick--;
824
825                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
826                                 switch_pathgroup(mpp);
827                 }
828         }
829 }
830
831 static void
832 retry_count_tick(vector mpvec)
833 {
834         struct multipath *mpp;
835         unsigned int i;
836
837         vector_foreach_slot (mpvec, mpp, i) {
838                 if (mpp->retry_tick) {
839                         mpp->stat_total_queueing_time++;
840                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
841                         if(--mpp->retry_tick == 0) {
842                                 dm_queue_if_no_path(mpp->alias, 0);
843                                 condlog(2, "%s: Disable queueing", mpp->alias);
844                         }
845                 }
846         }
847 }
848
849 static void *
850 checkerloop (void *ap)
851 {
852         struct vectors *vecs;
853         struct path *pp;
854         int count = 0;
855         int newstate;
856         unsigned int i;
857
858         mlockall(MCL_CURRENT | MCL_FUTURE);
859         vecs = (struct vectors *)ap;
860         condlog(2, "path checkers start up");
861
862         /*
863          * init the path check interval
864          */
865         vector_foreach_slot (vecs->pathvec, pp, i) {
866                 pp->checkint = conf->checkint;
867         }
868
869         while (1) {
870                 pthread_cleanup_push(cleanup_lock, vecs->lock);
871                 lock(vecs->lock);
872                 condlog(4, "tick");
873
874                 vector_foreach_slot (vecs->pathvec, pp, i) {
875                         if (!pp->mpp)
876                                 continue;
877
878                         if (pp->tick && --pp->tick)
879                                 continue; /* don't check this path yet */
880
881                         /*
882                          * provision a next check soonest,
883                          * in case we exit abnormaly from here
884                          */
885                         pp->tick = conf->checkint;
886                         
887                         if (!checker_selected(&pp->checker)) {
888                                 pathinfo(pp, conf->hwtable, DI_SYSFS);
889                                 select_checker(pp);
890                         }
891
892                         if (!checker_selected(&pp->checker)) {
893                                 condlog(0, "%s: checker is not set", pp->dev);
894                                 continue;
895                         }
896                         newstate = checker_check(&pp->checker);
897                         
898                         if (newstate < 0) {
899                                 condlog(2, "%s: unusable path", pp->dev);
900                                 pathinfo(pp, conf->hwtable, 0);
901                                 continue;
902                         }
903
904                         if (newstate != pp->state) {
905                                 int oldstate = pp->state;
906                                 pp->state = newstate;
907                                 LOG_MSG(1, checker_message(&pp->checker));
908
909                                 /*
910                                  * upon state change, reset the checkint
911                                  * to the shortest delay
912                                  */
913                                 pp->checkint = conf->checkint;
914
915                                 if (newstate == PATH_DOWN ||
916                                     newstate == PATH_SHAKY ||
917                                     update_multipath_strings(pp->mpp,
918                                                              vecs->pathvec)) {
919                                         /*
920                                          * proactively fail path in the DM
921                                          */
922                                         if (oldstate == PATH_UP ||
923                                             oldstate == PATH_GHOST)
924                                                 fail_path(pp, 1);
925                                         else
926                                                 fail_path(pp, 0);
927
928                                         /*
929                                          * cancel scheduled failback
930                                          */
931                                         pp->mpp->failback_tick = 0;
932
933                                         pp->mpp->stat_path_failures++;
934                                         continue;
935                                 }
936
937                                 /*
938                                  * reinstate this path
939                                  */
940                                 if (oldstate != PATH_UP &&
941                                     oldstate != PATH_GHOST)
942                                         reinstate_path(pp, 1);
943                                 else
944                                         reinstate_path(pp, 0);
945
946                                 /*
947                                  * schedule [defered] failback
948                                  */
949                                 if (pp->mpp->pgfailback > 0)
950                                         pp->mpp->failback_tick =
951                                                 pp->mpp->pgfailback + 1;
952                                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
953                                     need_switch_pathgroup(pp->mpp, 1))
954                                         switch_pathgroup(pp->mpp);
955
956                                 /*
957                                  * if at least one path is up in a group, and
958                                  * the group is disabled, re-enable it
959                                  */
960                                 if (newstate == PATH_UP)
961                                         enable_group(pp);
962                         }
963                         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
964                                 LOG_MSG(4, checker_message(&pp->checker));
965                                 /*
966                                  * double the next check delay.
967                                  * max at conf->max_checkint
968                                  */
969                                 if (pp->checkint < (conf->max_checkint / 2))
970                                         pp->checkint = 2 * pp->checkint;
971                                 else
972                                         pp->checkint = conf->max_checkint;
973
974                                 pp->tick = pp->checkint;
975                                 condlog(4, "%s: delay next check %is",
976                                                 pp->dev_t, pp->tick);
977                         }
978                         else if (newstate == PATH_DOWN)
979                                 LOG_MSG(2, checker_message(&pp->checker));
980
981                         pp->state = newstate;
982
983                         /*
984                          * path prio refreshing
985                          */
986                         condlog(4, "path prio refresh");
987                         pathinfo(pp, conf->hwtable, DI_PRIO);
988
989                         if (need_switch_pathgroup(pp->mpp, 0)) {
990                                 if (pp->mpp->pgfailback > 0 &&
991                                     pp->mpp->failback_tick <= 0)
992                                         pp->mpp->failback_tick =
993                                                 pp->mpp->pgfailback + 1;
994                                 else if (pp->mpp->pgfailback ==
995                                                 -FAILBACK_IMMEDIATE)
996                                         switch_pathgroup(pp->mpp);
997                         }
998                 }
999                 defered_failback_tick(vecs->mpvec);
1000                 retry_count_tick(vecs->mpvec);
1001
1002                 if (count)
1003                         count--;
1004                 else {
1005                         condlog(4, "map garbage collection");
1006                         mpvec_garbage_collector(vecs);
1007                         count = MAPGCINT;
1008                 }
1009                 
1010                 lock_cleanup_pop(vecs->lock);
1011                 sleep(1);
1012         }
1013         return NULL;
1014 }
1015
1016 int
1017 configure (struct vectors * vecs, int start_waiters)
1018 {
1019         struct multipath * mpp;
1020         struct path * pp;
1021         vector mpvec;
1022         int i;
1023
1024         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1025                 return 1;
1026         
1027         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1028                 return 1;
1029         
1030         if (!(mpvec = vector_alloc()))
1031                 return 1;
1032
1033         /*
1034          * probe for current path (from sysfs) and map (from dm) sets
1035          */
1036         path_discovery(vecs->pathvec, conf, DI_ALL);
1037
1038         vector_foreach_slot (vecs->pathvec, pp, i){
1039                 if (filter_path(conf, pp)){
1040                         vector_del_slot(vecs->pathvec, i);
1041                         free_path(pp);
1042                         i--;
1043                 }       
1044                 else
1045                         pp->checkint = conf->checkint;
1046         }
1047         if (map_discovery(vecs))
1048                 return 1;
1049
1050         /*
1051          * create new set of maps & push changed ones into dm
1052          */
1053         if (coalesce_paths(vecs, mpvec, NULL))
1054                 return 1;
1055
1056         /*
1057          * may need to remove some maps which are no longer relevant
1058          * e.g., due to blacklist changes in conf file
1059          */
1060         if (coalesce_maps(vecs, mpvec))
1061                 return 1;
1062
1063         dm_lib_release();
1064
1065         sync_maps_state(mpvec);
1066
1067         /*
1068          * purge dm of old maps
1069          */
1070         remove_maps(vecs, NULL);
1071
1072         /*
1073          * save new set of maps formed by considering current path state
1074          */
1075         vector_free(vecs->mpvec);
1076         vecs->mpvec = mpvec;
1077
1078         /*
1079          * start dm event waiter threads for these new maps
1080          */
1081         vector_foreach_slot(vecs->mpvec, mpp, i) {
1082                 if (setup_multipath(vecs, mpp))
1083                         return 1;
1084                 if (start_waiters)
1085                         if (start_waiter_thread(mpp, vecs))
1086                                 return 1;
1087         }
1088         return 0;
1089 }
1090
1091 int
1092 reconfigure (struct vectors * vecs)
1093 {
1094         struct config * old = conf;
1095
1096         /*
1097          * free old map and path vectors ... they use old conf state
1098          */
1099         if (VECTOR_SIZE(vecs->mpvec))
1100                 remove_maps(vecs, stop_waiter_thread);
1101
1102         if (VECTOR_SIZE(vecs->pathvec))
1103                 free_pathvec(vecs->pathvec, FREE_PATHS);
1104
1105         vecs->pathvec = NULL;
1106         conf = NULL;
1107
1108         if (load_config(DEFAULT_CONFIGFILE))
1109                 return 1;
1110
1111         conf->verbosity = old->verbosity;
1112
1113         if (!conf->checkint) {
1114                 conf->checkint = DEFAULT_CHECKINT;
1115                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1116         }
1117         configure(vecs, 1);
1118         free_config(old);
1119         return 0;
1120 }
1121
1122 static struct vectors *
1123 init_vecs (void)
1124 {
1125         struct vectors * vecs;
1126
1127         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1128
1129         if (!vecs)
1130                 return NULL;
1131
1132         vecs->lock = 
1133                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1134
1135         if (!vecs->lock)
1136                 goto out;
1137
1138         pthread_mutex_init(vecs->lock, NULL);
1139
1140         return vecs;
1141
1142 out:
1143         FREE(vecs);
1144         condlog(0, "failed to init paths");
1145         return NULL;
1146 }
1147
1148 static void *
1149 signal_set(int signo, void (*func) (int))
1150 {
1151         int r;
1152         struct sigaction sig;
1153         struct sigaction osig;
1154
1155         sig.sa_handler = func;
1156         sigemptyset(&sig.sa_mask);
1157         sig.sa_flags = 0;
1158
1159         r = sigaction(signo, &sig, &osig);
1160
1161         if (r < 0)
1162                 return (SIG_ERR);
1163         else
1164                 return (osig.sa_handler);
1165 }
1166
1167 static void
1168 sighup (int sig)
1169 {
1170         condlog(2, "reconfigure (SIGHUP)");
1171
1172         lock(gvecs->lock);
1173         reconfigure(gvecs);
1174         unlock(gvecs->lock);
1175
1176 #ifdef _DEBUG_
1177         dbg_free_final(NULL);
1178 #endif
1179 }
1180
1181 static void
1182 sigend (int sig)
1183 {
1184         exit_daemon(0);
1185 }
1186
1187 static void
1188 sigusr1 (int sig)
1189 {
1190         condlog(3, "SIGUSR1 received");
1191 }
1192
1193 static void
1194 signal_init(void)
1195 {
1196         signal_set(SIGHUP, sighup);
1197         signal_set(SIGUSR1, sigusr1);
1198         signal_set(SIGINT, sigend);
1199         signal_set(SIGTERM, sigend);
1200         signal(SIGPIPE, SIG_IGN);
1201 }
1202
1203 static void
1204 setscheduler (void)
1205 {
1206         int res;
1207         static struct sched_param sched_param = {
1208                 .sched_priority = 99
1209         };
1210
1211         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1212
1213         if (res == -1)
1214                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1215         return;
1216 }
1217
1218 static void
1219 set_oom_adj (int val)
1220 {
1221         FILE *fp;
1222
1223         fp = fopen("/proc/self/oom_adj", "w");
1224
1225         if (!fp)
1226                 return;
1227
1228         fprintf(fp, "%i", val);
1229         fclose(fp);
1230 }
1231         
1232 static int
1233 child (void * param)
1234 {
1235         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1236         pthread_attr_t attr;
1237         struct vectors * vecs;
1238
1239         mlockall(MCL_CURRENT | MCL_FUTURE);
1240
1241         if (logsink)
1242                 log_thread_start();
1243
1244         condlog(2, "--------start up--------");
1245         condlog(2, "read " DEFAULT_CONFIGFILE);
1246
1247         if (load_config(DEFAULT_CONFIGFILE))
1248                 exit(1);
1249
1250         setlogmask(LOG_UPTO(conf->verbosity + 3));
1251
1252         /*
1253          * fill the voids left in the config file
1254          */
1255         if (!conf->checkint) {
1256                 conf->checkint = DEFAULT_CHECKINT;
1257                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1258         }
1259
1260         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1261                 if (logsink)
1262                         log_thread_stop();
1263
1264                 exit(1);
1265         }
1266         signal_init();
1267         setscheduler();
1268         set_oom_adj(-16);
1269         vecs = gvecs = init_vecs();
1270
1271         if (!vecs)
1272                 exit(1);
1273
1274         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1275                 condlog(0, "can not find sysfs mount point");
1276                 exit(1);
1277         }
1278
1279         /*
1280          * fetch and configure both paths and multipaths
1281          */
1282         if (configure(vecs, 1)) {
1283                 condlog(0, "failure during configuration");
1284                 exit(1);
1285         }
1286
1287         /*
1288          * start threads
1289          */
1290         pthread_attr_init(&attr);
1291         pthread_attr_setstacksize(&attr, 64 * 1024);
1292         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1293         
1294         pthread_create(&check_thr, &attr, checkerloop, vecs);
1295         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1296         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1297
1298         pthread_cond_wait(&exit_cond, &exit_mutex);
1299
1300         /*
1301          * exit path
1302          */
1303         lock(vecs->lock);
1304         remove_maps(vecs, stop_waiter_thread);
1305         free_pathvec(vecs->pathvec, FREE_PATHS);
1306
1307         pthread_cancel(check_thr);
1308         pthread_cancel(uevent_thr);
1309         pthread_cancel(uxlsnr_thr);
1310
1311         sysfs_cleanup();
1312
1313         free_keys(keys);
1314         keys = NULL;
1315         free_handlers(handlers);
1316         handlers = NULL;
1317         free_polls();
1318
1319         unlock(vecs->lock);
1320         pthread_mutex_destroy(vecs->lock);
1321         FREE(vecs->lock);
1322         vecs->lock = NULL;
1323         FREE(vecs);
1324         vecs = NULL;
1325         free_config(conf);
1326         conf = NULL;
1327
1328         condlog(2, "--------shut down-------");
1329         
1330         if (logsink)
1331                 log_thread_stop();
1332
1333         dm_lib_release();
1334         dm_lib_exit();
1335
1336 #ifdef _DEBUG_
1337         dbg_free_final(NULL);
1338 #endif
1339
1340         exit(0);
1341 }
1342
1343 static int
1344 daemonize(void)
1345 {
1346         int pid;
1347         int in_fd, out_fd;
1348
1349         if( (pid = fork()) < 0){
1350                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1351                 return -1;
1352         }
1353         else if (pid != 0)
1354                 return pid;
1355
1356         setsid();
1357
1358         if ( (pid = fork()) < 0)
1359                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1360         else if (pid != 0)
1361                 _exit(0);
1362
1363         in_fd = open("/dev/null", O_RDONLY);
1364         if (in_fd < 0){
1365                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1366                         strerror(errno));
1367                 _exit(0);
1368         }
1369         out_fd = open("/dev/console", O_WRONLY);
1370         if (out_fd < 0){
1371                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1372                         strerror(errno));
1373                 _exit(0);
1374         }
1375
1376         close(STDIN_FILENO);
1377         dup(in_fd);
1378         close(STDOUT_FILENO);
1379         dup(out_fd);
1380         close(STDERR_FILENO);
1381         dup(out_fd);
1382
1383         close(in_fd);
1384         close(out_fd);
1385         chdir("/");
1386         umask(0);
1387         return 0;
1388 }
1389
1390 int
1391 main (int argc, char *argv[])
1392 {
1393         extern char *optarg;
1394         extern int optind;
1395         int arg;
1396         int err;
1397         
1398         logsink = 1;
1399         dm_init();
1400
1401         if (getuid() != 0) {
1402                 fprintf(stderr, "need to be root\n");
1403                 exit(1);
1404         }
1405
1406         /* make sure we don't lock any path */
1407         chdir("/");
1408         umask(umask(077) | 022);
1409
1410         conf = alloc_config();
1411
1412         if (!conf)
1413                 exit(1);
1414
1415         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1416         switch(arg) {
1417                 case 'd':
1418                         logsink = 0;
1419                         //debug=1; /* ### comment me out ### */
1420                         break;
1421                 case 'v':
1422                         if (sizeof(optarg) > sizeof(char *) ||
1423                             !isdigit(optarg[0]))
1424                                 exit(1);
1425
1426                         conf->verbosity = atoi(optarg);
1427                         break;
1428                 case 'k':
1429                         uxclnt(optarg);
1430                         exit(0);
1431                 default:
1432                         ;
1433                 }
1434         }
1435
1436         if (!logsink)
1437                 err = 0;
1438         else
1439                 err = daemonize();
1440         
1441         if (err < 0)
1442                 /* error */
1443                 exit(1);
1444         else if (err > 0)
1445                 /* parent dies */
1446                 exit(0);
1447         else
1448                 /* child lives */
1449                 return (child(NULL));
1450 }
1451