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