[multipathd] extract a spaghetto from checkerloop()
[platform/upstream/multipath-tools.git] / multipathd / main.c
1 /*
2  * Copyright (c) 2004, 2005 Christophe Varoqui
3  * Copyright (c) 2005 Kiyoshi Ueda, NEC
4  * Copyright (c) 2005 Benjamin Marzinski, Redhat
5  * Copyright (c) 2005 Edward Goggin, EMC
6  */
7 #include <unistd.h>
8 #include <sys/stat.h>
9 #include <libdevmapper.h>
10 #include <wait.h>
11 #include <sys/mman.h>
12 #include <sys/types.h>
13 #include <fcntl.h>
14 #include <errno.h>
15
16 /*
17  * libcheckers
18  */
19 #include <checkers.h>
20
21 /*
22  * libmultipath
23  */
24 #include <parser.h>
25 #include <vector.h>
26 #include <memory.h>
27 #include <config.h>
28 #include <util.h>
29 #include <hwtable.h>
30 #include <defaults.h>
31 #include <structs.h>
32 #include <callout.h>
33 #include <blacklist.h>
34 #include <structs_vec.h>
35 #include <dmparser.h>
36 #include <devmapper.h>
37 #include <sysfs.h>
38 #include <dict.h>
39 #include <discovery.h>
40 #include <debug.h>
41 #include <propsel.h>
42 #include <uevent.h>
43 #include <switchgroup.h>
44 #include <print.h>
45 #include <configure.h>
46
47 #include "main.h"
48 #include "pidfile.h"
49 #include "uxlsnr.h"
50 #include "uxclnt.h"
51 #include "cli.h"
52 #include "cli_handlers.h"
53 #include "lock.h"
54 #include "waiter.h"
55
56 #define FILE_NAME_SIZE 256
57 #define CMDSIZE 160
58
59 #define LOG_MSG(a,b) \
60         if (strlen(b)) condlog(a, "%s: %s", pp->dev, b);
61
62 pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
63 pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
64
65 /*
66  * global copy of vecs for use in sig handlers
67  */
68 struct vectors * gvecs;
69
70 static int
71 need_switch_pathgroup (struct multipath * mpp, int refresh)
72 {
73         struct pathgroup * pgp;
74         struct path * pp;
75         unsigned int i, j;
76
77         if (!mpp || mpp->pgfailback == -FAILBACK_MANUAL)
78                 return 0;
79
80         /*
81          * Refresh path priority values
82          */
83         if (refresh)
84                 vector_foreach_slot (mpp->pg, pgp, i)
85                         vector_foreach_slot (pgp->paths, pp, j)
86                                 pathinfo(pp, conf->hwtable, DI_PRIO);
87
88         mpp->bestpg = select_path_group(mpp);
89
90         if (mpp->bestpg != mpp->nextpg)
91                 return 1;
92
93         return 0;
94 }
95
96 static void
97 switch_pathgroup (struct multipath * mpp)
98 {
99         mpp->stat_switchgroup++;
100         dm_switchgroup(mpp->alias, mpp->bestpg);
101         condlog(2, "%s: switch to path group #%i",
102                  mpp->alias, mpp->bestpg);
103 }
104
105 static int
106 coalesce_maps(struct vectors *vecs, vector nmpv)
107 {
108         struct multipath * ompp;
109         vector ompv = vecs->mpvec;
110         unsigned int i;
111         int j;
112
113         vector_foreach_slot (ompv, ompp, i) {
114                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
115                         /*
116                          * remove all current maps not allowed by the
117                          * current configuration
118                          */
119                         if (dm_flush_map(ompp->alias, DEFAULT_TARGET)) {
120                                 condlog(0, "%s: unable to flush devmap",
121                                         ompp->alias);
122                                 /*
123                                  * may be just because the device is open
124                                  */
125                                 if (!vector_alloc_slot(nmpv))
126                                         return 1;
127
128                                 vector_set_slot(nmpv, ompp);
129                                 setup_multipath(vecs, ompp);
130
131                                 if ((j = find_slot(ompv, (void *)ompp)) != -1)
132                                         vector_del_slot(ompv, j);
133
134                                 continue;
135                         }
136                         else {
137                                 dm_lib_release();
138                                 condlog(3, "%s devmap removed", ompp->alias);
139                         }
140                 }
141         }
142         return 0;
143 }
144
145 static void
146 sync_map_state(struct multipath *mpp)
147 {
148         struct pathgroup *pgp;
149         struct path *pp;
150         unsigned int i, j;
151
152         vector_foreach_slot (mpp->pg, pgp, i){
153                 vector_foreach_slot (pgp->paths, pp, j){
154                         if (pp->state <= PATH_UNCHECKED)
155                                 continue;
156                         if ((pp->dmstate == PSTATE_FAILED ||
157                              pp->dmstate == PSTATE_UNDEF) &&
158                             (pp->state == PATH_UP || pp->state == PATH_GHOST))
159                                 dm_reinstate_path(mpp->alias, pp->dev_t);
160                         else if ((pp->dmstate == PSTATE_ACTIVE ||
161                                   pp->dmstate == PSTATE_UNDEF) &&
162                                  (pp->state == PATH_DOWN ||
163                                   pp->state == PATH_SHAKY))
164                                 dm_fail_path(mpp->alias, pp->dev_t);
165                 }
166         }
167 }
168
169 static void
170 sync_maps_state(vector mpvec)
171 {
172         unsigned int i;
173         struct multipath *mpp;
174
175         vector_foreach_slot (mpvec, mpp, i)
176                 sync_map_state(mpp);
177 }
178
179 static int
180 flush_map(struct multipath * mpp, struct vectors * vecs)
181 {
182         /*
183          * clear references to this map before flushing so we can ignore
184          * the spurious uevent we may generate with the dm_flush_map call below
185          */
186         if (dm_flush_map(mpp->alias, DEFAULT_TARGET)) {
187                 /*
188                  * May not really be an error -- if the map was already flushed
189                  * from the device mapper by dmsetup(8) for instance.
190                  */
191                 condlog(0, "%s: can't flush", mpp->alias);
192                 return 1;
193         }
194         else {
195                 dm_lib_release();
196                 condlog(3, "%s: devmap removed", mpp->alias);
197         }
198
199         orphan_paths(vecs->pathvec, mpp);
200         remove_map(mpp, vecs, stop_waiter_thread, 1);
201
202         return 0;
203 }
204
205 static int
206 uev_add_map (struct sysfs_device * dev, struct vectors * vecs)
207 {
208         condlog(2, "%s: add map (uevent)", dev->kernel);
209         return ev_add_map(dev, vecs);
210 }
211
212 int
213 ev_add_map (struct sysfs_device * dev, struct vectors * vecs)
214 {
215         char * alias;
216         char *dev_t;
217         int major, minor;
218         char * refwwid;
219         struct multipath * mpp;
220         int map_present;
221         int r = 1;
222
223         dev_t = sysfs_attr_get_value(dev->devpath, "dev");
224
225         if (!dev_t || sscanf(dev_t, "%d:%d", &major, &minor) != 2)
226                 return 1;
227
228         alias = dm_mapname(major, minor);
229
230         if (!alias)
231                 return 1;
232
233         map_present = dm_map_present(alias);
234
235         if (map_present && dm_type(alias, DEFAULT_TARGET) <= 0) {
236                 condlog(4, "%s: not a multipath map", alias);
237                 return 0;
238         }
239
240         mpp = find_mp_by_alias(vecs->mpvec, alias);
241
242         if (mpp) {
243                 /*
244                  * Not really an error -- we generate our own uevent
245                  * if we create a multipath mapped device as a result
246                  * of uev_add_path
247                  */
248                 condlog(0, "%s: devmap already registered",
249                         dev->kernel);
250                 return 0;
251         }
252
253         /*
254          * now we can register the map
255          */
256         if (map_present && (mpp = add_map_without_path(vecs, minor, alias,
257                                         start_waiter_thread))) {
258                 sync_map_state(mpp);
259                 condlog(3, "%s: devmap %s added", alias, dev->kernel);
260                 return 0;
261         }
262         refwwid = get_refwwid(dev->kernel, DEV_DEVMAP, vecs->pathvec);
263
264         if (refwwid) {
265                 r = coalesce_paths(vecs, NULL, refwwid);
266                 dm_lib_release();
267         }
268
269         if (!r)
270                 condlog(3, "%s: devmap %s added", alias, dev->kernel);
271         else
272                 condlog(0, "%s: uev_add_map %s failed", alias, dev->kernel);
273
274         FREE(refwwid);
275         return r;
276 }
277
278 static int
279 uev_remove_map (struct sysfs_device * dev, struct vectors * vecs)
280 {
281         condlog(2, "%s: remove map (uevent)", dev->kernel);
282         return ev_remove_map(dev->kernel, vecs);
283 }
284
285 int
286 ev_remove_map (char * devname, struct vectors * vecs)
287 {
288         struct multipath * mpp;
289
290         mpp = find_mp_by_str(vecs->mpvec, devname);
291
292         if (!mpp) {
293                 condlog(3, "%s: devmap not registered, can't remove",
294                         devname);
295                 return 0;
296         }
297         flush_map(mpp, vecs);
298
299         return 0;
300 }
301
302 static int
303 uev_umount_map (struct sysfs_device * dev, struct vectors * vecs)
304 {
305         struct multipath * mpp;
306
307         condlog(2, "%s: umount map (uevent)", dev->kernel);
308
309         mpp = find_mp_by_str(vecs->mpvec, dev->kernel);
310
311         if (!mpp)
312                 return 0;
313
314         update_mpp_paths(mpp, vecs->pathvec);
315         verify_paths(mpp, vecs, NULL);
316
317         if (!VECTOR_SIZE(mpp->paths))
318                 flush_map(mpp, vecs);
319
320         return 0;
321 }
322
323 static int
324 uev_add_path (struct sysfs_device * dev, struct vectors * vecs)
325 {
326         condlog(2, "%s: add path (uevent)", dev->kernel);
327         return (ev_add_path(dev->kernel, vecs) != 1)? 0 : 1;
328 }
329
330
331 /*
332  * returns:
333  * 0: added
334  * 1: error
335  * 2: blacklisted
336  */
337 int
338 ev_add_path (char * devname, struct vectors * vecs)
339 {
340         struct multipath * mpp;
341         struct path * pp;
342         char empty_buff[WWID_SIZE] = {0};
343
344         pp = find_path_by_dev(vecs->pathvec, devname);
345
346         if (pp) {
347                 condlog(0, "%s: spurious uevent, path already in pathvec",
348                         devname);
349                 if (pp->mpp)
350                         return 0;
351         }
352         else {
353                 /*
354                  * get path vital state
355                  */
356                 if (!(pp = store_pathinfo(vecs->pathvec, conf->hwtable,
357                       devname, DI_ALL))) {
358                         condlog(0, "%s: failed to store path info", devname);
359                         return 1;
360                 }
361                 pp->checkint = conf->checkint;
362         }
363
364         /*
365          * need path UID to go any further
366          */
367         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
368                 condlog(0, "%s: failed to get path uid", devname);
369                 return 1; /* leave path added to pathvec */
370         }
371         if (filter_path(conf, pp)){
372                 int i = find_slot(vecs->pathvec, (void *)pp);
373                 if (i != -1)
374                         vector_del_slot(vecs->pathvec, i);
375                 free_path(pp);
376                 return 2;
377         }
378         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
379 rescan:
380         if (mpp) {
381                 if (adopt_paths(vecs->pathvec, mpp))
382                         return 1; /* leave path added to pathvec */
383
384                 verify_paths(mpp, vecs, NULL);
385                 mpp->action = ACT_RELOAD;
386         }
387         else {
388                 if ((mpp = add_map_with_path(vecs, pp, 1)))
389                         mpp->action = ACT_CREATE;
390                 else
391                         return 1; /* leave path added to pathvec */
392         }
393
394         /*
395          * push the map to the device-mapper
396          */
397         if (setup_map(mpp)) {
398                 condlog(0, "%s: failed to setup map for addition of new "
399                         "path %s", mpp->alias, devname);
400                 goto out;
401         }
402         /*
403          * reload the map for the multipath mapped device
404          */
405         if (domap(mpp) <= 0) {
406                 condlog(0, "%s: failed in domap for addition of new "
407                         "path %s", mpp->alias, devname);
408                 /*
409                  * deal with asynchronous uevents :((
410                  */
411                 if (mpp->action == ACT_RELOAD) {
412                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
413                         sleep(1);
414                         update_mpp_paths(mpp, vecs->pathvec);
415                         goto rescan;
416                 }
417                 else
418                         goto out;
419         }
420         dm_lib_release();
421
422         /*
423          * update our state from kernel regardless of create or reload
424          */
425         if (setup_multipath(vecs, mpp))
426                 goto out;
427
428         sync_map_state(mpp);
429
430         if (mpp->action == ACT_CREATE &&
431             start_waiter_thread(mpp, vecs))
432                         goto out;
433
434         condlog(3, "%s path added to devmap %s", devname, mpp->alias);
435         return 0;
436
437 out:
438         remove_map(mpp, vecs, NULL, 1);
439         return 1;
440 }
441
442 static int
443 uev_remove_path (struct sysfs_device * dev, struct vectors * vecs)
444 {
445         int retval;
446
447         condlog(2, "%s: remove path (uevent)", dev->kernel);
448         retval = ev_remove_path(dev->kernel, vecs);
449         if (!retval)
450                 sysfs_device_put(dev);
451
452         return retval;
453 }
454
455 int
456 ev_remove_path (char * devname, struct vectors * vecs)
457 {
458         struct multipath * mpp;
459         struct path * pp;
460         int i;
461         int rm_path = 1;
462
463         pp = find_path_by_dev(vecs->pathvec, devname);
464
465         if (!pp) {
466                 condlog(0, "%s: spurious uevent, path not in pathvec", devname);
467                 return 1;
468         }
469
470         /*
471          * avoid referring to the map of an orphanned path
472          */
473         if ((mpp = pp->mpp)) {
474
475                 /*
476                  * remove the map IFF removing the last path
477                  */
478                 if (pathcount(mpp, PATH_WILD) > 1) {
479                         vector rpvec = vector_alloc();
480
481                         /*
482                          * transform the mp->pg vector of vectors of paths
483                          * into a mp->params string to feed the device-mapper
484                          */
485                         update_mpp_paths(mpp, vecs->pathvec);
486                         if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
487                                 vector_del_slot(mpp->paths, i);
488
489                         if (VECTOR_SIZE(mpp->paths) == 0) {
490                                 char alias[WWID_SIZE];
491
492                                 /*
493                                  * flush_map will fail if the device is open
494                                  */
495                                 strncpy(alias, mpp->alias, WWID_SIZE);
496                                 if (flush_map(mpp, vecs))
497                                         rm_path = 0;
498                                 else
499                                         condlog(3, "%s: removed map after removing"
500                                                 " multiple paths", alias);
501                         }
502                         else {
503                                 if (setup_map(mpp)) {
504                                         condlog(0, "%s: failed to setup map for"
505                                                 " removal of path %s", mpp->alias, devname);
506                                         free_pathvec(rpvec, KEEP_PATHS);
507                                         goto out;
508                                 }
509                                 /*
510                                  * reload the map
511                                  */
512                                 mpp->action = ACT_RELOAD;
513                                 if (domap(mpp) <= 0) {
514                                         condlog(0, "%s: failed in domap for "
515                                                 "removal of path %s",
516                                                 mpp->alias, devname);
517                                         /*
518                                          * Delete path from pathvec so that
519                                          * update_mpp_paths wont find it later
520                                          * when/if another path is removed.
521                                          */
522                                         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
523                                                 vector_del_slot(vecs->pathvec, i);
524                                         free_path(pp);
525                                         return 1;
526                                 }
527                                 /*
528                                  * update our state from kernel
529                                  */
530                                 if (setup_multipath(vecs, mpp)) {
531                                         free_pathvec(rpvec, KEEP_PATHS);
532                                         goto out;
533                                 }
534                                 sync_map_state(mpp);
535
536                                 condlog(3, "%s: path removed from map %s",
537                                         devname, mpp->alias);
538                         }
539                         free_pathvec(rpvec, KEEP_PATHS);
540                 }
541                 else {
542                         char alias[WWID_SIZE];
543
544                         /*
545                          * flush_map will fail if the device is open
546                          */
547                         strncpy(alias, mpp->alias, WWID_SIZE);
548                         if (flush_map(mpp, vecs))
549                                 rm_path = 0;
550                         else
551                                 condlog(3, "%s: removed map", alias);
552                 }
553         }
554
555         if (rm_path) {
556                 if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
557                         vector_del_slot(vecs->pathvec, i);
558                 free_path(pp);
559         }
560
561         return 0;
562
563 out:
564         remove_map(mpp, vecs, stop_waiter_thread, 1);
565         return 1;
566 }
567
568 static int
569 map_discovery (struct vectors * vecs)
570 {
571         struct multipath * mpp;
572         unsigned int i;
573
574         if (dm_get_maps(vecs->mpvec, "multipath"))
575                 return 1;
576
577         vector_foreach_slot (vecs->mpvec, mpp, i)
578                 if (setup_multipath(vecs, mpp))
579                         return 1;
580
581         return 0;
582 }
583
584 int
585 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
586 {
587         struct vectors * vecs;
588         int r;
589
590         *reply = NULL;
591         *len = 0;
592         vecs = (struct vectors *)trigger_data;
593
594         pthread_cleanup_push(cleanup_lock, vecs->lock);
595         lock(vecs->lock);
596
597         r = parse_cmd(str, reply, len, vecs);
598
599         if (r > 0) {
600                 *reply = STRDUP("fail\n");
601                 *len = strlen(*reply) + 1;
602                 r = 1;
603         }
604         else if (!r && *len == 0) {
605                 *reply = STRDUP("ok\n");
606                 *len = strlen(*reply) + 1;
607                 r = 0;
608         }
609         /* else if (r < 0) leave *reply alone */
610
611         lock_cleanup_pop(vecs->lock);
612         return r;
613 }
614
615 static int
616 uev_discard(char * devpath)
617 {
618         char a[10], b[10];
619
620         /*
621          * keep only block devices, discard partitions
622          */
623         if (sscanf(devpath, "/block/%10s", a) != 1 ||
624             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
625                 condlog(4, "discard event on %s", devpath);
626                 return 1;
627         }
628         return 0;
629 }
630
631 int
632 uev_trigger (struct uevent * uev, void * trigger_data)
633 {
634         int r = 0;
635         struct sysfs_device *sysdev;
636         struct vectors * vecs;
637
638         vecs = (struct vectors *)trigger_data;
639
640         if (uev_discard(uev->devpath))
641                 return 0;
642
643         sysdev = sysfs_device_get(uev->devpath);
644         if(!sysdev)
645                 return 0;
646
647         lock(vecs->lock);
648
649         /*
650          * device map event
651          * Add events are ignored here as the tables
652          * are not fully initialised then.
653          */
654         if (!strncmp(sysdev->kernel, "dm-", 3)) {
655                 if (!strncmp(uev->action, "change", 6)) {
656                         r = uev_add_map(sysdev, vecs);
657                         goto out;
658                 }
659                 if (!strncmp(uev->action, "remove", 6)) {
660                         r = uev_remove_map(sysdev, vecs);
661                         goto out;
662                 }
663                 if (!strncmp(uev->action, "umount", 6)) {
664                         r = uev_umount_map(sysdev, vecs);
665                         goto out;
666                 }
667                 goto out;
668         }
669
670         /*
671          * path add/remove event
672          */
673         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
674                            sysdev->kernel) > 0)
675                 goto out;
676
677         if (!strncmp(uev->action, "add", 3)) {
678                 r = uev_add_path(sysdev, vecs);
679                 goto out;
680         }
681         if (!strncmp(uev->action, "remove", 6)) {
682                 r = uev_remove_path(sysdev, vecs);
683                 goto out;
684         }
685
686 out:
687         unlock(vecs->lock);
688         return r;
689 }
690
691 static void *
692 ueventloop (void * ap)
693 {
694         if (uevent_listen(&uev_trigger, ap))
695                 fprintf(stderr, "error starting uevent listener");
696
697         return NULL;
698 }
699
700 static void *
701 uxlsnrloop (void * ap)
702 {
703         if (cli_init())
704                 return NULL;
705
706         set_handler_callback(LIST+PATHS, cli_list_paths);
707         set_handler_callback(LIST+MAPS, cli_list_maps);
708         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
709         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
710         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
711         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
712         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
713         set_handler_callback(LIST+CONFIG, cli_list_config);
714         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
715         set_handler_callback(LIST+DEVICES, cli_list_devices);
716         set_handler_callback(ADD+PATH, cli_add_path);
717         set_handler_callback(DEL+PATH, cli_del_path);
718         set_handler_callback(ADD+MAP, cli_add_map);
719         set_handler_callback(DEL+MAP, cli_del_map);
720         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
721         set_handler_callback(RECONFIGURE, cli_reconfigure);
722         set_handler_callback(SUSPEND+MAP, cli_suspend);
723         set_handler_callback(RESUME+MAP, cli_resume);
724         set_handler_callback(REINSTATE+PATH, cli_reinstate);
725         set_handler_callback(FAIL+PATH, cli_fail);
726
727         uxsock_listen(&uxsock_trigger, ap);
728
729         return NULL;
730 }
731
732 static int
733 exit_daemon (int status)
734 {
735         if (status != 0)
736                 fprintf(stderr, "bad exit status. see daemon.log\n");
737
738         condlog(3, "unlink pidfile");
739         unlink(DEFAULT_PIDFILE);
740
741         lock(&exit_mutex);
742         pthread_cond_signal(&exit_cond);
743         unlock(&exit_mutex);
744
745         return status;
746 }
747
748 static void
749 fail_path (struct path * pp, int del_active)
750 {
751         if (!pp->mpp)
752                 return;
753
754         condlog(2, "checker failed path %s in map %s",
755                  pp->dev_t, pp->mpp->alias);
756
757         dm_fail_path(pp->mpp->alias, pp->dev_t);
758         if (del_active)
759                 update_queue_mode_del_path(pp->mpp);
760 }
761
762 /*
763  * caller must have locked the path list before calling that function
764  */
765 static void
766 reinstate_path (struct path * pp, int add_active)
767 {
768         if (!pp->mpp)
769                 return;
770
771         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
772                 condlog(0, "%s: reinstate failed", pp->dev_t);
773         else {
774                 condlog(2, "%s: reinstated", pp->dev_t);
775                 if (add_active)
776                         update_queue_mode_add_path(pp->mpp);
777         }
778 }
779
780 static void
781 enable_group(struct path * pp)
782 {
783         struct pathgroup * pgp;
784
785         /*
786          * if path is added through uev_add_path, pgindex can be unset.
787          * next update_strings() will set it, upon map reload event.
788          *
789          * we can safely return here, because upon map reload, all
790          * PG will be enabled.
791          */
792         if (!pp->mpp->pg || !pp->pgindex)
793                 return;
794
795         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
796
797         if (pgp->status == PGSTATE_DISABLED) {
798                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
799                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
800         }
801 }
802
803 static void
804 mpvec_garbage_collector (struct vectors * vecs)
805 {
806         struct multipath * mpp;
807         unsigned int i;
808
809         vector_foreach_slot (vecs->mpvec, mpp, i) {
810                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
811                         condlog(2, "%s: remove dead map", mpp->alias);
812                         remove_map(mpp, vecs, stop_waiter_thread, 1);
813                         i--;
814                 }
815         }
816 }
817
818 static void
819 defered_failback_tick (vector mpvec)
820 {
821         struct multipath * mpp;
822         unsigned int i;
823
824         vector_foreach_slot (mpvec, mpp, i) {
825                 /*
826                  * defered failback getting sooner
827                  */
828                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
829                         mpp->failback_tick--;
830
831                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
832                                 switch_pathgroup(mpp);
833                 }
834         }
835 }
836
837 static void
838 retry_count_tick(vector mpvec)
839 {
840         struct multipath *mpp;
841         unsigned int i;
842
843         vector_foreach_slot (mpvec, mpp, i) {
844                 if (mpp->retry_tick) {
845                         mpp->stat_total_queueing_time++;
846                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
847                         if(--mpp->retry_tick == 0) {
848                                 dm_queue_if_no_path(mpp->alias, 0);
849                                 condlog(2, "%s: Disable queueing", mpp->alias);
850                         }
851                 }
852         }
853 }
854
855 void
856 check_path (struct vectors * vecs, struct path * pp)
857 {
858         int newstate;
859
860         if (!pp->mpp)
861                 return;
862
863         if (pp->tick && --pp->tick)
864                 return; /* don't check this path yet */
865
866         /*
867          * provision a next check soonest,
868          * in case we exit abnormaly from here
869          */
870         pp->tick = conf->checkint;
871
872         if (!checker_selected(&pp->checker)) {
873                 pathinfo(pp, conf->hwtable, DI_SYSFS);
874                 select_checker(pp);
875         }
876         if (!checker_selected(&pp->checker)) {
877                 condlog(0, "%s: checker is not set", pp->dev);
878                 return;
879         }
880         /*
881          * Set checker in async mode.
882          * Honored only by checker implementing the said mode.
883          */
884         checker_set_async(&pp->checker);
885
886         newstate = checker_check(&pp->checker);
887
888         if (newstate < 0) {
889                 condlog(2, "%s: unusable path", pp->dev);
890                 pathinfo(pp, conf->hwtable, 0);
891                 return;
892         }
893         /*
894          * Async IO in flight. Keep the previous path state
895          * and reschedule as soon as possible
896          */
897         if (newstate == PATH_PENDING) {
898                 pp->tick = 1;
899                 return;
900         }
901         if (newstate != pp->state) {
902                 int oldstate = pp->state;
903                 pp->state = newstate;
904                 LOG_MSG(1, checker_message(&pp->checker));
905
906                 /*
907                  * upon state change, reset the checkint
908                  * to the shortest delay
909                  */
910                 pp->checkint = conf->checkint;
911
912                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY ||
913                     update_multipath_strings(pp->mpp, vecs->pathvec)) {
914                         /*
915                          * proactively fail path in the DM
916                          */
917                         if (oldstate == PATH_UP ||
918                             oldstate == PATH_GHOST)
919                                 fail_path(pp, 1);
920                         else
921                                 fail_path(pp, 0);
922
923                         /*
924                          * cancel scheduled failback
925                          */
926                         pp->mpp->failback_tick = 0;
927
928                         pp->mpp->stat_path_failures++;
929                         return;
930                 }
931
932                 /*
933                  * reinstate this path
934                  */
935                 if (oldstate != PATH_UP &&
936                     oldstate != PATH_GHOST)
937                         reinstate_path(pp, 1);
938                 else
939                         reinstate_path(pp, 0);
940
941                 /*
942                  * schedule [defered] failback
943                  */
944                 if (pp->mpp->pgfailback > 0)
945                         pp->mpp->failback_tick =
946                                 pp->mpp->pgfailback + 1;
947                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
948                     need_switch_pathgroup(pp->mpp, 1))
949                         switch_pathgroup(pp->mpp);
950
951                 /*
952                  * if at least one path is up in a group, and
953                  * the group is disabled, re-enable it
954                  */
955                 if (newstate == PATH_UP)
956                         enable_group(pp);
957         }
958         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
959                 LOG_MSG(4, checker_message(&pp->checker));
960                 /*
961                  * double the next check delay.
962                  * max at conf->max_checkint
963                  */
964                 if (pp->checkint < (conf->max_checkint / 2))
965                         pp->checkint = 2 * pp->checkint;
966                 else
967                         pp->checkint = conf->max_checkint;
968
969                 pp->tick = pp->checkint;
970                 condlog(4, "%s: delay next check %is",
971                                 pp->dev_t, pp->tick);
972         }
973         else if (newstate == PATH_DOWN)
974                 LOG_MSG(2, checker_message(&pp->checker));
975
976         pp->state = newstate;
977
978         /*
979          * path prio refreshing
980          */
981         condlog(4, "path prio refresh");
982         pathinfo(pp, conf->hwtable, DI_PRIO);
983
984         /*
985          * pathgroup failback policy
986          */
987         if (need_switch_pathgroup(pp->mpp, 0)) {
988                 if (pp->mpp->pgfailback > 0 &&
989                     pp->mpp->failback_tick <= 0)
990                         pp->mpp->failback_tick =
991                                 pp->mpp->pgfailback + 1;
992                 else if (pp->mpp->pgfailback ==
993                                 -FAILBACK_IMMEDIATE)
994                         switch_pathgroup(pp->mpp);
995         }
996 }
997
998 static void *
999 checkerloop (void *ap)
1000 {
1001         struct vectors *vecs;
1002         struct path *pp;
1003         int count = 0;
1004         unsigned int i;
1005
1006         mlockall(MCL_CURRENT | MCL_FUTURE);
1007         vecs = (struct vectors *)ap;
1008         condlog(2, "path checkers start up");
1009
1010         /*
1011          * init the path check interval
1012          */
1013         vector_foreach_slot (vecs->pathvec, pp, i) {
1014                 pp->checkint = conf->checkint;
1015         }
1016
1017         while (1) {
1018                 pthread_cleanup_push(cleanup_lock, vecs->lock);
1019                 lock(vecs->lock);
1020                 condlog(4, "tick");
1021
1022                 vector_foreach_slot (vecs->pathvec, pp, i) {
1023                         check_path(vecs, pp);
1024                 }
1025                 defered_failback_tick(vecs->mpvec);
1026                 retry_count_tick(vecs->mpvec);
1027
1028                 if (count)
1029                         count--;
1030                 else {
1031                         condlog(4, "map garbage collection");
1032                         mpvec_garbage_collector(vecs);
1033                         count = MAPGCINT;
1034                 }
1035
1036                 lock_cleanup_pop(vecs->lock);
1037                 sleep(1);
1038         }
1039         return NULL;
1040 }
1041
1042 int
1043 configure (struct vectors * vecs, int start_waiters)
1044 {
1045         struct multipath * mpp;
1046         struct path * pp;
1047         vector mpvec;
1048         int i;
1049
1050         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1051                 return 1;
1052
1053         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1054                 return 1;
1055
1056         if (!(mpvec = vector_alloc()))
1057                 return 1;
1058
1059         /*
1060          * probe for current path (from sysfs) and map (from dm) sets
1061          */
1062         path_discovery(vecs->pathvec, conf, DI_ALL);
1063
1064         vector_foreach_slot (vecs->pathvec, pp, i){
1065                 if (filter_path(conf, pp)){
1066                         vector_del_slot(vecs->pathvec, i);
1067                         free_path(pp);
1068                         i--;
1069                 }
1070                 else
1071                         pp->checkint = conf->checkint;
1072         }
1073         if (map_discovery(vecs))
1074                 return 1;
1075
1076         /*
1077          * create new set of maps & push changed ones into dm
1078          */
1079         if (coalesce_paths(vecs, mpvec, NULL))
1080                 return 1;
1081
1082         /*
1083          * may need to remove some maps which are no longer relevant
1084          * e.g., due to blacklist changes in conf file
1085          */
1086         if (coalesce_maps(vecs, mpvec))
1087                 return 1;
1088
1089         dm_lib_release();
1090
1091         sync_maps_state(mpvec);
1092
1093         /*
1094          * purge dm of old maps
1095          */
1096         remove_maps(vecs, NULL);
1097
1098         /*
1099          * save new set of maps formed by considering current path state
1100          */
1101         vector_free(vecs->mpvec);
1102         vecs->mpvec = mpvec;
1103
1104         /*
1105          * start dm event waiter threads for these new maps
1106          */
1107         vector_foreach_slot(vecs->mpvec, mpp, i) {
1108                 if (setup_multipath(vecs, mpp))
1109                         return 1;
1110                 if (start_waiters)
1111                         if (start_waiter_thread(mpp, vecs))
1112                                 return 1;
1113         }
1114         return 0;
1115 }
1116
1117 int
1118 reconfigure (struct vectors * vecs)
1119 {
1120         struct config * old = conf;
1121
1122         /*
1123          * free old map and path vectors ... they use old conf state
1124          */
1125         if (VECTOR_SIZE(vecs->mpvec))
1126                 remove_maps(vecs, stop_waiter_thread);
1127
1128         if (VECTOR_SIZE(vecs->pathvec))
1129                 free_pathvec(vecs->pathvec, FREE_PATHS);
1130
1131         vecs->pathvec = NULL;
1132         conf = NULL;
1133
1134         if (load_config(DEFAULT_CONFIGFILE))
1135                 return 1;
1136
1137         conf->verbosity = old->verbosity;
1138
1139         if (!conf->checkint) {
1140                 conf->checkint = DEFAULT_CHECKINT;
1141                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1142         }
1143         configure(vecs, 1);
1144         free_config(old);
1145         return 0;
1146 }
1147
1148 static struct vectors *
1149 init_vecs (void)
1150 {
1151         struct vectors * vecs;
1152
1153         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1154
1155         if (!vecs)
1156                 return NULL;
1157
1158         vecs->lock =
1159                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1160
1161         if (!vecs->lock)
1162                 goto out;
1163
1164         pthread_mutex_init(vecs->lock, NULL);
1165
1166         return vecs;
1167
1168 out:
1169         FREE(vecs);
1170         condlog(0, "failed to init paths");
1171         return NULL;
1172 }
1173
1174 static void *
1175 signal_set(int signo, void (*func) (int))
1176 {
1177         int r;
1178         struct sigaction sig;
1179         struct sigaction osig;
1180
1181         sig.sa_handler = func;
1182         sigemptyset(&sig.sa_mask);
1183         sig.sa_flags = 0;
1184
1185         r = sigaction(signo, &sig, &osig);
1186
1187         if (r < 0)
1188                 return (SIG_ERR);
1189         else
1190                 return (osig.sa_handler);
1191 }
1192
1193 static void
1194 sighup (int sig)
1195 {
1196         condlog(2, "reconfigure (SIGHUP)");
1197
1198         lock(gvecs->lock);
1199         reconfigure(gvecs);
1200         unlock(gvecs->lock);
1201
1202 #ifdef _DEBUG_
1203         dbg_free_final(NULL);
1204 #endif
1205 }
1206
1207 static void
1208 sigend (int sig)
1209 {
1210         exit_daemon(0);
1211 }
1212
1213 static void
1214 sigusr1 (int sig)
1215 {
1216         condlog(3, "SIGUSR1 received");
1217 }
1218
1219 static void
1220 signal_init(void)
1221 {
1222         signal_set(SIGHUP, sighup);
1223         signal_set(SIGUSR1, sigusr1);
1224         signal_set(SIGINT, sigend);
1225         signal_set(SIGTERM, sigend);
1226         signal(SIGPIPE, SIG_IGN);
1227 }
1228
1229 static void
1230 setscheduler (void)
1231 {
1232         int res;
1233         static struct sched_param sched_param = {
1234                 .sched_priority = 99
1235         };
1236
1237         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1238
1239         if (res == -1)
1240                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1241         return;
1242 }
1243
1244 static void
1245 set_oom_adj (int val)
1246 {
1247         FILE *fp;
1248
1249         fp = fopen("/proc/self/oom_adj", "w");
1250
1251         if (!fp)
1252                 return;
1253
1254         fprintf(fp, "%i", val);
1255         fclose(fp);
1256 }
1257
1258 static int
1259 child (void * param)
1260 {
1261         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1262         pthread_attr_t attr;
1263         struct vectors * vecs;
1264
1265         mlockall(MCL_CURRENT | MCL_FUTURE);
1266
1267         if (logsink)
1268                 log_thread_start();
1269
1270         condlog(2, "--------start up--------");
1271         condlog(2, "read " DEFAULT_CONFIGFILE);
1272
1273         if (load_config(DEFAULT_CONFIGFILE))
1274                 exit(1);
1275
1276         setlogmask(LOG_UPTO(conf->verbosity + 3));
1277
1278         /*
1279          * fill the voids left in the config file
1280          */
1281         if (!conf->checkint) {
1282                 conf->checkint = DEFAULT_CHECKINT;
1283                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1284         }
1285
1286         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1287                 if (logsink)
1288                         log_thread_stop();
1289
1290                 exit(1);
1291         }
1292         signal_init();
1293         setscheduler();
1294         set_oom_adj(-16);
1295         vecs = gvecs = init_vecs();
1296
1297         if (!vecs)
1298                 exit(1);
1299
1300         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1301                 condlog(0, "can not find sysfs mount point");
1302                 exit(1);
1303         }
1304
1305         /*
1306          * fetch and configure both paths and multipaths
1307          */
1308         if (configure(vecs, 1)) {
1309                 condlog(0, "failure during configuration");
1310                 exit(1);
1311         }
1312
1313         /*
1314          * start threads
1315          */
1316         pthread_attr_init(&attr);
1317         pthread_attr_setstacksize(&attr, 64 * 1024);
1318         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1319
1320         pthread_create(&check_thr, &attr, checkerloop, vecs);
1321         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1322         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1323
1324         pthread_cond_wait(&exit_cond, &exit_mutex);
1325
1326         /*
1327          * exit path
1328          */
1329         lock(vecs->lock);
1330         remove_maps(vecs, stop_waiter_thread);
1331         free_pathvec(vecs->pathvec, FREE_PATHS);
1332
1333         pthread_cancel(check_thr);
1334         pthread_cancel(uevent_thr);
1335         pthread_cancel(uxlsnr_thr);
1336
1337         sysfs_cleanup();
1338
1339         free_keys(keys);
1340         keys = NULL;
1341         free_handlers(handlers);
1342         handlers = NULL;
1343         free_polls();
1344
1345         unlock(vecs->lock);
1346         pthread_mutex_destroy(vecs->lock);
1347         FREE(vecs->lock);
1348         vecs->lock = NULL;
1349         FREE(vecs);
1350         vecs = NULL;
1351         free_config(conf);
1352         conf = NULL;
1353
1354         condlog(2, "--------shut down-------");
1355
1356         if (logsink)
1357                 log_thread_stop();
1358
1359         dm_lib_release();
1360         dm_lib_exit();
1361
1362 #ifdef _DEBUG_
1363         dbg_free_final(NULL);
1364 #endif
1365
1366         exit(0);
1367 }
1368
1369 static int
1370 daemonize(void)
1371 {
1372         int pid;
1373         int in_fd, out_fd;
1374
1375         if( (pid = fork()) < 0){
1376                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1377                 return -1;
1378         }
1379         else if (pid != 0)
1380                 return pid;
1381
1382         setsid();
1383
1384         if ( (pid = fork()) < 0)
1385                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1386         else if (pid != 0)
1387                 _exit(0);
1388
1389         in_fd = open("/dev/null", O_RDONLY);
1390         if (in_fd < 0){
1391                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1392                         strerror(errno));
1393                 _exit(0);
1394         }
1395         out_fd = open("/dev/console", O_WRONLY);
1396         if (out_fd < 0){
1397                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1398                         strerror(errno));
1399                 _exit(0);
1400         }
1401
1402         close(STDIN_FILENO);
1403         dup(in_fd);
1404         close(STDOUT_FILENO);
1405         dup(out_fd);
1406         close(STDERR_FILENO);
1407         dup(out_fd);
1408
1409         close(in_fd);
1410         close(out_fd);
1411         chdir("/");
1412         umask(0);
1413         return 0;
1414 }
1415
1416 int
1417 main (int argc, char *argv[])
1418 {
1419         extern char *optarg;
1420         extern int optind;
1421         int arg;
1422         int err;
1423
1424         logsink = 1;
1425         dm_init();
1426
1427         if (getuid() != 0) {
1428                 fprintf(stderr, "need to be root\n");
1429                 exit(1);
1430         }
1431
1432         /* make sure we don't lock any path */
1433         chdir("/");
1434         umask(umask(077) | 022);
1435
1436         conf = alloc_config();
1437
1438         if (!conf)
1439                 exit(1);
1440
1441         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1442         switch(arg) {
1443                 case 'd':
1444                         logsink = 0;
1445                         //debug=1; /* ### comment me out ### */
1446                         break;
1447                 case 'v':
1448                         if (sizeof(optarg) > sizeof(char *) ||
1449                             !isdigit(optarg[0]))
1450                                 exit(1);
1451
1452                         conf->verbosity = atoi(optarg);
1453                         break;
1454                 case 'k':
1455                         uxclnt(optarg);
1456                         exit(0);
1457                 default:
1458                         ;
1459                 }
1460         }
1461
1462         if (!logsink)
1463                 err = 0;
1464         else
1465                 err = daemonize();
1466
1467         if (err < 0)
1468                 /* error */
1469                 exit(1);
1470         else if (err > 0)
1471                 /* parent dies */
1472                 exit(0);
1473         else
1474                 /* child lives */
1475                 return (child(NULL));
1476 }
1477