[multipathd] don't print headers when there is nothing to list
[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(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(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
1065         uxsock_listen(&uxsock_trigger, ap);
1066
1067         return NULL;
1068 }
1069
1070 static int
1071 exit_daemon (int status)
1072 {
1073         if (status != 0)
1074                 fprintf(stderr, "bad exit status. see daemon.log\n");
1075
1076         condlog(3, "unlink pidfile");
1077         unlink(DEFAULT_PIDFILE);
1078
1079         lock(&exit_mutex);
1080         pthread_cond_signal(&exit_cond);
1081         unlock(&exit_mutex);
1082
1083         return status;
1084 }
1085
1086 static void
1087 fail_path (struct path * pp)
1088 {
1089         if (!pp->mpp)
1090                 return;
1091
1092         condlog(2, "checker failed path %s in map %s",
1093                  pp->dev_t, pp->mpp->alias);
1094
1095         dm_fail_path(pp->mpp->alias, pp->dev_t);
1096         update_queue_mode_del_path(pp->mpp);
1097 }
1098
1099 /*
1100  * caller must have locked the path list before calling that function
1101  */
1102 static void
1103 reinstate_path (struct path * pp)
1104 {
1105         if (!pp->mpp)
1106                 return;
1107
1108         if (dm_reinstate(pp->mpp->alias, pp->dev_t))
1109                 condlog(0, "%s: reinstate failed", pp->dev_t);
1110         else {
1111                 condlog(2, "%s: reinstated", pp->dev_t);
1112                 update_queue_mode_add_path(pp->mpp);
1113         }
1114 }
1115
1116 static void
1117 enable_group(struct path * pp)
1118 {
1119         struct pathgroup * pgp;
1120
1121         /*
1122          * if path is added through uev_add_path, pgindex can be unset.
1123          * next update_strings() will set it, upon map reload event.
1124          *
1125          * we can safely return here, because upon map reload, all
1126          * PG will be enabled.
1127          */
1128         if (!pp->pgindex)
1129                 return;
1130
1131         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
1132         
1133         if (pgp->status == PGSTATE_DISABLED) {
1134                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
1135                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
1136         }
1137 }
1138
1139 static void
1140 mpvec_garbage_collector (struct vectors * vecs)
1141 {
1142         struct multipath * mpp;
1143         int i;
1144
1145         vector_foreach_slot (vecs->mpvec, mpp, i) {
1146                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
1147                         condlog(2, "%s: remove dead map", mpp->alias);
1148                         remove_map(mpp, vecs);
1149                         i--;
1150                 }
1151         }
1152 }
1153
1154 static void
1155 defered_failback_tick (vector mpvec)
1156 {
1157         struct multipath * mpp;
1158         int i;
1159
1160         vector_foreach_slot (mpvec, mpp, i) {
1161                 /*
1162                  * defered failback getting sooner
1163                  */
1164                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1165                         mpp->failback_tick--;
1166
1167                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1168                                 switch_pathgroup(mpp);
1169                 }
1170         }
1171 }
1172
1173 static void
1174 retry_count_tick(vector mpvec)
1175 {
1176         struct multipath *mpp;
1177         int i;
1178
1179         vector_foreach_slot (mpvec, mpp, i) {
1180                 if (mpp->retry_tick) {
1181                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1182                         if(--mpp->retry_tick == 0) {
1183                                 dm_queue_if_no_path(mpp->alias, 0);
1184                                 condlog(2, "%s: Disable queueing", mpp->alias);
1185                         }
1186                 }
1187         }
1188 }
1189
1190 static void *
1191 checkerloop (void *ap)
1192 {
1193         struct vectors *vecs;
1194         struct path *pp;
1195         int i, count = 0;
1196         int newstate;
1197         char checker_msg[MAX_CHECKER_MSG_SIZE];
1198
1199         mlockall(MCL_CURRENT | MCL_FUTURE);
1200
1201         memset(checker_msg, 0, MAX_CHECKER_MSG_SIZE);
1202         vecs = (struct vectors *)ap;
1203
1204         condlog(2, "path checkers start up");
1205
1206         /*
1207          * init the path check interval
1208          */
1209         vector_foreach_slot (vecs->pathvec, pp, i) {
1210                 pp->checkint = conf->checkint;
1211         }
1212
1213         while (1) {
1214                 pthread_cleanup_push(cleanup_lock, vecs->lock);
1215                 lock(vecs->lock);
1216                 condlog(4, "tick");
1217
1218                 vector_foreach_slot (vecs->pathvec, pp, i) {
1219                         if (!pp->mpp)
1220                                 continue;
1221
1222                         if (pp->tick && --pp->tick)
1223                                 continue; /* don't check this path yet */
1224
1225                         /*
1226                          * provision a next check soonest,
1227                          * in case we exit abnormaly from here
1228                          */
1229                         pp->tick = conf->checkint;
1230                         
1231                         if (!pp->checkfn) {
1232                                 pathinfo(pp, conf->hwtable, DI_SYSFS);
1233                                 select_checkfn(pp);
1234                         }
1235
1236                         if (!pp->checkfn) {
1237                                 condlog(0, "%s: checkfn is void", pp->dev);
1238                                 continue;
1239                         }
1240                         newstate = pp->checkfn(pp->fd, checker_msg,
1241                                                &pp->checker_context);
1242                         
1243                         if (newstate != pp->state) {
1244                                 pp->state = newstate;
1245                                 LOG_MSG(1, checker_msg);
1246
1247                                 /*
1248                                  * upon state change, reset the checkint
1249                                  * to the shortest delay
1250                                  */
1251                                 pp->checkint = conf->checkint;
1252
1253                                 if (newstate == PATH_DOWN ||
1254                                     newstate == PATH_SHAKY) {
1255                                         /*
1256                                          * proactively fail path in the DM
1257                                          */
1258                                         fail_path(pp);
1259
1260                                         /*
1261                                          * cancel scheduled failback
1262                                          */
1263                                         pp->mpp->failback_tick = 0;
1264
1265                                         continue;
1266                                 }
1267
1268                                 /*
1269                                  * reinstate this path
1270                                  */
1271                                 reinstate_path(pp);
1272
1273                                 /*
1274                                  * need to switch group ?
1275                                  */
1276                                 update_multipath_strings(pp->mpp,
1277                                                          vecs->pathvec);
1278
1279                                 /*
1280                                  * schedule defered failback
1281                                  */
1282                                 if (pp->mpp->pgfailback > 0)
1283                                         pp->mpp->failback_tick =
1284                                                 pp->mpp->pgfailback + 1;
1285                                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
1286                                     need_switch_pathgroup(pp->mpp, 1))
1287                                         switch_pathgroup(pp->mpp);
1288
1289                                 /*
1290                                  * if at least one path is up in a group, and
1291                                  * the group is disabled, re-enable it
1292                                  */
1293                                 if (newstate == PATH_UP)
1294                                         enable_group(pp);
1295                         }
1296                         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1297                                 LOG_MSG(4, checker_msg);
1298                                 /*
1299                                  * double the next check delay.
1300                                  * max at conf->max_checkint
1301                                  */
1302                                 if (pp->checkint < (conf->max_checkint / 2))
1303                                         pp->checkint = 2 * pp->checkint;
1304                                 else
1305                                         pp->checkint = conf->max_checkint;
1306
1307                                 pp->tick = pp->checkint;
1308                                 condlog(4, "%s: delay next check %is",
1309                                                 pp->dev_t, pp->tick);
1310
1311                         }
1312                         pp->state = newstate;
1313
1314                         /*
1315                          * path prio refreshing
1316                          */
1317                         condlog(4, "path prio refresh");
1318                         pathinfo(pp, conf->hwtable, DI_PRIO);
1319
1320                         if (need_switch_pathgroup(pp->mpp, 0)) {
1321                                 if (pp->mpp->pgfailback > 0)
1322                                         pp->mpp->failback_tick =
1323                                                 pp->mpp->pgfailback + 1;
1324                                 else if (pp->mpp->pgfailback ==
1325                                                 -FAILBACK_IMMEDIATE)
1326                                         switch_pathgroup(pp->mpp);
1327                         }
1328                 }
1329                 defered_failback_tick(vecs->mpvec);
1330                 retry_count_tick(vecs->mpvec);
1331
1332                 if (count)
1333                         count--;
1334                 else {
1335                         condlog(4, "map garbage collection");
1336                         mpvec_garbage_collector(vecs);
1337                         count = MAPGCINT;
1338                 }
1339                 
1340                 lock_cleanup_pop(vecs->lock);
1341                 sleep(1);
1342         }
1343         return NULL;
1344 }
1345
1346 static struct vectors *
1347 init_paths (void)
1348 {
1349         struct vectors * vecs;
1350
1351         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1352
1353         if (!vecs)
1354                 return NULL;
1355
1356         vecs->lock = 
1357                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1358
1359         if (!vecs->lock)
1360                 goto out;
1361
1362         vecs->pathvec = vector_alloc();
1363
1364         if (!vecs->pathvec)
1365                 goto out1;
1366                 
1367         vecs->mpvec = vector_alloc();
1368
1369         if (!vecs->mpvec)
1370                 goto out2;
1371         
1372         pthread_mutex_init(vecs->lock, NULL);
1373
1374         return vecs;
1375
1376 out2:
1377         vector_free(vecs->pathvec);
1378 out1:
1379         FREE(vecs->lock);
1380 out:
1381         FREE(vecs);
1382         condlog(0, "failed to init paths");
1383         return NULL;
1384 }
1385
1386 static void *
1387 signal_set(int signo, void (*func) (int))
1388 {
1389         int r;
1390         struct sigaction sig;
1391         struct sigaction osig;
1392
1393         sig.sa_handler = func;
1394         sigemptyset(&sig.sa_mask);
1395         sig.sa_flags = 0;
1396
1397         r = sigaction(signo, &sig, &osig);
1398
1399         if (r < 0)
1400                 return (SIG_ERR);
1401         else
1402                 return (osig.sa_handler);
1403 }
1404
1405 static void
1406 sighup (int sig)
1407 {
1408         condlog(3, "SIGHUP received");
1409
1410 #ifdef _DEBUG_
1411         dbg_free_final(NULL);
1412 #endif
1413 }
1414
1415 static void
1416 sigend (int sig)
1417 {
1418         exit_daemon(0);
1419 }
1420
1421 static void
1422 signal_init(void)
1423 {
1424         signal_set(SIGHUP, sighup);
1425         signal_set(SIGINT, sigend);
1426         signal_set(SIGTERM, sigend);
1427         signal_set(SIGKILL, sigend);
1428 }
1429
1430 static void
1431 setscheduler (void)
1432 {
1433         int res;
1434         static struct sched_param sched_param = {
1435                 sched_priority: 99
1436         };
1437
1438         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1439
1440         if (res == -1)
1441                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1442         return;
1443 }
1444
1445 static void
1446 set_oom_adj (int val)
1447 {
1448         FILE *fp;
1449
1450         fp = fopen("/proc/self/oom_adj", "w");
1451
1452         if (!fp)
1453                 return;
1454
1455         fprintf(fp, "%i", val);
1456         fclose(fp);
1457 }
1458         
1459 static int
1460 child (void * param)
1461 {
1462         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1463         pthread_attr_t attr;
1464         struct vectors * vecs;
1465
1466         mlockall(MCL_CURRENT | MCL_FUTURE);
1467
1468         if (logsink)
1469                 log_thread_start();
1470
1471         condlog(2, "--------start up--------");
1472         condlog(2, "read " DEFAULT_CONFIGFILE);
1473
1474         if (load_config(DEFAULT_CONFIGFILE))
1475                 exit(1);
1476
1477         setlogmask(LOG_UPTO(conf->verbosity + 3));
1478
1479         /*
1480          * fill the voids left in the config file
1481          */
1482         if (!conf->checkint) {
1483                 conf->checkint = CHECKINT;
1484                 conf->max_checkint = MAX_CHECKINT;
1485         }
1486
1487         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1488                 if (logsink)
1489                         log_thread_stop();
1490
1491                 exit(1);
1492         }
1493         signal_init();
1494         setscheduler();
1495         set_oom_adj(-17);
1496         vecs = init_paths();
1497
1498         if (!vecs)
1499                 exit(1);
1500
1501         if (sysfs_get_mnt_path(sysfs_path, FILE_NAME_SIZE)) {
1502                 condlog(0, "can not find sysfs mount point");
1503                 exit(1);
1504         }
1505
1506         /*
1507          * fetch paths and multipaths lists
1508          * no paths and/or no multipaths are valid scenarii
1509          * vectors maintenance will be driven by events
1510          */
1511         path_discovery(vecs->pathvec, conf, DI_SYSFS | DI_WWID | DI_CHECKER);
1512         map_discovery(vecs);
1513
1514         /*
1515          * start threads
1516          */
1517         pthread_attr_init(&attr);
1518         pthread_attr_setstacksize(&attr, 64 * 1024);
1519         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1520         
1521         pthread_create(&check_thr, &attr, checkerloop, vecs);
1522         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1523         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1524
1525         pthread_cond_wait(&exit_cond, &exit_mutex);
1526
1527         /*
1528          * exit path
1529          */
1530         lock(vecs->lock);
1531         remove_maps(vecs);
1532         free_pathvec(vecs->pathvec, FREE_PATHS);
1533
1534         pthread_cancel(check_thr);
1535         pthread_cancel(uevent_thr);
1536         pthread_cancel(uxlsnr_thr);
1537
1538         free_keys(keys);
1539         keys = NULL;
1540         free_handlers(handlers);
1541         handlers = NULL;
1542         free_polls();
1543
1544         unlock(vecs->lock);
1545         pthread_mutex_destroy(vecs->lock);
1546         FREE(vecs->lock);
1547         vecs->lock = NULL;
1548         FREE(vecs);
1549         vecs = NULL;
1550         free_config(conf);
1551         conf = NULL;
1552
1553         condlog(2, "--------shut down-------");
1554         
1555         if (logsink)
1556                 log_thread_stop();
1557
1558 #ifdef _DEBUG_
1559         dbg_free_final(NULL);
1560 #endif
1561
1562         exit(0);
1563 }
1564
1565 int
1566 main (int argc, char *argv[])
1567 {
1568         extern char *optarg;
1569         extern int optind;
1570         int arg;
1571         int err;
1572         
1573         logsink = 1;
1574
1575         if (getuid() != 0) {
1576                 fprintf(stderr, "need to be root\n");
1577                 exit(1);
1578         }
1579
1580         /* make sure we don't lock any path */
1581         chdir("/");
1582         umask(umask(077) | 022);
1583
1584         conf = alloc_config();
1585
1586         if (!conf)
1587                 exit(1);
1588
1589         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1590         switch(arg) {
1591                 case 'd':
1592                         logsink = 0;
1593                         //debug=1; /* ### comment me out ### */
1594                         break;
1595                 case 'v':
1596                         if (sizeof(optarg) > sizeof(char *) ||
1597                             !isdigit(optarg[0]))
1598                                 exit(1);
1599
1600                         conf->verbosity = atoi(optarg);
1601                         break;
1602                 case 'k':
1603                         uxclnt(optarg);
1604                         exit(0);
1605                 default:
1606                         ;
1607                 }
1608         }
1609
1610         if (!logsink)
1611                 err = 0;
1612         else
1613                 err = fork();
1614         
1615         if (err < 0)
1616                 /* error */
1617                 exit(1);
1618         else if (err > 0)
1619                 /* parent dies */
1620                 exit(0);
1621         else
1622                 /* child lives */
1623                 return (child(NULL));
1624 }