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