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