[libmultipath] rename find_mp() to find_mp_by_alias()
[platform/upstream/multipath-tools.git] / multipathd / main.c
1 #include <unistd.h>
2 #include <sys/stat.h>
3 #include <libdevmapper.h>
4 #include <wait.h>
5 #include <sys/mman.h>
6
7 /*
8  * libsysfs
9  */
10 #include <sysfs/libsysfs.h>
11 #include <sysfs/dlist.h>
12
13 /*
14  * libcheckers
15  */
16 #include <checkers.h>
17 #include <path_state.h>
18
19 /*
20  * libmultipath
21  */
22 #include <parser.h>
23 #include <vector.h>
24 #include <memory.h>
25 #include <config.h>
26 #include <callout.h>
27 #include <util.h>
28 #include <blacklist.h>
29 #include <hwtable.h>
30 #include <defaults.h>
31 #include <structs.h>
32 #include <dmparser.h>
33 #include <devmapper.h>
34 #include <dict.h>
35 #include <discovery.h>
36 #include <debug.h>
37 #include <propsel.h>
38 #include <uevent.h>
39 #include <switchgroup.h>
40 #include <path_state.h>
41 #include <print.h>
42
43 #include "main.h"
44 #include "pidfile.h"
45 #include "uxlsnr.h"
46 #include "uxclnt.h"
47 #include "cli.h"
48 #include "cli_handlers.h"
49
50 #define FILE_NAME_SIZE 256
51 #define CMDSIZE 160
52
53 #define LOG_MSG(a,b) \
54         if (strlen(b)) { \
55                 condlog(a, "%s: %s", pp->dev_t, b); \
56                 memset(b, 0, MAX_CHECKER_MSG_SIZE); \
57         }
58
59 #ifdef LCKDBG
60 #define lock(a) \
61         fprintf(stderr, "%s:%s(%i) lock %p\n", __FILE__, __FUNCTION__, __LINE__, a); \
62         pthread_mutex_lock(a)
63 #define unlock(a) \
64         fprintf(stderr, "%s:%s(%i) unlock %p\n", __FILE__, __FUNCTION__, __LINE__, a); \
65         pthread_mutex_unlock(a)
66 #define lock_cleanup_pop(a) \
67         fprintf(stderr, "%s:%s(%i) unlock %p\n", __FILE__, __FUNCTION__, __LINE__, a); \
68         pthread_cleanup_pop(1);
69 #else
70 #define lock(a) pthread_mutex_lock(a)
71 #define unlock(a) pthread_mutex_unlock(a)
72 #define lock_cleanup_pop(a) pthread_cleanup_pop(1);
73 #endif
74
75 pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
76 pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
77
78 /*
79  * structs
80  */
81 struct event_thread {
82         struct dm_task *dmt;
83         pthread_t thread;
84         int event_nr;
85         char mapname[WWID_SIZE];
86         struct vectors *vecs;
87 };
88
89 static struct event_thread *
90 alloc_waiter (void)
91 {
92
93         struct event_thread * wp;
94
95         wp = (struct event_thread *)MALLOC(sizeof(struct event_thread));
96
97         return wp;
98 }
99
100 static void
101 free_waiter (void * data)
102 {
103         struct event_thread * wp = (struct event_thread *)data;
104
105         if (wp->dmt)
106                 dm_task_destroy(wp->dmt);
107         FREE(wp);
108 }
109
110 static void
111 stop_waiter_thread (struct multipath * mpp, struct vectors * vecs)
112 {
113         struct event_thread * wp = (struct event_thread *)mpp->waiter;
114         pthread_t thread;
115         
116         if (!wp) {
117                 condlog(3, "%s: no waiter thread", mpp->alias);
118                 return;
119         }
120         thread = wp->thread;
121
122         if (!wp) {
123                 condlog(3, "%s: thread not started", mpp->alias);
124                 return;
125         }
126         condlog(2, "%s: stop event checker thread", wp->mapname);
127         pthread_kill(thread, SIGHUP);
128 }
129
130 static void
131 cleanup_lock (void * data)
132 {
133         pthread_mutex_unlock((pthread_mutex_t *)data);
134 }
135
136 static void
137 adopt_paths (struct vectors * vecs, struct multipath * mpp)
138 {
139         int i;
140         struct path * pp;
141
142         if (!mpp)
143                 return;
144
145         vector_foreach_slot (vecs->pathvec, pp, i) {
146                 if (!strncmp(mpp->wwid, pp->wwid, WWID_SIZE)) {
147                         condlog(4, "%s ownership set", pp->dev_t);
148                         pp->mpp = mpp;
149                 }
150         }
151 }
152
153 static void
154 orphan_path (struct path * pp)
155 {
156         pp->mpp = NULL;
157         pp->checkfn = NULL;
158         pp->dmstate = PSTATE_UNDEF;
159         pp->checker_context = NULL;
160         pp->getuid = NULL;
161         pp->getprio = NULL;
162
163         if (pp->fd >= 0)
164                 close(pp->fd);
165
166         pp->fd = -1;
167 }
168
169 static void
170 orphan_paths (struct vectors * vecs, struct multipath * mpp)
171 {
172         int i;
173         struct path * pp;
174
175         vector_foreach_slot (vecs->pathvec, pp, i) {
176                 if (pp->mpp == mpp) {
177                         condlog(4, "%s is orphaned", pp->dev_t);
178                         orphan_path(pp);
179                 }
180         }
181 }
182
183 static int
184 update_multipath_table (struct multipath *mpp, vector pathvec)
185 {
186         if (!mpp)
187                 return 1;
188
189         if (dm_get_map(mpp->alias, &mpp->size, mpp->params))
190                 return 1;
191
192         if (disassemble_map(pathvec, mpp->params, mpp))
193                 return 1;
194
195         return 0;
196 }
197
198 static int
199 update_multipath_status (struct multipath *mpp)
200 {
201         if (!mpp)
202                 return 1;
203
204         if(dm_get_status(mpp->alias, mpp->status))
205                 return 1;
206
207         if (disassemble_status(mpp->status, mpp))
208                 return 1;
209
210         return 0;
211 }
212
213 static int
214 update_multipath_strings (struct multipath *mpp, vector pathvec)
215 {
216         if (mpp->selector) {
217                 FREE(mpp->selector);
218                 mpp->selector = NULL;
219         }
220
221         if (mpp->features) {
222                 FREE(mpp->features);
223                 mpp->features = NULL;
224         }
225
226         if (mpp->hwhandler) {
227                 FREE(mpp->hwhandler);
228                 mpp->hwhandler = NULL;
229         }
230
231         free_pgvec(mpp->pg, KEEP_PATHS);
232         mpp->pg = NULL;
233
234         if (update_multipath_table(mpp, pathvec))
235                 return 1;
236
237         if (update_multipath_status(mpp))
238                 return 1;
239
240         return 0;
241 }
242
243 static void
244 set_multipath_wwid (struct multipath * mpp)
245 {
246         if (mpp->wwid)
247                 return;
248
249         dm_get_uuid(mpp->alias, mpp->wwid);
250 }
251
252 static int
253 pathcount (struct multipath *mpp, int state)
254 {
255         struct pathgroup *pgp;
256         struct path *pp;
257         int i, j;
258         int count = 0;
259
260         vector_foreach_slot (mpp->pg, pgp, i)
261                 vector_foreach_slot (pgp->paths, pp, j)
262                         if (pp->state == state)
263                                 count++;
264         return count;
265 }
266
267 /*
268  * mpp->no_path_retry:
269  *   -2 (QUEUE) : queue_if_no_path enabled, never turned off
270  *   -1 (FAIL)  : fail_if_no_path
271  *    0 (UNDEF) : nothing
272  *   >0         : queue_if_no_path enabled, turned off after polling n times
273  */
274 static void
275 update_queue_mode_del_path(struct multipath *mpp)
276 {
277         if (--mpp->nr_active == 0 && mpp->no_path_retry > 0) {
278                 /*
279                  * Enter retry mode.
280                  * meaning of +1: retry_tick may be decremented in
281                  *                checkerloop before starting retry.
282                  */
283                 mpp->retry_tick = mpp->no_path_retry * conf->checkint + 1;
284                 condlog(1, "%s: Entering recovery mode: max_retries=%d",
285                         mpp->alias, mpp->no_path_retry);
286         }
287         condlog(2, "%s: remaining active paths: %d", mpp->alias, mpp->nr_active);
288 }
289
290 static void
291 update_queue_mode_add_path(struct multipath *mpp)
292 {
293         if (mpp->nr_active++ == 0 && mpp->no_path_retry > 0) {
294                 /* come back to normal mode from retry mode */
295                 mpp->retry_tick = 0;
296                 dm_queue_if_no_path(mpp->alias, 1);
297                 condlog(2, "%s: queue_if_no_path enabled", mpp->alias);
298                 condlog(1, "%s: Recovered to normal mode", mpp->alias);
299         }
300         condlog(2, "%s: remaining active paths: %d", mpp->alias, mpp->nr_active);
301 }
302
303 static void
304 set_no_path_retry(struct multipath *mpp)
305 {
306         mpp->retry_tick = 0;
307         mpp->nr_active = pathcount(mpp, PATH_UP);
308         select_no_path_retry(mpp);
309
310         switch (mpp->no_path_retry) {
311         case NO_PATH_RETRY_UNDEF:
312                 break;
313         case NO_PATH_RETRY_FAIL:
314                 dm_queue_if_no_path(mpp->alias, 0);
315                 break;
316         case NO_PATH_RETRY_QUEUE:
317                 dm_queue_if_no_path(mpp->alias, 1);
318                 break;
319         default:
320                 dm_queue_if_no_path(mpp->alias, 1);
321                 if (mpp->nr_active == 0) {
322                         /* Enter retry mode */
323                         mpp->retry_tick = mpp->no_path_retry * conf->checkint;
324                         condlog(1, "%s: Entering recovery mode: max_retries=%d",
325                                 mpp->alias, mpp->no_path_retry);
326                 }
327                 break;
328         }
329 }
330
331 static struct hwentry *
332 extract_hwe_from_path(struct multipath * mpp)
333 {
334         struct path * pp;
335         struct pathgroup * pgp;
336
337         pgp = VECTOR_SLOT(mpp->pg, 0);
338         pp = VECTOR_SLOT(pgp->paths, 0);
339
340         return pp->hwe;
341 }
342
343 static void
344 remove_map (struct multipath * mpp, struct vectors * vecs)
345 {
346         int i;
347
348         stop_waiter_thread(mpp, vecs);
349
350         /*
351          * clear references to this map
352          */
353         orphan_paths(vecs, mpp);
354
355         /*
356          * purge the multipath vector
357          */
358         i = find_slot(vecs->mpvec, (void *)mpp);
359         vector_del_slot(vecs->mpvec, i);
360
361         /*
362          * final free
363          */
364         free_multipath(mpp, KEEP_PATHS);
365         mpp = NULL;
366 }
367
368 static void
369 remove_maps (struct vectors * vecs)
370 {
371         int i;
372         struct multipath * mpp;
373
374         vector_foreach_slot (vecs->mpvec, mpp, i) {
375                 remove_map(mpp, vecs);
376                 i--;
377         }
378
379         vector_free(vecs->mpvec);
380         vecs->mpvec = NULL;
381 }
382
383 static int
384 setup_multipath (struct vectors * vecs, struct multipath * mpp)
385 {
386         set_multipath_wwid(mpp);
387         mpp->mpe = find_mpe(mpp->wwid);
388         condlog(4, "discovered map %s", mpp->alias);
389
390         if (update_multipath_strings(mpp, vecs->pathvec))
391                 goto out;
392
393         adopt_paths(vecs, mpp);
394         select_pgfailback(mpp);
395         mpp->hwe = extract_hwe_from_path(mpp);
396         set_no_path_retry(mpp);
397
398         return 0;
399 out:
400         condlog(0, "%s: failed to setup multipath", mpp->alias);
401         remove_map(mpp, vecs);
402         return 1;
403 }
404
405 static int
406 need_switch_pathgroup (struct multipath * mpp, int refresh)
407 {
408         struct pathgroup * pgp;
409         struct path * pp;
410         int i, j;
411
412         if (!mpp || mpp->pgfailback == -FAILBACK_MANUAL)
413                 return 0;
414
415         /*
416          * Refresh path priority values
417          */
418         if (refresh)
419                 vector_foreach_slot (mpp->pg, pgp, i)
420                         vector_foreach_slot (pgp->paths, pp, j)
421                                 pathinfo(pp, conf->hwtable, DI_PRIO);
422
423         select_path_group(mpp); /* sets mpp->nextpg */
424         pgp = VECTOR_SLOT(mpp->pg, mpp->nextpg - 1);
425
426         if (pgp && pgp->status != PGSTATE_ACTIVE)
427                 return 1;
428
429         return 0;
430 }
431
432 static void
433 switch_pathgroup (struct multipath * mpp)
434 {
435         struct pathgroup * pgp;
436         
437         pgp = VECTOR_SLOT(mpp->pg, mpp->nextpg - 1);
438         
439         if (pgp && pgp->status != PGSTATE_ACTIVE) {
440                 dm_switchgroup(mpp->alias, mpp->nextpg);
441                 condlog(2, "%s: switch to path group #%i",
442                          mpp->alias, mpp->nextpg);
443         }
444 }
445
446 static int
447 update_multipath (struct vectors *vecs, char *mapname)
448 {
449         struct multipath *mpp;
450         struct pathgroup  *pgp;
451         struct path *pp;
452         int i, j;
453         int r = 1;
454
455         mpp = find_mp_by_alias(vecs->mpvec, mapname);
456
457         if (!mpp)
458                 goto out;
459
460         free_pgvec(mpp->pg, KEEP_PATHS);
461         mpp->pg = NULL;
462
463         if (setup_multipath(vecs, mpp))
464                 goto out; /* mpp freed in setup_multipath */
465
466         /*
467          * compare checkers states with DM states
468          */
469         vector_foreach_slot (mpp->pg, pgp, i) {
470                 vector_foreach_slot (pgp->paths, pp, j) {
471                         if (pp->dmstate != PSTATE_FAILED)
472                                 continue;
473
474                         if (pp->state != PATH_DOWN) {
475                                 condlog(2, "%s: mark as failed", pp->dev_t);
476                                 pp->state = PATH_DOWN;
477                                 update_queue_mode_del_path(mpp);
478
479                                 /*
480                                  * if opportune,
481                                  * schedule the next check earlier
482                                  */
483                                 if (pp->tick > conf->checkint)
484                                         pp->tick = conf->checkint;
485                         }
486                 }
487         }
488         r = 0;
489 out:
490         if (r)
491                 condlog(0, "failed to update multipath");
492
493         return r;
494 }
495
496 static sigset_t unblock_sighup(void)
497 {
498         sigset_t set, old;
499
500         sigemptyset(&set);
501         sigaddset(&set, SIGHUP);
502         pthread_sigmask(SIG_UNBLOCK, &set, &old);
503         return old;
504 }
505
506 /*
507  * returns the reschedule delay
508  * negative means *stop*
509  */
510 static int
511 waiteventloop (struct event_thread * waiter)
512 {
513         sigset_t set;
514         int event_nr;
515         int r;
516
517         if (!waiter->event_nr)
518                 waiter->event_nr = dm_geteventnr(waiter->mapname);
519
520         if (!(waiter->dmt = dm_task_create(DM_DEVICE_WAITEVENT)))
521                 return 1;
522
523         if (!dm_task_set_name(waiter->dmt, waiter->mapname)) {
524                 dm_task_destroy(waiter->dmt);
525                 return 1;
526         }
527
528         if (waiter->event_nr && !dm_task_set_event_nr(waiter->dmt,
529                                                       waiter->event_nr)) {
530                 dm_task_destroy(waiter->dmt);
531                 return 1;
532         }
533
534         dm_task_no_open_count(waiter->dmt);
535         
536         /* accept wait interruption */
537         set = unblock_sighup();
538
539         /* interruption spits messages */
540         dm_shut_log();
541
542         /* wait */
543         r = dm_task_run(waiter->dmt);
544
545         /* wait is over : event or interrupt */
546         pthread_sigmask(SIG_SETMASK, &set, NULL);
547         //dm_restore_log();
548
549         if (!r) /* wait interrupted by signal */
550                 return -1;
551
552         dm_task_destroy(waiter->dmt);
553         waiter->dmt = NULL;
554         waiter->event_nr++;
555
556         /*
557          * upon event ...
558          */
559         while (1) {
560                 condlog(3, "%s: devmap event #%i",
561                                 waiter->mapname, waiter->event_nr);
562
563                 /*
564                  * event might be :
565                  *
566                  * 1) a table reload, which means our mpp structure is
567                  *    obsolete : refresh it through update_multipath()
568                  * 2) a path failed by DM : mark as such through
569                  *    update_multipath()
570                  * 3) map has gone away : stop the thread.
571                  * 4) a path reinstate : nothing to do
572                  * 5) a switch group : nothing to do
573                  */
574                 pthread_cleanup_push(cleanup_lock, waiter->vecs->lock);
575                 lock(waiter->vecs->lock);
576                 r = update_multipath(waiter->vecs, waiter->mapname);
577                 lock_cleanup_pop(waiter->vecs->lock);
578
579                 if (r)
580                         return -1; /* stop the thread */
581
582                 event_nr = dm_geteventnr(waiter->mapname);
583
584                 if (waiter->event_nr == event_nr)
585                         return 1; /* upon problem reschedule 1s later */
586
587                 waiter->event_nr = event_nr;
588         }
589         return -1; /* never reach there */
590 }
591
592 static void *
593 waitevent (void * et)
594 {
595         int r;
596         struct event_thread *waiter;
597
598         mlockall(MCL_CURRENT | MCL_FUTURE);
599
600         waiter = (struct event_thread *)et;
601         pthread_cleanup_push(free_waiter, et);
602
603         while (1) {
604                 r = waiteventloop(waiter);
605
606                 if (r < 0)
607                         break;
608
609                 sleep(r);
610         }
611
612         pthread_cleanup_pop(1);
613         return NULL;
614 }
615
616 static int
617 start_waiter_thread (struct multipath * mpp, struct vectors * vecs)
618 {
619         pthread_attr_t attr;
620         struct event_thread * wp;
621
622         if (!mpp)
623                 return 0;
624
625         if (pthread_attr_init(&attr))
626                 goto out;
627
628         pthread_attr_setstacksize(&attr, 32 * 1024);
629         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
630
631         wp = alloc_waiter();
632
633         if (!wp)
634                 goto out;
635
636         mpp->waiter = (void *)wp;
637         strncpy(wp->mapname, mpp->alias, WWID_SIZE);
638         wp->vecs = vecs;
639
640         if (pthread_create(&wp->thread, &attr, waitevent, wp)) {
641                 condlog(0, "%s: cannot create event checker", wp->mapname);
642                 goto out1;
643         }
644         condlog(2, "%s: event checker started", wp->mapname);
645
646         return 0;
647 out1:
648         free_waiter(wp);
649         mpp->waiter = NULL;
650 out:
651         condlog(0, "failed to start waiter thread");
652         return 1;
653 }
654
655 int
656 uev_add_map (char * devname, struct vectors * vecs)
657 {
658         int major, minor;
659         char dev_t[BLK_DEV_SIZE];
660         char * alias;
661         struct multipath * mpp;
662
663         if (sysfs_get_dev(sysfs_path, devname, dev_t, BLK_DEV_SIZE))
664                 return 1;
665
666         if (sscanf(dev_t, "%d:%d", &major, &minor) != 2)
667                 return 1;
668
669         alias = dm_mapname(major, minor);
670                 
671         if (!alias)
672                 return 1;
673         
674         if (!dm_type(alias, DEFAULT_TARGET)) {
675                 condlog(4, "%s: not a multipath map", alias);
676                 FREE(alias);
677                 return 0;
678         }
679
680         mpp = find_mp_by_alias(vecs->mpvec, alias);
681
682         if (mpp) {
683                 /*
684                  * this should not happen,
685                  * we missed a remove map event (not sent ?)
686                  */
687                 condlog(2, "%s: already registered", alias);
688                 remove_map(mpp, vecs);
689         }
690
691         /*
692          * now we can allocate
693          */
694         mpp = alloc_multipath();
695
696         if (!mpp)
697                 return 1;
698
699         mpp->minor = minor;
700         mpp->alias = alias;
701
702         if (setup_multipath(vecs, mpp))
703                 return 1; /* mpp freed in setup_multipath */
704
705         if (!vector_alloc_slot(vecs->mpvec))
706                 goto out;
707
708         vector_set_slot(vecs->mpvec, mpp);
709         adopt_paths(vecs, mpp);
710
711         if (start_waiter_thread(mpp, vecs))
712                 goto out;
713
714         return 0;
715 out:
716         condlog(2, "%s: add devmap failed", mpp->alias);
717         remove_map(mpp, vecs);
718         return 1;
719 }
720
721 int
722 uev_remove_map (char * devname, struct vectors * vecs)
723 {
724         int minor;
725         struct multipath * mpp;
726
727         if (sscanf(devname, "dm-%d", &minor) != 1)
728                 return 1;
729
730         mpp = find_mp_by_minor(vecs->mpvec, minor);
731
732         if (!mpp) {
733                 condlog(3, "%s: devmap not registered, can't remove",
734                         devname);
735                 return 0;
736         }
737
738         condlog(2, "remove %s devmap", mpp->alias);
739         remove_map(mpp, vecs);
740
741         return 0;
742 }
743
744 int
745 uev_add_path (char * devname, struct vectors * vecs)
746 {
747         struct path * pp;
748
749         pp = find_path_by_dev(vecs->pathvec, devname);
750
751         if (pp) {
752                 condlog(3, "%s: already in pathvec");
753                 return 1;
754         }
755         pp = store_pathinfo(vecs->pathvec, conf->hwtable,
756                        devname, DI_SYSFS | DI_WWID);
757
758         if (!pp) {
759                 condlog(0, "%s: failed to store path info", devname);
760                 return 1;
761         }
762
763         condlog(2, "%s: path checker registered", devname);
764         pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
765
766         if (pp->mpp) {
767                 condlog(4, "%s: ownership set to %s",
768                                 pp->dev_t, pp->mpp->alias);
769         } else {
770                 condlog(4, "%s: orphaned", pp->dev_t);
771                 orphan_path(pp);
772         }
773
774         return 0;
775 }
776
777 int
778 uev_remove_path (char * devname, struct vectors * vecs)
779 {
780         int i;
781         struct path * pp;
782
783         pp = find_path_by_dev(vecs->pathvec, devname);
784
785         if (!pp) {
786                 condlog(3, "%s: not in pathvec");
787                 return 1;
788         }
789
790         if (pp->mpp && pp->state == PATH_UP)
791                 update_queue_mode_del_path(pp->mpp);
792
793         condlog(2, "remove %s path checker", devname);
794         i = find_slot(vecs->pathvec, (void *)pp);
795         vector_del_slot(vecs->pathvec, i);
796         free_path(pp);
797
798         return 0;
799 }
800
801 int
802 show_paths (char ** r, int * len, struct vectors * vecs)
803 {
804         int i;
805         struct path * pp;
806         char * c;
807         char * reply;
808         struct path_layout pl;
809
810         get_path_layout(&pl, vecs->pathvec);
811         reply = MALLOC(MAX_REPLY_LEN);
812
813         if (!reply)
814                 return 1;
815
816         c = reply;
817
818         if (VECTOR_SIZE(vecs->pathvec) > 0)
819                 c += snprint_path_header(c, reply + MAX_REPLY_LEN - c,
820                                          PRINT_PATH_CHECKER, &pl);
821
822         vector_foreach_slot(vecs->pathvec, pp, i)
823                 c += snprint_path(c, reply + MAX_REPLY_LEN - c,
824                                   PRINT_PATH_CHECKER, pp, &pl);
825
826         *r = reply;
827         *len = (int)(c - reply + 1);
828         return 0;
829 }
830
831 int
832 show_maps (char ** r, int *len, struct vectors * vecs)
833 {
834         int i;
835         struct multipath * mpp;
836         char * c;
837         char * reply;
838         struct map_layout ml;
839
840         get_map_layout(&ml, vecs->mpvec);
841         reply = MALLOC(MAX_REPLY_LEN);
842
843         if (!reply)
844                 return 1;
845
846         c = reply;
847         if (VECTOR_SIZE(vecs->mpvec) > 0)
848                 c += snprint_map_header(c, reply + MAX_REPLY_LEN - c,
849                                         PRINT_MAP_FAILBACK, &ml);
850
851         vector_foreach_slot(vecs->mpvec, mpp, i)
852                 c += snprint_map(c, reply + MAX_REPLY_LEN - c,
853                                  PRINT_MAP_FAILBACK, mpp, &ml);
854
855         *r = reply;
856         *len = (int)(c - reply + 1);
857         return 0;
858 }
859
860 int
861 dump_pathvec (char ** r, int * len, struct vectors * vecs)
862 {
863         int i;
864         struct path * pp;
865         char * reply;
866         char * p;
867
868         *len = VECTOR_SIZE(vecs->pathvec) * sizeof(struct path);
869         reply = (char *)MALLOC(*len);
870         *r = reply;
871
872         if (!reply)
873                 return 1;
874
875         p = reply;
876
877         vector_foreach_slot (vecs->pathvec, pp, i) {
878                 memcpy((void *)p, pp, sizeof(struct path));
879                 p += sizeof(struct path);
880         }
881
882         /* return negative to hint caller not to add "ok" to the dump */
883         return -1;
884 }
885
886 static int
887 map_discovery (struct vectors * vecs)
888 {
889         int i;
890         struct multipath * mpp;
891
892         if (dm_get_maps(vecs->mpvec, "multipath"))
893                 return 1;
894
895         vector_foreach_slot (vecs->mpvec, mpp, i) {
896                 if (setup_multipath(vecs, mpp))
897                         return 1;
898                 mpp->minor = dm_get_minor(mpp->alias);
899                 start_waiter_thread(mpp, vecs);
900         }
901
902         return 0;
903 }
904
905 int
906 reconfigure (struct vectors * vecs)
907 {
908         struct config * old = conf;
909         struct multipath * mpp;
910         struct path * pp;
911         int i;
912
913         conf = NULL;
914
915         if (load_config(DEFAULT_CONFIGFILE)) {
916                 conf = old;
917                 condlog(2, "reconfigure failed, continue with old config");
918                 return 1;
919         }
920         conf->verbosity = old->verbosity;
921         free_config(old);
922
923         vector_foreach_slot (vecs->mpvec, mpp, i) {
924                 mpp->mpe = find_mpe(mpp->wwid);
925                 mpp->hwe = extract_hwe_from_path(mpp);
926                 adopt_paths(vecs, mpp);
927                 set_no_path_retry(mpp);
928         }
929         vector_foreach_slot (vecs->pathvec, pp, i) {
930                 select_checkfn(pp);
931                 select_getuid(pp);
932                 select_getprio(pp);
933         }
934         condlog(2, "reconfigured");
935         return 0;
936 }
937
938 int
939 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
940 {
941         struct vectors * vecs;
942         int r;
943         
944         *reply = NULL;
945         *len = 0;
946         vecs = (struct vectors *)trigger_data;
947
948         pthread_cleanup_push(cleanup_lock, vecs->lock);
949         lock(vecs->lock);
950
951         r = parse_cmd(str, reply, len, vecs);
952
953         if (r > 0) {
954                 *reply = STRDUP("fail\n");
955                 *len = strlen(*reply) + 1;
956                 r = 1;
957         }
958         else if (!r && *len == 0) {
959                 *reply = STRDUP("ok\n");
960                 *len = strlen(*reply) + 1;
961                 r = 0;
962         }
963         /* else if (r < 0) leave *reply alone */
964
965         lock_cleanup_pop(vecs->lock);
966         return r;
967 }
968
969 static int
970 uev_discard(char * devpath)
971 {
972         char a[10], b[10];
973
974         /*
975          * keep only block devices, discard partitions
976          */
977         if (sscanf(devpath, "/block/%10s", a) != 1 ||
978             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
979                 condlog(4, "discard event on %s", devpath);
980                 return 1;
981         }
982         return 0;
983 }
984
985 int 
986 uev_trigger (struct uevent * uev, void * trigger_data)
987 {
988         int r = 0;
989         char devname[32];
990         struct vectors * vecs;
991
992         vecs = (struct vectors *)trigger_data;
993
994         if (uev_discard(uev->devpath))
995                 goto out;
996
997         basename(uev->devpath, devname);
998         lock(vecs->lock);
999
1000         /*
1001          * device map add/remove event
1002          */
1003         if (!strncmp(devname, "dm-", 3)) {
1004                 if (!strncmp(uev->action, "add", 3)) {
1005                         r = uev_add_map(devname, vecs);
1006                         goto out;
1007                 }
1008 #if 0
1009                 if (!strncmp(uev->action, "remove", 6)) {
1010                         r = uev_remove_map(devname, vecs);
1011                         goto out;
1012                 }
1013 #endif
1014                 goto out;
1015         }
1016         
1017         /*
1018          * path add/remove event
1019          */
1020         if (blacklist(conf->blist, devname))
1021                 goto out;
1022
1023         if (!strncmp(uev->action, "add", 3)) {
1024                 r = uev_add_path(devname, vecs);
1025                 goto out;
1026         }
1027         if (!strncmp(uev->action, "remove", 6)) {
1028                 r = uev_remove_path(devname, vecs);
1029                 goto out;
1030         }
1031
1032 out:
1033         unlock(vecs->lock);
1034         return r;
1035 }
1036
1037 static void *
1038 ueventloop (void * ap)
1039 {
1040         if (uevent_listen(&uev_trigger, ap))
1041                 fprintf(stderr, "error starting uevent listener");
1042                 
1043         return NULL;
1044 }
1045
1046 static void *
1047 uxlsnrloop (void * ap)
1048 {
1049         if (load_keys())
1050                 return NULL;
1051         
1052         if (alloc_handlers())
1053                 return NULL;
1054
1055         add_handler(LIST+PATHS, cli_list_paths);
1056         add_handler(LIST+MAPS, cli_list_maps);
1057         add_handler(ADD+PATH, cli_add_path);
1058         add_handler(DEL+PATH, cli_del_path);
1059         add_handler(ADD+MAP, cli_add_map);
1060         add_handler(DEL+MAP, cli_del_map);
1061         add_handler(SWITCH+MAP+GROUP, cli_switch_group);
1062         add_handler(DUMP+PATHVEC, cli_dump_pathvec);
1063         add_handler(RECONFIGURE, cli_reconfigure);
1064         add_handler(SUSPEND+MAP, cli_suspend);
1065         add_handler(RESUME+MAP, cli_resume);
1066         add_handler(REINSTATE+PATH, cli_reinstate);
1067         add_handler(FAIL+PATH, cli_fail);
1068
1069         uxsock_listen(&uxsock_trigger, ap);
1070
1071         return NULL;
1072 }
1073
1074 static int
1075 exit_daemon (int status)
1076 {
1077         if (status != 0)
1078                 fprintf(stderr, "bad exit status. see daemon.log\n");
1079
1080         condlog(3, "unlink pidfile");
1081         unlink(DEFAULT_PIDFILE);
1082
1083         lock(&exit_mutex);
1084         pthread_cond_signal(&exit_cond);
1085         unlock(&exit_mutex);
1086
1087         return status;
1088 }
1089
1090 static void
1091 fail_path (struct path * pp)
1092 {
1093         if (!pp->mpp)
1094                 return;
1095
1096         condlog(2, "checker failed path %s in map %s",
1097                  pp->dev_t, pp->mpp->alias);
1098
1099         dm_fail_path(pp->mpp->alias, pp->dev_t);
1100         update_queue_mode_del_path(pp->mpp);
1101 }
1102
1103 /*
1104  * caller must have locked the path list before calling that function
1105  */
1106 static void
1107 reinstate_path (struct path * pp)
1108 {
1109         if (!pp->mpp)
1110                 return;
1111
1112         if (dm_reinstate(pp->mpp->alias, pp->dev_t))
1113                 condlog(0, "%s: reinstate failed", pp->dev_t);
1114         else {
1115                 condlog(2, "%s: reinstated", pp->dev_t);
1116                 update_queue_mode_add_path(pp->mpp);
1117         }
1118 }
1119
1120 static void
1121 enable_group(struct path * pp)
1122 {
1123         struct pathgroup * pgp;
1124
1125         /*
1126          * if path is added through uev_add_path, pgindex can be unset.
1127          * next update_strings() will set it, upon map reload event.
1128          *
1129          * we can safely return here, because upon map reload, all
1130          * PG will be enabled.
1131          */
1132         if (!pp->pgindex)
1133                 return;
1134
1135         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1136         
1137         if (pgp->status == PGSTATE_DISABLED) {
1138                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
1139                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
1140         }
1141 }
1142
1143 static void
1144 mpvec_garbage_collector (struct vectors * vecs)
1145 {
1146         struct multipath * mpp;
1147         int i;
1148
1149         vector_foreach_slot (vecs->mpvec, mpp, i) {
1150                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
1151                         condlog(2, "%s: remove dead map", mpp->alias);
1152                         remove_map(mpp, vecs);
1153                         i--;
1154                 }
1155         }
1156 }
1157
1158 static void
1159 defered_failback_tick (vector mpvec)
1160 {
1161         struct multipath * mpp;
1162         int i;
1163
1164         vector_foreach_slot (mpvec, mpp, i) {
1165                 /*
1166                  * defered failback getting sooner
1167                  */
1168                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1169                         mpp->failback_tick--;
1170
1171                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1172                                 switch_pathgroup(mpp);
1173                 }
1174         }
1175 }
1176
1177 static void
1178 retry_count_tick(vector mpvec)
1179 {
1180         struct multipath *mpp;
1181         int i;
1182
1183         vector_foreach_slot (mpvec, mpp, i) {
1184                 if (mpp->retry_tick) {
1185                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1186                         if(--mpp->retry_tick == 0) {
1187                                 dm_queue_if_no_path(mpp->alias, 0);
1188                                 condlog(2, "%s: Disable queueing", mpp->alias);
1189                         }
1190                 }
1191         }
1192 }
1193
1194 static void *
1195 checkerloop (void *ap)
1196 {
1197         struct vectors *vecs;
1198         struct path *pp;
1199         int i, count = 0;
1200         int newstate;
1201         char checker_msg[MAX_CHECKER_MSG_SIZE];
1202
1203         mlockall(MCL_CURRENT | MCL_FUTURE);
1204
1205         memset(checker_msg, 0, MAX_CHECKER_MSG_SIZE);
1206         vecs = (struct vectors *)ap;
1207
1208         condlog(2, "path checkers start up");
1209
1210         /*
1211          * init the path check interval
1212          */
1213         vector_foreach_slot (vecs->pathvec, pp, i) {
1214                 pp->checkint = conf->checkint;
1215         }
1216
1217         while (1) {
1218                 pthread_cleanup_push(cleanup_lock, vecs->lock);
1219                 lock(vecs->lock);
1220                 condlog(4, "tick");
1221
1222                 vector_foreach_slot (vecs->pathvec, pp, i) {
1223                         if (!pp->mpp)
1224                                 continue;
1225
1226                         if (pp->tick && --pp->tick)
1227                                 continue; /* don't check this path yet */
1228
1229                         /*
1230                          * provision a next check soonest,
1231                          * in case we exit abnormaly from here
1232                          */
1233                         pp->tick = conf->checkint;
1234                         
1235                         if (!pp->checkfn) {
1236                                 pathinfo(pp, conf->hwtable, DI_SYSFS);
1237                                 select_checkfn(pp);
1238                         }
1239
1240                         if (!pp->checkfn) {
1241                                 condlog(0, "%s: checkfn is void", pp->dev);
1242                                 continue;
1243                         }
1244                         newstate = pp->checkfn(pp->fd, checker_msg,
1245                                                &pp->checker_context);
1246                         
1247                         if (newstate != pp->state) {
1248                                 pp->state = newstate;
1249                                 LOG_MSG(1, checker_msg);
1250
1251                                 /*
1252                                  * upon state change, reset the checkint
1253                                  * to the shortest delay
1254                                  */
1255                                 pp->checkint = conf->checkint;
1256
1257                                 if (newstate == PATH_DOWN ||
1258                                     newstate == PATH_SHAKY) {
1259                                         /*
1260                                          * proactively fail path in the DM
1261                                          */
1262                                         fail_path(pp);
1263
1264                                         /*
1265                                          * cancel scheduled failback
1266                                          */
1267                                         pp->mpp->failback_tick = 0;
1268
1269                                         continue;
1270                                 }
1271
1272                                 /*
1273                                  * reinstate this path
1274                                  */
1275                                 reinstate_path(pp);
1276
1277                                 /*
1278                                  * need to switch group ?
1279                                  */
1280                                 update_multipath_strings(pp->mpp,
1281                                                          vecs->pathvec);
1282
1283                                 /*
1284                                  * schedule defered failback
1285                                  */
1286                                 if (pp->mpp->pgfailback > 0)
1287                                         pp->mpp->failback_tick =
1288                                                 pp->mpp->pgfailback + 1;
1289                                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
1290                                     need_switch_pathgroup(pp->mpp, 1))
1291                                         switch_pathgroup(pp->mpp);
1292
1293                                 /*
1294                                  * if at least one path is up in a group, and
1295                                  * the group is disabled, re-enable it
1296                                  */
1297                                 if (newstate == PATH_UP)
1298                                         enable_group(pp);
1299                         }
1300                         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1301                                 LOG_MSG(4, checker_msg);
1302                                 /*
1303                                  * double the next check delay.
1304                                  * max at conf->max_checkint
1305                                  */
1306                                 if (pp->checkint < (conf->max_checkint / 2))
1307                                         pp->checkint = 2 * pp->checkint;
1308                                 else
1309                                         pp->checkint = conf->max_checkint;
1310
1311                                 pp->tick = pp->checkint;
1312                                 condlog(4, "%s: delay next check %is",
1313                                                 pp->dev_t, pp->tick);
1314
1315                         }
1316                         pp->state = newstate;
1317
1318                         /*
1319                          * path prio refreshing
1320                          */
1321                         condlog(4, "path prio refresh");
1322                         pathinfo(pp, conf->hwtable, DI_PRIO);
1323
1324                         if (need_switch_pathgroup(pp->mpp, 0)) {
1325                                 if (pp->mpp->pgfailback > 0)
1326                                         pp->mpp->failback_tick =
1327                                                 pp->mpp->pgfailback + 1;
1328                                 else if (pp->mpp->pgfailback ==
1329                                                 -FAILBACK_IMMEDIATE)
1330                                         switch_pathgroup(pp->mpp);
1331                         }
1332                 }
1333                 defered_failback_tick(vecs->mpvec);
1334                 retry_count_tick(vecs->mpvec);
1335
1336                 if (count)
1337                         count--;
1338                 else {
1339                         condlog(4, "map garbage collection");
1340                         mpvec_garbage_collector(vecs);
1341                         count = MAPGCINT;
1342                 }
1343                 
1344                 lock_cleanup_pop(vecs->lock);
1345                 sleep(1);
1346         }
1347         return NULL;
1348 }
1349
1350 static struct vectors *
1351 init_paths (void)
1352 {
1353         struct vectors * vecs;
1354
1355         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1356
1357         if (!vecs)
1358                 return NULL;
1359
1360         vecs->lock = 
1361                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1362
1363         if (!vecs->lock)
1364                 goto out;
1365
1366         vecs->pathvec = vector_alloc();
1367
1368         if (!vecs->pathvec)
1369                 goto out1;
1370                 
1371         vecs->mpvec = vector_alloc();
1372
1373         if (!vecs->mpvec)
1374                 goto out2;
1375         
1376         pthread_mutex_init(vecs->lock, NULL);
1377
1378         return vecs;
1379
1380 out2:
1381         vector_free(vecs->pathvec);
1382 out1:
1383         FREE(vecs->lock);
1384 out:
1385         FREE(vecs);
1386         condlog(0, "failed to init paths");
1387         return NULL;
1388 }
1389
1390 static void *
1391 signal_set(int signo, void (*func) (int))
1392 {
1393         int r;
1394         struct sigaction sig;
1395         struct sigaction osig;
1396
1397         sig.sa_handler = func;
1398         sigemptyset(&sig.sa_mask);
1399         sig.sa_flags = 0;
1400
1401         r = sigaction(signo, &sig, &osig);
1402
1403         if (r < 0)
1404                 return (SIG_ERR);
1405         else
1406                 return (osig.sa_handler);
1407 }
1408
1409 static void
1410 sighup (int sig)
1411 {
1412         condlog(3, "SIGHUP received");
1413
1414 #ifdef _DEBUG_
1415         dbg_free_final(NULL);
1416 #endif
1417 }
1418
1419 static void
1420 sigend (int sig)
1421 {
1422         exit_daemon(0);
1423 }
1424
1425 static void
1426 signal_init(void)
1427 {
1428         signal_set(SIGHUP, sighup);
1429         signal_set(SIGINT, sigend);
1430         signal_set(SIGTERM, sigend);
1431         signal_set(SIGKILL, sigend);
1432 }
1433
1434 static void
1435 setscheduler (void)
1436 {
1437         int res;
1438         static struct sched_param sched_param = {
1439                 sched_priority: 99
1440         };
1441
1442         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1443
1444         if (res == -1)
1445                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1446         return;
1447 }
1448
1449 static void
1450 set_oom_adj (int val)
1451 {
1452         FILE *fp;
1453
1454         fp = fopen("/proc/self/oom_adj", "w");
1455
1456         if (!fp)
1457                 return;
1458
1459         fprintf(fp, "%i", val);
1460         fclose(fp);
1461 }
1462         
1463 static int
1464 child (void * param)
1465 {
1466         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1467         pthread_attr_t attr;
1468         struct vectors * vecs;
1469
1470         mlockall(MCL_CURRENT | MCL_FUTURE);
1471
1472         if (logsink)
1473                 log_thread_start();
1474
1475         condlog(2, "--------start up--------");
1476         condlog(2, "read " DEFAULT_CONFIGFILE);
1477
1478         if (load_config(DEFAULT_CONFIGFILE))
1479                 exit(1);
1480
1481         setlogmask(LOG_UPTO(conf->verbosity + 3));
1482
1483         /*
1484          * fill the voids left in the config file
1485          */
1486         if (!conf->checkint) {
1487                 conf->checkint = CHECKINT;
1488                 conf->max_checkint = MAX_CHECKINT;
1489         }
1490
1491         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1492                 if (logsink)
1493                         log_thread_stop();
1494
1495                 exit(1);
1496         }
1497         signal_init();
1498         setscheduler();
1499         set_oom_adj(-17);
1500         vecs = init_paths();
1501
1502         if (!vecs)
1503                 exit(1);
1504
1505         if (sysfs_get_mnt_path(sysfs_path, FILE_NAME_SIZE)) {
1506                 condlog(0, "can not find sysfs mount point");
1507                 exit(1);
1508         }
1509
1510         /*
1511          * fetch paths and multipaths lists
1512          * no paths and/or no multipaths are valid scenarii
1513          * vectors maintenance will be driven by events
1514          */
1515         path_discovery(vecs->pathvec, conf, DI_SYSFS | DI_WWID | DI_CHECKER);
1516         map_discovery(vecs);
1517
1518         /*
1519          * start threads
1520          */
1521         pthread_attr_init(&attr);
1522         pthread_attr_setstacksize(&attr, 64 * 1024);
1523         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1524         
1525         pthread_create(&check_thr, &attr, checkerloop, vecs);
1526         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1527         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1528
1529         pthread_cond_wait(&exit_cond, &exit_mutex);
1530
1531         /*
1532          * exit path
1533          */
1534         lock(vecs->lock);
1535         remove_maps(vecs);
1536         free_pathvec(vecs->pathvec, FREE_PATHS);
1537
1538         pthread_cancel(check_thr);
1539         pthread_cancel(uevent_thr);
1540         pthread_cancel(uxlsnr_thr);
1541
1542         free_keys(keys);
1543         keys = NULL;
1544         free_handlers(handlers);
1545         handlers = NULL;
1546         free_polls();
1547
1548         unlock(vecs->lock);
1549         pthread_mutex_destroy(vecs->lock);
1550         FREE(vecs->lock);
1551         vecs->lock = NULL;
1552         FREE(vecs);
1553         vecs = NULL;
1554         free_config(conf);
1555         conf = NULL;
1556
1557         condlog(2, "--------shut down-------");
1558         
1559         if (logsink)
1560                 log_thread_stop();
1561
1562 #ifdef _DEBUG_
1563         dbg_free_final(NULL);
1564 #endif
1565
1566         exit(0);
1567 }
1568
1569 int
1570 main (int argc, char *argv[])
1571 {
1572         extern char *optarg;
1573         extern int optind;
1574         int arg;
1575         int err;
1576         
1577         logsink = 1;
1578
1579         if (getuid() != 0) {
1580                 fprintf(stderr, "need to be root\n");
1581                 exit(1);
1582         }
1583
1584         /* make sure we don't lock any path */
1585         chdir("/");
1586         umask(umask(077) | 022);
1587
1588         conf = alloc_config();
1589
1590         if (!conf)
1591                 exit(1);
1592
1593         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1594         switch(arg) {
1595                 case 'd':
1596                         logsink = 0;
1597                         //debug=1; /* ### comment me out ### */
1598                         break;
1599                 case 'v':
1600                         if (sizeof(optarg) > sizeof(char *) ||
1601                             !isdigit(optarg[0]))
1602                                 exit(1);
1603
1604                         conf->verbosity = atoi(optarg);
1605                         break;
1606                 case 'k':
1607                         uxclnt(optarg);
1608                         exit(0);
1609                 default:
1610                         ;
1611                 }
1612         }
1613
1614         if (!logsink)
1615                 err = 0;
1616         else
1617                 err = fork();
1618         
1619         if (err < 0)
1620                 /* error */
1621                 exit(1);
1622         else if (err > 0)
1623                 /* parent dies */
1624                 exit(0);
1625         else
1626                 /* child lives */
1627                 return (child(NULL));
1628 }