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