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