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