[libmultipath] blacklist exceptions
[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         if (sscanf(devname, "dm-%d", &minor) == 1 &&
229             !sysfs_get_dev(sysfs_path, devname, dev_t, BLK_DEV_SIZE) &&
230             sscanf(dev_t, "%d:%d", &major, &minor) == 2)
231                 alias = dm_mapname(major, minor);
232         else
233                 alias = STRDUP(devname);
234                 
235         if (!alias)
236                 return 1;
237         
238         map_present = dm_map_present(alias);
239
240         if (map_present && dm_type(alias, DEFAULT_TARGET) <= 0) {
241                 condlog(4, "%s: not a multipath map", alias);
242                 FREE(alias);
243                 return 0;
244         }
245
246         mpp = find_mp_by_alias(vecs->mpvec, alias);
247
248         if (mpp) {
249                 /*
250                  * Not really an error -- we generate our own uevent
251                  * if we create a multipath mapped device as a result
252                  * of uev_add_path
253                  */
254                 condlog(0, "%s: devmap already registered",
255                         devname);
256                 FREE(alias);
257                 return 0;
258         }
259
260         /*
261          * now we can register the map
262          */
263         if (map_present && (mpp = add_map_without_path(vecs, minor, alias,
264                                         start_waiter_thread))) {
265                 sync_map_state(mpp);
266                 condlog(3, "%s: devmap %s added", alias, devname);
267                 return 0;
268         }
269         refwwid = get_refwwid(devname, DEV_DEVMAP, vecs->pathvec);
270
271         if (refwwid) {
272                 r = coalesce_paths(vecs, NULL, refwwid);
273                 dm_lib_release();
274         }
275         
276         if (!r)
277                 condlog(3, "%s: devmap %s added", alias, devname);
278         else
279                 condlog(0, "%s: uev_add_map %s failed", alias, devname);
280
281         FREE(refwwid);
282         FREE(alias);
283         return r;
284 }
285
286 static int
287 uev_remove_map (char * devname, struct vectors * vecs)
288 {
289         condlog(2, "%s: remove map (uevent)", devname);
290         return ev_remove_map(devname, vecs);
291 }
292
293 int
294 ev_remove_map (char * devname, struct vectors * vecs)
295 {
296         struct multipath * mpp;
297
298         mpp = find_mp_by_str(vecs->mpvec, devname);
299
300         if (!mpp) {
301                 condlog(3, "%s: devmap not registered, can't remove",
302                         devname);
303                 return 0;
304         }
305         flush_map(mpp, vecs);
306
307         return 0;
308 }
309
310 static int
311 uev_umount_map (char * devname, struct vectors * vecs)
312 {
313         struct multipath * mpp;
314
315         condlog(2, "%s: umount map (uevent)", devname);
316
317         mpp = find_mp_by_str(vecs->mpvec, devname);
318
319         if (!mpp)
320                 return 0;
321
322         update_mpp_paths(mpp, vecs->pathvec);
323         verify_paths(mpp, vecs, NULL);
324
325         if (!VECTOR_SIZE(mpp->paths))
326                 flush_map(mpp, vecs);
327
328         return 0;
329 }
330         
331 static int
332 uev_add_path (char * devname, struct vectors * vecs)
333 {
334         condlog(2, "%s: add path (uevent)", devname);
335         return (ev_add_path(devname, vecs) != 1)? 0 : 1;
336 }
337
338
339 /*
340  * returns:
341  * 0: added
342  * 1: error
343  * 2: blacklisted
344  */
345 int
346 ev_add_path (char * devname, struct vectors * vecs)
347 {
348         struct multipath * mpp;
349         struct path * pp;
350         char empty_buff[WWID_SIZE] = {0};
351
352         pp = find_path_by_dev(vecs->pathvec, devname);
353
354         if (pp) {
355                 condlog(0, "%s: spurious uevent, path already in pathvec",
356                         devname);
357                 if (pp->mpp)
358                         return 0;
359         }
360         else {
361                 /*
362                  * get path vital state
363                  */
364                 if (!(pp = store_pathinfo(vecs->pathvec, conf->hwtable,
365                       devname, DI_ALL))) {
366                         condlog(0, "%s: failed to store path info", devname);
367                         return 1;
368                 }
369                 pp->checkint = conf->checkint;
370         }
371
372         /*
373          * need path UID to go any further
374          */
375         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
376                 condlog(0, "%s: failed to get path uid", devname);
377                 return 1; /* leave path added to pathvec */
378         }
379         if (blacklist_path(conf, pp)){
380                 int i = find_slot(vecs->pathvec, (void *)pp);
381                 if (i != -1)
382                         vector_del_slot(vecs->pathvec, i);
383                 free_path(pp);
384                 return 2;
385         }       
386         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
387 rescan:
388         if (mpp) {
389                 if (adopt_paths(vecs->pathvec, mpp))
390                         return 1; /* leave path added to pathvec */
391
392                 verify_paths(mpp, vecs, NULL);
393                 mpp->action = ACT_RELOAD;
394         }
395         else {
396                 if ((mpp = add_map_with_path(vecs, pp, 1)))
397                         mpp->action = ACT_CREATE;
398                 else
399                         return 1; /* leave path added to pathvec */
400         }
401
402         /*
403          * push the map to the device-mapper
404          */
405         if (setup_map(mpp)) {
406                 condlog(0, "%s: failed to setup map for addition of new "
407                         "path %s", mpp->alias, devname);
408                 goto out;
409         }
410         /*
411          * reload the map for the multipath mapped device
412          */
413         if (domap(mpp) <= 0) {
414                 condlog(0, "%s: failed in domap for addition of new "
415                         "path %s", mpp->alias, devname);
416                 /*
417                  * deal with asynchronous uevents :((
418                  */
419                 if (mpp->action == ACT_RELOAD) {
420                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
421                         sleep(1);
422                         update_mpp_paths(mpp, vecs->pathvec);
423                         goto rescan;
424                 }
425                 else
426                         goto out;
427         }
428         dm_lib_release();
429
430         /*
431          * update our state from kernel regardless of create or reload
432          */
433         if (setup_multipath(vecs, mpp))
434                 goto out;
435
436         sync_map_state(mpp);
437
438         if (mpp->action == ACT_CREATE &&
439             start_waiter_thread(mpp, vecs))
440                         goto out;
441
442         condlog(3, "%s path added to devmap %s", devname, mpp->alias);
443         return 0;
444
445 out:
446         remove_map(mpp, vecs, NULL, 1);
447         return 1;
448 }
449
450 static int
451 uev_remove_path (char * devname, struct vectors * vecs)
452 {
453         condlog(2, "%s: remove path (uevent)", devname);
454         return ev_remove_path(devname, vecs);
455 }
456
457 int
458 ev_remove_path (char * devname, struct vectors * vecs)
459 {
460         struct multipath * mpp;
461         struct path * pp;
462         int i;
463         int rm_path = 1;
464
465         pp = find_path_by_dev(vecs->pathvec, devname);
466
467         if (!pp) {
468                 condlog(0, "%s: spurious uevent, path not in pathvec", devname);
469                 return 1;
470         }
471
472         /*
473          * avoid referring to the map of an orphanned path
474          */
475         if ((mpp = pp->mpp)) {
476
477                 /*
478                  * remove the map IFF removing the last path
479                  */
480                 if (pathcount(mpp, PATH_WILD) > 1) {
481                         vector rpvec = vector_alloc();
482
483                         /*
484                          * transform the mp->pg vector of vectors of paths
485                          * into a mp->params string to feed the device-mapper
486                          */
487                         update_mpp_paths(mpp, vecs->pathvec);
488                         if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
489                                 vector_del_slot(mpp->paths, i);
490
491                         if (VECTOR_SIZE(mpp->paths) == 0) {
492                                 char alias[WWID_SIZE];
493
494                                 /*
495                                  * flush_map will fail if the device is open
496                                  */
497                                 strncpy(alias, mpp->alias, WWID_SIZE);
498                                 if (flush_map(mpp, vecs))
499                                         rm_path = 0;
500                                 else
501                                         condlog(3, "%s: removed map after removing"
502                                                 " multiple paths", alias);
503                         }
504                         else {
505                                 if (setup_map(mpp)) {
506                                         condlog(0, "%s: failed to setup map for"
507                                                 " removal of path %s", mpp->alias, devname);
508                                         free_pathvec(rpvec, KEEP_PATHS);
509                                         goto out;
510                                 }
511                                 /*
512                                  * reload the map
513                                  */
514                                 mpp->action = ACT_RELOAD;
515                                 if (domap(mpp) <= 0) {
516                                         condlog(0, "%s: failed in domap for "
517                                                 "removal of path %s",
518                                                 mpp->alias, devname);
519                                         /*
520                                          * Delete path from pathvec so that
521                                          * update_mpp_paths wont find it later
522                                          * when/if another path is removed.
523                                          */
524                                         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
525                                                 vector_del_slot(vecs->pathvec, i);
526                                         free_path(pp);
527                                         return 1;
528                                 }
529                                 /*
530                                  * update our state from kernel
531                                  */
532                                 if (setup_multipath(vecs, mpp)) {
533                                         free_pathvec(rpvec, KEEP_PATHS);
534                                         goto out;
535                                 }
536                                 sync_map_state(mpp);
537
538                                 condlog(3, "%s: path removed from map %s",
539                                         devname, mpp->alias);
540                         }
541                         free_pathvec(rpvec, KEEP_PATHS);
542                 }
543                 else {
544                         char alias[WWID_SIZE];
545
546                         /*
547                          * flush_map will fail if the device is open
548                          */
549                         strncpy(alias, mpp->alias, WWID_SIZE);
550                         if (flush_map(mpp, vecs))
551                                 rm_path = 0;
552                         else
553                                 condlog(3, "%s: removed map", alias);
554                 }
555         }
556
557         if (rm_path) {
558                 if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
559                         vector_del_slot(vecs->pathvec, i);
560                 free_path(pp);
561         }
562
563         return 0;
564
565 out:
566         remove_map(mpp, vecs, stop_waiter_thread, 1);
567         return 1;
568 }
569
570 static int
571 map_discovery (struct vectors * vecs)
572 {
573         struct multipath * mpp;
574         unsigned int i;
575
576         if (dm_get_maps(vecs->mpvec, "multipath"))
577                 return 1;
578
579         vector_foreach_slot (vecs->mpvec, mpp, i)
580                 if (setup_multipath(vecs, mpp))
581                         return 1;
582
583         return 0;
584 }
585
586 int
587 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
588 {
589         struct vectors * vecs;
590         int r;
591         
592         *reply = NULL;
593         *len = 0;
594         vecs = (struct vectors *)trigger_data;
595
596         pthread_cleanup_push(cleanup_lock, vecs->lock);
597         lock(vecs->lock);
598
599         r = parse_cmd(str, reply, len, vecs);
600
601         if (r > 0) {
602                 *reply = STRDUP("fail\n");
603                 *len = strlen(*reply) + 1;
604                 r = 1;
605         }
606         else if (!r && *len == 0) {
607                 *reply = STRDUP("ok\n");
608                 *len = strlen(*reply) + 1;
609                 r = 0;
610         }
611         /* else if (r < 0) leave *reply alone */
612
613         lock_cleanup_pop(vecs->lock);
614         return r;
615 }
616
617 static int
618 uev_discard(char * devpath)
619 {
620         char a[10], b[10];
621
622         /*
623          * keep only block devices, discard partitions
624          */
625         if (sscanf(devpath, "/block/%10s", a) != 1 ||
626             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
627                 condlog(4, "discard event on %s", devpath);
628                 return 1;
629         }
630         return 0;
631 }
632
633 int 
634 uev_trigger (struct uevent * uev, void * trigger_data)
635 {
636         int r = 0;
637         char devname[32];
638         struct vectors * vecs;
639
640         vecs = (struct vectors *)trigger_data;
641
642         if (uev_discard(uev->devpath))
643                 return 0;
644
645         basename(uev->devpath, devname);
646         lock(vecs->lock);
647
648         /*
649          * device map add/remove event
650          */
651         if (!strncmp(devname, "dm-", 3)) {
652                 if (!strncmp(uev->action, "add", 3)) {
653                         r = uev_add_map(devname, vecs);
654                         goto out;
655                 }
656                 if (!strncmp(uev->action, "remove", 6)) {
657                         r = uev_remove_map(devname, vecs);
658                         goto out;
659                 }
660                 if (!strncmp(uev->action, "umount", 6)) {
661                         r = uev_umount_map(devname, vecs);
662                         goto out;
663                 }
664                 goto out;
665         }
666         
667         /*
668          * path add/remove event
669          */
670         if (blacklist(conf->blist_devnode, conf->elist_devnode, devname))
671                 goto out;
672
673         if (!strncmp(uev->action, "add", 3)) {
674                 r = uev_add_path(devname, vecs);
675                 goto out;
676         }
677         if (!strncmp(uev->action, "remove", 6)) {
678                 r = uev_remove_path(devname, vecs);
679                 goto out;
680         }
681
682 out:
683         unlock(vecs->lock);
684         return r;
685 }
686
687 static void *
688 ueventloop (void * ap)
689 {
690         if (uevent_listen(&uev_trigger, ap))
691                 fprintf(stderr, "error starting uevent listener");
692                 
693         return NULL;
694 }
695
696 static void *
697 uxlsnrloop (void * ap)
698 {
699         if (load_keys())
700                 return NULL;
701         
702         if (alloc_handlers())
703                 return NULL;
704
705         add_handler(LIST+PATHS, cli_list_paths);
706         add_handler(LIST+MAPS, cli_list_maps);
707         add_handler(LIST+MAPS+STATUS, cli_list_maps_status);
708         add_handler(LIST+MAPS+STATS, cli_list_maps_stats);
709         add_handler(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
710         add_handler(LIST+TOPOLOGY, cli_list_maps_topology);
711         add_handler(LIST+MAP+TOPOLOGY, cli_list_map_topology);
712         add_handler(LIST+CONFIG, cli_list_config);
713         add_handler(LIST+BLACKLIST, cli_list_blacklist);
714         add_handler(LIST+DEVICES, cli_list_devices);
715         add_handler(ADD+PATH, cli_add_path);
716         add_handler(DEL+PATH, cli_del_path);
717         add_handler(ADD+MAP, cli_add_map);
718         add_handler(DEL+MAP, cli_del_map);
719         add_handler(SWITCH+MAP+GROUP, cli_switch_group);
720         add_handler(RECONFIGURE, cli_reconfigure);
721         add_handler(SUSPEND+MAP, cli_suspend);
722         add_handler(RESUME+MAP, cli_resume);
723         add_handler(REINSTATE+PATH, cli_reinstate);
724         add_handler(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 (blacklist_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         if (conf->verbosity > 2)
1073                 vector_foreach_slot(mpvec, mpp, i)
1074                         print_map(mpp);
1075
1076         /*
1077          * purge dm of old maps
1078          */
1079         remove_maps(vecs, NULL);
1080
1081         /*
1082          * save new set of maps formed by considering current path state
1083          */
1084         vector_free(vecs->mpvec);
1085         vecs->mpvec = mpvec;
1086
1087         /*
1088          * start dm event waiter threads for these new maps
1089          */
1090         vector_foreach_slot(vecs->mpvec, mpp, i) {
1091                 if (setup_multipath(vecs, mpp))
1092                         return 1;
1093                 if (start_waiters)
1094                         if (start_waiter_thread(mpp, vecs))
1095                                 return 1;
1096         }
1097         return 0;
1098 }
1099
1100 int
1101 reconfigure (struct vectors * vecs)
1102 {
1103         struct config * old = conf;
1104
1105         /*
1106          * free old map and path vectors ... they use old conf state
1107          */
1108         if (VECTOR_SIZE(vecs->mpvec))
1109                 remove_maps(vecs, stop_waiter_thread);
1110
1111         if (VECTOR_SIZE(vecs->pathvec))
1112                 free_pathvec(vecs->pathvec, FREE_PATHS);
1113
1114         vecs->pathvec = NULL;
1115         conf = NULL;
1116
1117         if (load_config(DEFAULT_CONFIGFILE))
1118                 return 1;
1119
1120         conf->verbosity = old->verbosity;
1121
1122         if (!conf->checkint) {
1123                 conf->checkint = DEFAULT_CHECKINT;
1124                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1125         }
1126         configure(vecs, 1);
1127         free_config(old);
1128         return 0;
1129 }
1130
1131 static struct vectors *
1132 init_vecs (void)
1133 {
1134         struct vectors * vecs;
1135
1136         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1137
1138         if (!vecs)
1139                 return NULL;
1140
1141         vecs->lock = 
1142                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1143
1144         if (!vecs->lock)
1145                 goto out;
1146
1147         pthread_mutex_init(vecs->lock, NULL);
1148
1149         return vecs;
1150
1151 out:
1152         FREE(vecs);
1153         condlog(0, "failed to init paths");
1154         return NULL;
1155 }
1156
1157 static void *
1158 signal_set(int signo, void (*func) (int))
1159 {
1160         int r;
1161         struct sigaction sig;
1162         struct sigaction osig;
1163
1164         sig.sa_handler = func;
1165         sigemptyset(&sig.sa_mask);
1166         sig.sa_flags = 0;
1167
1168         r = sigaction(signo, &sig, &osig);
1169
1170         if (r < 0)
1171                 return (SIG_ERR);
1172         else
1173                 return (osig.sa_handler);
1174 }
1175
1176 static void
1177 sighup (int sig)
1178 {
1179         condlog(2, "reconfigure (SIGHUP)");
1180
1181         lock(gvecs->lock);
1182         reconfigure(gvecs);
1183         unlock(gvecs->lock);
1184
1185 #ifdef _DEBUG_
1186         dbg_free_final(NULL);
1187 #endif
1188 }
1189
1190 static void
1191 sigend (int sig)
1192 {
1193         exit_daemon(0);
1194 }
1195
1196 static void
1197 sigusr1 (int sig)
1198 {
1199         condlog(3, "SIGUSR1 received");
1200 }
1201
1202 static void
1203 signal_init(void)
1204 {
1205         signal_set(SIGHUP, sighup);
1206         signal_set(SIGUSR1, sigusr1);
1207         signal_set(SIGINT, sigend);
1208         signal_set(SIGTERM, sigend);
1209         signal(SIGPIPE, SIG_IGN);
1210 }
1211
1212 static void
1213 setscheduler (void)
1214 {
1215         int res;
1216         static struct sched_param sched_param = {
1217                 .sched_priority = 99
1218         };
1219
1220         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1221
1222         if (res == -1)
1223                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1224         return;
1225 }
1226
1227 static void
1228 set_oom_adj (int val)
1229 {
1230         FILE *fp;
1231
1232         fp = fopen("/proc/self/oom_adj", "w");
1233
1234         if (!fp)
1235                 return;
1236
1237         fprintf(fp, "%i", val);
1238         fclose(fp);
1239 }
1240         
1241 static int
1242 child (void * param)
1243 {
1244         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1245         pthread_attr_t attr;
1246         struct vectors * vecs;
1247
1248         mlockall(MCL_CURRENT | MCL_FUTURE);
1249
1250         if (logsink)
1251                 log_thread_start();
1252
1253         condlog(2, "--------start up--------");
1254         condlog(2, "read " DEFAULT_CONFIGFILE);
1255
1256         if (load_config(DEFAULT_CONFIGFILE))
1257                 exit(1);
1258
1259         setlogmask(LOG_UPTO(conf->verbosity + 3));
1260
1261         /*
1262          * fill the voids left in the config file
1263          */
1264         if (!conf->checkint) {
1265                 conf->checkint = DEFAULT_CHECKINT;
1266                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1267         }
1268
1269         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1270                 if (logsink)
1271                         log_thread_stop();
1272
1273                 exit(1);
1274         }
1275         signal_init();
1276         setscheduler();
1277         set_oom_adj(-16);
1278         vecs = gvecs = init_vecs();
1279
1280         if (!vecs)
1281                 exit(1);
1282
1283         if (sysfs_get_mnt_path(sysfs_path, FILE_NAME_SIZE)) {
1284                 condlog(0, "can not find sysfs mount point");
1285                 exit(1);
1286         }
1287
1288         /*
1289          * fetch and configure both paths and multipaths
1290          */
1291         if (configure(vecs, 1)) {
1292                 condlog(0, "failure during configuration");
1293                 exit(1);
1294         }
1295
1296         /*
1297          * start threads
1298          */
1299         pthread_attr_init(&attr);
1300         pthread_attr_setstacksize(&attr, 64 * 1024);
1301         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1302         
1303         pthread_create(&check_thr, &attr, checkerloop, vecs);
1304         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1305         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1306
1307         pthread_cond_wait(&exit_cond, &exit_mutex);
1308
1309         /*
1310          * exit path
1311          */
1312         lock(vecs->lock);
1313         remove_maps(vecs, stop_waiter_thread);
1314         free_pathvec(vecs->pathvec, FREE_PATHS);
1315
1316         pthread_cancel(check_thr);
1317         pthread_cancel(uevent_thr);
1318         pthread_cancel(uxlsnr_thr);
1319
1320         free_keys(keys);
1321         keys = NULL;
1322         free_handlers(handlers);
1323         handlers = NULL;
1324         free_polls();
1325
1326         unlock(vecs->lock);
1327         pthread_mutex_destroy(vecs->lock);
1328         FREE(vecs->lock);
1329         vecs->lock = NULL;
1330         FREE(vecs);
1331         vecs = NULL;
1332         free_config(conf);
1333         conf = NULL;
1334
1335         condlog(2, "--------shut down-------");
1336         
1337         if (logsink)
1338                 log_thread_stop();
1339
1340         dm_lib_release();
1341         dm_lib_exit();
1342
1343 #ifdef _DEBUG_
1344         dbg_free_final(NULL);
1345 #endif
1346
1347         exit(0);
1348 }
1349
1350 static int
1351 daemonize(void)
1352 {
1353         int pid;
1354         int in_fd, out_fd;
1355
1356         if( (pid = fork()) < 0){
1357                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1358                 return -1;
1359         }
1360         else if (pid != 0)
1361                 return pid;
1362
1363         setsid();
1364
1365         if ( (pid = fork()) < 0)
1366                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1367         else if (pid != 0)
1368                 _exit(0);
1369
1370         in_fd = open("/dev/null", O_RDONLY);
1371         if (in_fd < 0){
1372                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1373                         strerror(errno));
1374                 _exit(0);
1375         }
1376         out_fd = open("/dev/console", O_WRONLY);
1377         if (out_fd < 0){
1378                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1379                         strerror(errno));
1380                 _exit(0);
1381         }
1382
1383         close(STDIN_FILENO);
1384         dup(in_fd);
1385         close(STDOUT_FILENO);
1386         dup(out_fd);
1387         close(STDERR_FILENO);
1388         dup(out_fd);
1389
1390         close(in_fd);
1391         close(out_fd);
1392         chdir("/");
1393         umask(0);
1394         return 0;
1395 }
1396
1397 int
1398 main (int argc, char *argv[])
1399 {
1400         extern char *optarg;
1401         extern int optind;
1402         int arg;
1403         int err;
1404         
1405         logsink = 1;
1406
1407         if (getuid() != 0) {
1408                 fprintf(stderr, "need to be root\n");
1409                 exit(1);
1410         }
1411
1412         /* make sure we don't lock any path */
1413         chdir("/");
1414         umask(umask(077) | 022);
1415
1416         conf = alloc_config();
1417
1418         if (!conf)
1419                 exit(1);
1420
1421         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1422         switch(arg) {
1423                 case 'd':
1424                         logsink = 0;
1425                         //debug=1; /* ### comment me out ### */
1426                         break;
1427                 case 'v':
1428                         if (sizeof(optarg) > sizeof(char *) ||
1429                             !isdigit(optarg[0]))
1430                                 exit(1);
1431
1432                         conf->verbosity = atoi(optarg);
1433                         break;
1434                 case 'k':
1435                         uxclnt(optarg);
1436                         exit(0);
1437                 default:
1438                         ;
1439                 }
1440         }
1441
1442         if (!logsink)
1443                 err = 0;
1444         else
1445                 err = daemonize();
1446         
1447         if (err < 0)
1448                 /* error */
1449                 exit(1);
1450         else if (err > 0)
1451                 /* parent dies */
1452                 exit(0);
1453         else
1454                 /* child lives */
1455                 return (child(NULL));
1456 }
1457