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