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