7304056ec80991067f5948491cca4aa7be7b94c6
[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 a[10], b[10];
607
608         /*
609          * keep only block devices, discard partitions
610          */
611         if (sscanf(devpath, "/block/%10s", a) != 1 ||
612             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
613                 condlog(4, "discard event on %s", devpath);
614                 return 1;
615         }
616         return 0;
617 }
618
619 int
620 uev_trigger (struct uevent * uev, void * trigger_data)
621 {
622         int r = 0;
623         struct sysfs_device *sysdev;
624         struct vectors * vecs;
625
626         vecs = (struct vectors *)trigger_data;
627
628         if (uev_discard(uev->devpath))
629                 return 0;
630
631         sysdev = sysfs_device_get(uev->devpath);
632         if(!sysdev)
633                 return 0;
634
635         lock(vecs->lock);
636
637         /*
638          * device map event
639          * Add events are ignored here as the tables
640          * are not fully initialised then.
641          */
642         if (!strncmp(sysdev->kernel, "dm-", 3)) {
643                 if (!strncmp(uev->action, "change", 6)) {
644                         r = uev_add_map(sysdev, vecs);
645                         goto out;
646                 }
647                 if (!strncmp(uev->action, "remove", 6)) {
648                         r = uev_remove_map(sysdev, vecs);
649                         goto out;
650                 }
651                 if (!strncmp(uev->action, "umount", 6)) {
652                         r = uev_umount_map(sysdev, vecs);
653                         goto out;
654                 }
655                 goto out;
656         }
657
658         /*
659          * path add/remove event
660          */
661         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
662                            sysdev->kernel) > 0)
663                 goto out;
664
665         if (!strncmp(uev->action, "add", 3)) {
666                 r = uev_add_path(sysdev, vecs);
667                 goto out;
668         }
669         if (!strncmp(uev->action, "remove", 6)) {
670                 r = uev_remove_path(sysdev, vecs);
671                 goto out;
672         }
673
674 out:
675         unlock(vecs->lock);
676         return r;
677 }
678
679 static void *
680 ueventloop (void * ap)
681 {
682         if (uevent_listen(&uev_trigger, ap))
683                 fprintf(stderr, "error starting uevent listener");
684
685         return NULL;
686 }
687
688 static void *
689 uxlsnrloop (void * ap)
690 {
691         if (cli_init())
692                 return NULL;
693
694         set_handler_callback(LIST+PATHS, cli_list_paths);
695         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
696         set_handler_callback(LIST+MAPS, cli_list_maps);
697         set_handler_callback(LIST+STATUS, cli_list_status);
698         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
699         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
700         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
701         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
702         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
703         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
704         set_handler_callback(LIST+CONFIG, cli_list_config);
705         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
706         set_handler_callback(LIST+DEVICES, cli_list_devices);
707         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
708         set_handler_callback(ADD+PATH, cli_add_path);
709         set_handler_callback(DEL+PATH, cli_del_path);
710         set_handler_callback(ADD+MAP, cli_add_map);
711         set_handler_callback(DEL+MAP, cli_del_map);
712         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
713         set_handler_callback(RECONFIGURE, cli_reconfigure);
714         set_handler_callback(SUSPEND+MAP, cli_suspend);
715         set_handler_callback(RESUME+MAP, cli_resume);
716         set_handler_callback(REINSTATE+PATH, cli_reinstate);
717         set_handler_callback(FAIL+PATH, cli_fail);
718         set_handler_callback(QUIT, cli_quit);
719
720         uxsock_listen(&uxsock_trigger, ap);
721
722         return NULL;
723 }
724
725 static int
726 exit_daemon (int status)
727 {
728         if (status != 0)
729                 fprintf(stderr, "bad exit status. see daemon.log\n");
730
731         condlog(3, "unlink pidfile");
732         unlink(DEFAULT_PIDFILE);
733
734         lock(&exit_mutex);
735         pthread_cond_signal(&exit_cond);
736         unlock(&exit_mutex);
737
738         return status;
739 }
740
741 static void
742 fail_path (struct path * pp, int del_active)
743 {
744         if (!pp->mpp)
745                 return;
746
747         condlog(2, "checker failed path %s in map %s",
748                  pp->dev_t, pp->mpp->alias);
749
750         dm_fail_path(pp->mpp->alias, pp->dev_t);
751         if (del_active)
752                 update_queue_mode_del_path(pp->mpp);
753 }
754
755 /*
756  * caller must have locked the path list before calling that function
757  */
758 static void
759 reinstate_path (struct path * pp, int add_active)
760 {
761         if (!pp->mpp)
762                 return;
763
764         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
765                 condlog(0, "%s: reinstate failed", pp->dev_t);
766         else {
767                 condlog(2, "%s: reinstated", pp->dev_t);
768                 if (add_active)
769                         update_queue_mode_add_path(pp->mpp);
770         }
771 }
772
773 static void
774 enable_group(struct path * pp)
775 {
776         struct pathgroup * pgp;
777
778         /*
779          * if path is added through uev_add_path, pgindex can be unset.
780          * next update_strings() will set it, upon map reload event.
781          *
782          * we can safely return here, because upon map reload, all
783          * PG will be enabled.
784          */
785         if (!pp->mpp->pg || !pp->pgindex)
786                 return;
787
788         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
789
790         if (pgp->status == PGSTATE_DISABLED) {
791                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
792                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
793         }
794 }
795
796 static void
797 mpvec_garbage_collector (struct vectors * vecs)
798 {
799         struct multipath * mpp;
800         unsigned int i;
801
802         vector_foreach_slot (vecs->mpvec, mpp, i) {
803                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
804                         condlog(2, "%s: remove dead map", mpp->alias);
805                         remove_map_and_stop_waiter(mpp, vecs, 1);
806                         i--;
807                 }
808         }
809 }
810
811 static void
812 defered_failback_tick (vector mpvec)
813 {
814         struct multipath * mpp;
815         unsigned int i;
816
817         vector_foreach_slot (mpvec, mpp, i) {
818                 /*
819                  * defered failback getting sooner
820                  */
821                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
822                         mpp->failback_tick--;
823
824                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
825                                 switch_pathgroup(mpp);
826                 }
827         }
828 }
829
830 static void
831 retry_count_tick(vector mpvec)
832 {
833         struct multipath *mpp;
834         unsigned int i;
835
836         vector_foreach_slot (mpvec, mpp, i) {
837                 if (mpp->retry_tick) {
838                         mpp->stat_total_queueing_time++;
839                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
840                         if(--mpp->retry_tick == 0) {
841                                 dm_queue_if_no_path(mpp->alias, 0);
842                                 condlog(2, "%s: Disable queueing", mpp->alias);
843                         }
844                 }
845         }
846 }
847
848 void
849 check_path (struct vectors * vecs, struct path * pp)
850 {
851         int newstate;
852
853         if (!pp->mpp)
854                 return;
855
856         if (pp->tick && --pp->tick)
857                 return; /* don't check this path yet */
858
859         /*
860          * provision a next check soonest,
861          * in case we exit abnormaly from here
862          */
863         pp->tick = conf->checkint;
864
865         if (!checker_selected(&pp->checker)) {
866                 pathinfo(pp, conf->hwtable, DI_SYSFS);
867                 select_checker(pp);
868         }
869         if (!checker_selected(&pp->checker)) {
870                 condlog(0, "%s: checker is not set", pp->dev);
871                 return;
872         }
873         /*
874          * Set checker in async mode.
875          * Honored only by checker implementing the said mode.
876          */
877         checker_set_async(&pp->checker);
878
879         if (path_offline(pp))
880                 newstate = PATH_DOWN;
881         else
882                 newstate = checker_check(&pp->checker);
883
884         if (newstate < 0) {
885                 condlog(2, "%s: unusable path", pp->dev);
886                 pathinfo(pp, conf->hwtable, 0);
887                 return;
888         }
889         /*
890          * Async IO in flight. Keep the previous path state
891          * and reschedule as soon as possible
892          */
893         if (newstate == PATH_PENDING) {
894                 pp->tick = 1;
895                 return;
896         }
897         if (newstate != pp->state) {
898                 int oldstate = pp->state;
899                 pp->state = newstate;
900                 LOG_MSG(1, checker_message(&pp->checker));
901
902                 /*
903                  * upon state change, reset the checkint
904                  * to the shortest delay
905                  */
906                 pp->checkint = conf->checkint;
907
908                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY ||
909                     update_multipath_strings(pp->mpp, vecs->pathvec)) {
910                         /*
911                          * proactively fail path in the DM
912                          */
913                         if (oldstate == PATH_UP ||
914                             oldstate == PATH_GHOST)
915                                 fail_path(pp, 1);
916                         else
917                                 fail_path(pp, 0);
918
919                         /*
920                          * cancel scheduled failback
921                          */
922                         pp->mpp->failback_tick = 0;
923
924                         pp->mpp->stat_path_failures++;
925                         return;
926                 }
927
928                 /*
929                  * reinstate this path
930                  */
931                 if (oldstate != PATH_UP &&
932                     oldstate != PATH_GHOST)
933                         reinstate_path(pp, 1);
934                 else
935                         reinstate_path(pp, 0);
936
937                 /*
938                  * schedule [defered] failback
939                  */
940                 if (pp->mpp->pgfailback > 0)
941                         pp->mpp->failback_tick =
942                                 pp->mpp->pgfailback + 1;
943                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
944                     need_switch_pathgroup(pp->mpp, 1))
945                         switch_pathgroup(pp->mpp);
946
947                 /*
948                  * if at least one path is up in a group, and
949                  * the group is disabled, re-enable it
950                  */
951                 if (newstate == PATH_UP)
952                         enable_group(pp);
953         }
954         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
955                 LOG_MSG(4, checker_message(&pp->checker));
956                 /*
957                  * double the next check delay.
958                  * max at conf->max_checkint
959                  */
960                 if (pp->checkint < (conf->max_checkint / 2))
961                         pp->checkint = 2 * pp->checkint;
962                 else
963                         pp->checkint = conf->max_checkint;
964
965                 pp->tick = pp->checkint;
966                 condlog(4, "%s: delay next check %is",
967                                 pp->dev_t, pp->tick);
968         }
969         else if (newstate == PATH_DOWN)
970                 LOG_MSG(2, checker_message(&pp->checker));
971
972         pp->state = newstate;
973
974         /*
975          * path prio refreshing
976          */
977         condlog(4, "path prio refresh");
978         pathinfo(pp, conf->hwtable, DI_PRIO);
979
980         /*
981          * pathgroup failback policy
982          */
983         if (need_switch_pathgroup(pp->mpp, 0)) {
984                 if (pp->mpp->pgfailback > 0 &&
985                     pp->mpp->failback_tick <= 0)
986                         pp->mpp->failback_tick =
987                                 pp->mpp->pgfailback + 1;
988                 else if (pp->mpp->pgfailback ==
989                                 -FAILBACK_IMMEDIATE)
990                         switch_pathgroup(pp->mpp);
991         }
992 }
993
994 static void *
995 checkerloop (void *ap)
996 {
997         struct vectors *vecs;
998         struct path *pp;
999         int count = 0;
1000         unsigned int i;
1001
1002         mlockall(MCL_CURRENT | MCL_FUTURE);
1003         vecs = (struct vectors *)ap;
1004         condlog(2, "path checkers start up");
1005
1006         /*
1007          * init the path check interval
1008          */
1009         vector_foreach_slot (vecs->pathvec, pp, i) {
1010                 pp->checkint = conf->checkint;
1011         }
1012
1013         while (1) {
1014                 pthread_cleanup_push(cleanup_lock, vecs->lock);
1015                 lock(vecs->lock);
1016                 condlog(4, "tick");
1017
1018                 if (vecs->pathvec) {
1019                         vector_foreach_slot (vecs->pathvec, pp, i) {
1020                                 check_path(vecs, pp);
1021                         }
1022                 }
1023                 if (vecs->mpvec) {
1024                         defered_failback_tick(vecs->mpvec);
1025                         retry_count_tick(vecs->mpvec);
1026                 }
1027                 if (count)
1028                         count--;
1029                 else {
1030                         condlog(4, "map garbage collection");
1031                         mpvec_garbage_collector(vecs);
1032                         count = MAPGCINT;
1033                 }
1034
1035                 lock_cleanup_pop(vecs->lock);
1036                 sleep(1);
1037         }
1038         return NULL;
1039 }
1040
1041 int
1042 configure (struct vectors * vecs, int start_waiters)
1043 {
1044         struct multipath * mpp;
1045         struct path * pp;
1046         vector mpvec;
1047         int i;
1048
1049         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1050                 return 1;
1051
1052         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1053                 return 1;
1054
1055         if (!(mpvec = vector_alloc()))
1056                 return 1;
1057
1058         /*
1059          * probe for current path (from sysfs) and map (from dm) sets
1060          */
1061         path_discovery(vecs->pathvec, conf, DI_ALL);
1062
1063         vector_foreach_slot (vecs->pathvec, pp, i){
1064                 if (filter_path(conf, pp) > 0){
1065                         vector_del_slot(vecs->pathvec, i);
1066                         free_path(pp);
1067                         i--;
1068                 }
1069                 else
1070                         pp->checkint = conf->checkint;
1071         }
1072         if (map_discovery(vecs))
1073                 return 1;
1074
1075         /*
1076          * create new set of maps & push changed ones into dm
1077          */
1078         if (coalesce_paths(vecs, mpvec, NULL, 0))
1079                 return 1;
1080
1081         /*
1082          * may need to remove some maps which are no longer relevant
1083          * e.g., due to blacklist changes in conf file
1084          */
1085         if (coalesce_maps(vecs, mpvec))
1086                 return 1;
1087
1088         dm_lib_release();
1089
1090         sync_maps_state(mpvec);
1091
1092         /*
1093          * purge dm of old maps
1094          */
1095         remove_maps(vecs);
1096
1097         /*
1098          * save new set of maps formed by considering current path state
1099          */
1100         vector_free(vecs->mpvec);
1101         vecs->mpvec = mpvec;
1102
1103         /*
1104          * start dm event waiter threads for these new maps
1105          */
1106         vector_foreach_slot(vecs->mpvec, mpp, i) {
1107                 if (setup_multipath(vecs, mpp))
1108                         return 1;
1109                 if (start_waiters)
1110                         if (start_waiter_thread(mpp, vecs))
1111                                 return 1;
1112         }
1113         return 0;
1114 }
1115
1116 int
1117 reconfigure (struct vectors * vecs)
1118 {
1119         struct config * old = conf;
1120
1121         /*
1122          * free old map and path vectors ... they use old conf state
1123          */
1124         if (VECTOR_SIZE(vecs->mpvec))
1125                 remove_maps_and_stop_waiters(vecs);
1126
1127         if (VECTOR_SIZE(vecs->pathvec))
1128                 free_pathvec(vecs->pathvec, FREE_PATHS);
1129
1130         vecs->pathvec = NULL;
1131         conf = NULL;
1132
1133         if (load_config(DEFAULT_CONFIGFILE))
1134                 return 1;
1135
1136         conf->verbosity = old->verbosity;
1137
1138         if (!conf->checkint) {
1139                 conf->checkint = DEFAULT_CHECKINT;
1140                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1141         }
1142         configure(vecs, 1);
1143         free_config(old);
1144         return 0;
1145 }
1146
1147 static struct vectors *
1148 init_vecs (void)
1149 {
1150         struct vectors * vecs;
1151
1152         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1153
1154         if (!vecs)
1155                 return NULL;
1156
1157         vecs->lock =
1158                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1159
1160         if (!vecs->lock)
1161                 goto out;
1162
1163         pthread_mutex_init(vecs->lock, NULL);
1164
1165         return vecs;
1166
1167 out:
1168         FREE(vecs);
1169         condlog(0, "failed to init paths");
1170         return NULL;
1171 }
1172
1173 static void *
1174 signal_set(int signo, void (*func) (int))
1175 {
1176         int r;
1177         struct sigaction sig;
1178         struct sigaction osig;
1179
1180         sig.sa_handler = func;
1181         sigemptyset(&sig.sa_mask);
1182         sig.sa_flags = 0;
1183
1184         r = sigaction(signo, &sig, &osig);
1185
1186         if (r < 0)
1187                 return (SIG_ERR);
1188         else
1189                 return (osig.sa_handler);
1190 }
1191
1192 static void
1193 sighup (int sig)
1194 {
1195         condlog(2, "reconfigure (SIGHUP)");
1196
1197         lock(gvecs->lock);
1198         reconfigure(gvecs);
1199         unlock(gvecs->lock);
1200
1201 #ifdef _DEBUG_
1202         dbg_free_final(NULL);
1203 #endif
1204 }
1205
1206 static void
1207 sigend (int sig)
1208 {
1209         exit_daemon(0);
1210 }
1211
1212 static void
1213 sigusr1 (int sig)
1214 {
1215         condlog(3, "SIGUSR1 received");
1216 }
1217
1218 static void
1219 signal_init(void)
1220 {
1221         signal_set(SIGHUP, sighup);
1222         signal_set(SIGUSR1, sigusr1);
1223         signal_set(SIGINT, sigend);
1224         signal_set(SIGTERM, sigend);
1225         signal(SIGPIPE, SIG_IGN);
1226 }
1227
1228 static void
1229 setscheduler (void)
1230 {
1231         int res;
1232         static struct sched_param sched_param = {
1233                 .sched_priority = 99
1234         };
1235
1236         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1237
1238         if (res == -1)
1239                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1240         return;
1241 }
1242
1243 static void
1244 set_oom_adj (int val)
1245 {
1246         FILE *fp;
1247
1248         fp = fopen("/proc/self/oom_adj", "w");
1249
1250         if (!fp)
1251                 return;
1252
1253         fprintf(fp, "%i", val);
1254         fclose(fp);
1255 }
1256
1257 static int
1258 child (void * param)
1259 {
1260         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1261         pthread_attr_t attr;
1262         struct vectors * vecs;
1263
1264         mlockall(MCL_CURRENT | MCL_FUTURE);
1265
1266         if (logsink)
1267                 log_thread_start();
1268
1269         condlog(2, "--------start up--------");
1270         condlog(2, "read " DEFAULT_CONFIGFILE);
1271
1272         if (load_config(DEFAULT_CONFIGFILE))
1273                 exit(1);
1274
1275         if (init_checkers()) {
1276                 condlog(0, "failed to initialize checkers");
1277                 exit(1);
1278         }
1279         if (init_prio()) {
1280                 condlog(0, "failed to initialize prioritizers");
1281                 exit(1);
1282         }
1283
1284         setlogmask(LOG_UPTO(conf->verbosity + 3));
1285
1286         /*
1287          * fill the voids left in the config file
1288          */
1289         if (!conf->checkint) {
1290                 conf->checkint = DEFAULT_CHECKINT;
1291                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1292         }
1293
1294         if (conf->max_fds) {
1295                 struct rlimit fd_limit;
1296                 if (conf->max_fds > 0) {
1297                         fd_limit.rlim_cur = conf->max_fds;
1298                         fd_limit.rlim_max = conf->max_fds;
1299                 }
1300                 else {
1301                         fd_limit.rlim_cur = RLIM_INFINITY;
1302                         fd_limit.rlim_max = RLIM_INFINITY;
1303                 }
1304                 if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0)
1305                         condlog(0, "can't set open fds limit to %d : %s\n",
1306                                 conf->max_fds, strerror(errno));
1307         }
1308
1309         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1310                 if (logsink)
1311                         log_thread_stop();
1312
1313                 exit(1);
1314         }
1315         signal_init();
1316         setscheduler();
1317         set_oom_adj(-16);
1318         vecs = gvecs = init_vecs();
1319
1320         if (!vecs)
1321                 exit(1);
1322
1323         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1324                 condlog(0, "can not find sysfs mount point");
1325                 exit(1);
1326         }
1327
1328         /*
1329          * fetch and configure both paths and multipaths
1330          */
1331         if (configure(vecs, 1)) {
1332                 condlog(0, "failure during configuration");
1333                 exit(1);
1334         }
1335
1336         /*
1337          * start threads
1338          */
1339         pthread_attr_init(&attr);
1340         pthread_attr_setstacksize(&attr, 64 * 1024);
1341         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1342
1343         pthread_create(&check_thr, &attr, checkerloop, vecs);
1344         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1345         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1346
1347         pthread_cond_wait(&exit_cond, &exit_mutex);
1348
1349         /*
1350          * exit path
1351          */
1352         lock(vecs->lock);
1353         remove_maps_and_stop_waiters(vecs);
1354         free_pathvec(vecs->pathvec, FREE_PATHS);
1355
1356         pthread_cancel(check_thr);
1357         pthread_cancel(uevent_thr);
1358         pthread_cancel(uxlsnr_thr);
1359
1360         sysfs_cleanup();
1361
1362         free_keys(keys);
1363         keys = NULL;
1364         free_handlers(handlers);
1365         handlers = NULL;
1366         free_polls();
1367
1368         unlock(vecs->lock);
1369         pthread_mutex_destroy(vecs->lock);
1370         FREE(vecs->lock);
1371         vecs->lock = NULL;
1372         FREE(vecs);
1373         vecs = NULL;
1374
1375         condlog(2, "--------shut down-------");
1376
1377         if (logsink)
1378                 log_thread_stop();
1379
1380         dm_lib_release();
1381         dm_lib_exit();
1382
1383         /*
1384          * Freeing config must be done after condlog() and dm_lib_exit(),
1385          * because logging functions like dlog() and dm_write_log()
1386          * reference the config.
1387          */
1388         free_config(conf);
1389         conf = NULL;
1390
1391 #ifdef _DEBUG_
1392         dbg_free_final(NULL);
1393 #endif
1394
1395         exit(0);
1396 }
1397
1398 static int
1399 daemonize(void)
1400 {
1401         int pid;
1402         int in_fd, out_fd;
1403
1404         if( (pid = fork()) < 0){
1405                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1406                 return -1;
1407         }
1408         else if (pid != 0)
1409                 return pid;
1410
1411         setsid();
1412
1413         if ( (pid = fork()) < 0)
1414                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1415         else if (pid != 0)
1416                 _exit(0);
1417
1418         in_fd = open("/dev/null", O_RDONLY);
1419         if (in_fd < 0){
1420                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1421                         strerror(errno));
1422                 _exit(0);
1423         }
1424         out_fd = open("/dev/console", O_WRONLY);
1425         if (out_fd < 0){
1426                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1427                         strerror(errno));
1428                 _exit(0);
1429         }
1430
1431         close(STDIN_FILENO);
1432         dup(in_fd);
1433         close(STDOUT_FILENO);
1434         dup(out_fd);
1435         close(STDERR_FILENO);
1436         dup(out_fd);
1437
1438         close(in_fd);
1439         close(out_fd);
1440         chdir("/");
1441         umask(0);
1442         return 0;
1443 }
1444
1445 int
1446 main (int argc, char *argv[])
1447 {
1448         extern char *optarg;
1449         extern int optind;
1450         int arg;
1451         int err;
1452
1453         logsink = 1;
1454         dm_init();
1455
1456         if (getuid() != 0) {
1457                 fprintf(stderr, "need to be root\n");
1458                 exit(1);
1459         }
1460
1461         /* make sure we don't lock any path */
1462         chdir("/");
1463         umask(umask(077) | 022);
1464
1465         conf = alloc_config();
1466
1467         if (!conf)
1468                 exit(1);
1469
1470         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1471         switch(arg) {
1472                 case 'd':
1473                         logsink = 0;
1474                         //debug=1; /* ### comment me out ### */
1475                         break;
1476                 case 'v':
1477                         if (sizeof(optarg) > sizeof(char *) ||
1478                             !isdigit(optarg[0]))
1479                                 exit(1);
1480
1481                         conf->verbosity = atoi(optarg);
1482                         break;
1483                 case 'k':
1484                         uxclnt(optarg);
1485                         exit(0);
1486                 default:
1487                         ;
1488                 }
1489         }
1490         if (optind < argc) {
1491                 char cmd[CMDSIZE];
1492                 char * s = cmd;
1493                 char * c = s;
1494
1495                 while (optind < argc) {
1496                         if (strchr(argv[optind], ' '))
1497                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1498                         else
1499                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1500                         optind++;
1501                 }
1502                 c += snprintf(c, s + CMDSIZE - c, "\n");
1503                 uxclnt(s);
1504                 exit(0);
1505         }
1506
1507         if (!logsink)
1508                 err = 0;
1509         else
1510                 err = daemonize();
1511
1512         if (err < 0)
1513                 /* error */
1514                 exit(1);
1515         else if (err > 0)
1516                 /* parent dies */
1517                 exit(0);
1518         else
1519                 /* child lives */
1520                 return (child(NULL));
1521 }
1522