[multipathd] plug a small leak on "reconfigure" 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
16 /*
17  * libsysfs
18  */
19 #include <sysfs/libsysfs.h>
20 #include <sysfs/dlist.h>
21
22 /*
23  * libcheckers
24  */
25 #include <checkers.h>
26
27 /*
28  * libmultipath
29  */
30 #include <parser.h>
31 #include <vector.h>
32 #include <memory.h>
33 #include <config.h>
34 #include <util.h>
35 #include <hwtable.h>
36 #include <defaults.h>
37 #include <structs.h>
38 #include <callout.h>
39 #include <blacklist.h>
40 #include <structs_vec.h>
41 #include <dmparser.h>
42 #include <devmapper.h>
43 #include <dict.h>
44 #include <discovery.h>
45 #include <debug.h>
46 #include <propsel.h>
47 #include <uevent.h>
48 #include <switchgroup.h>
49 #include <print.h>
50 #include <configure.h>
51
52 #include "main.h"
53 #include "pidfile.h"
54 #include "uxlsnr.h"
55 #include "uxclnt.h"
56 #include "cli.h"
57 #include "cli_handlers.h"
58 #include "lock.h"
59 #include "waiter.h"
60
61 #define FILE_NAME_SIZE 256
62 #define CMDSIZE 160
63
64 #define LOG_MSG(a,b) \
65         if (strlen(b)) condlog(a, "%s: %s", pp->dev_t, b);
66
67 pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
68 pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
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         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         int i, j;
116
117         vector_foreach_slot (ompv, ompp, i) {
118                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
119                         /*
120                          * remove all current maps not allowed by the
121                          * current configuration
122                          */
123                         if (dm_flush_map(ompp->alias, DEFAULT_TARGET)) {
124                                 condlog(0, "%s: unable to flush devmap",
125                                         ompp->alias);
126                                 /*
127                                  * may be just because the device is open
128                                  */
129                                 if (!vector_alloc_slot(nmpv))
130                                         return 1;
131
132                                 vector_set_slot(nmpv, ompp);
133                                 setup_multipath(vecs, ompp);
134
135                                 if ((j = find_slot(ompv, (void *)ompp)) != -1)
136                                         vector_del_slot(ompv, j);
137
138                                 continue;
139                         }
140                         else {
141                                 dm_lib_release();
142                                 condlog(3, "%s devmap removed", ompp->alias);
143                         }
144                 }
145         }
146         return 0;
147 }
148
149 static void
150 sync_map_state(struct multipath *mpp)
151 {
152         int i, j;
153         struct pathgroup *pgp;
154         struct path *pp;
155
156         vector_foreach_slot (mpp->pg, pgp, i){
157                 vector_foreach_slot (pgp->paths, pp, j){
158                         if (pp->state <= PATH_UNCHECKED)
159                                 continue;
160                         if ((pp->dmstate == PSTATE_FAILED ||
161                              pp->dmstate == PSTATE_UNDEF) &&
162                             (pp->state == PATH_UP || pp->state == PATH_GHOST))
163                                 dm_reinstate_path(mpp->alias, pp->dev_t);
164                         else if ((pp->dmstate == PSTATE_ACTIVE ||
165                                   pp->dmstate == PSTATE_UNDEF) &&
166                                  (pp->state == PATH_DOWN ||
167                                   pp->state == PATH_SHAKY))
168                                 dm_fail_path(mpp->alias, pp->dev_t);
169                 }
170         }
171 }
172
173 static void
174 sync_maps_state(vector mpvec)
175 {
176         int i;
177         struct multipath *mpp;
178
179         vector_foreach_slot (mpvec, mpp, i) 
180                 sync_map_state(mpp);
181 }
182
183 static int
184 flush_map(struct multipath * mpp, struct vectors * vecs)
185 {
186         /*
187          * clear references to this map before flushing so we can ignore
188          * the spurious uevent we may generate with the dm_flush_map call below
189          */
190         if (dm_flush_map(mpp->alias, DEFAULT_TARGET)) {
191                 /*
192                  * May not really be an error -- if the map was already flushed
193                  * from the device mapper by dmsetup(8) for instance.
194                  */
195                 condlog(0, "%s: can't flush", mpp->alias);
196                 return 1;
197         }
198         else {
199                 dm_lib_release();
200                 condlog(3, "%s: devmap removed", mpp->alias);
201         }
202
203         orphan_paths(vecs->pathvec, mpp);
204         remove_map(mpp, vecs, stop_waiter_thread, 1);
205
206         return 0;
207 }
208
209 static int
210 uev_add_map (char * devname, struct vectors * vecs)
211 {
212         condlog(2, "%s: add map (uevent)", devname);
213         return ev_add_map(devname, vecs);
214 }
215
216 int
217 ev_add_map (char * devname, struct vectors * vecs)
218 {
219         int major, minor;
220         char dev_t[BLK_DEV_SIZE];
221         char * alias;
222         char * refwwid;
223         struct multipath * mpp;
224         int map_present;
225         int r = 1;
226
227         if (sscanf(devname, "dm-%d", &minor) == 1 &&
228             !sysfs_get_dev(sysfs_path, devname, dev_t, BLK_DEV_SIZE) &&
229             sscanf(dev_t, "%d:%d", &major, &minor) == 2)
230                 alias = dm_mapname(major, minor);
231         else
232                 alias = STRDUP(devname);
233                 
234         if (!alias)
235                 return 1;
236         
237         map_present = dm_map_present(alias);
238
239         if (map_present && dm_type(alias, DEFAULT_TARGET) <= 0) {
240                 condlog(4, "%s: not a multipath map", alias);
241                 FREE(alias);
242                 return 0;
243         }
244
245         mpp = find_mp_by_alias(vecs->mpvec, alias);
246
247         if (mpp) {
248                 /*
249                  * Not really an error -- we generate our own uevent
250                  * if we create a multipath mapped device as a result
251                  * of uev_add_path
252                  */
253                 condlog(0, "%s: devmap already registered",
254                         devname);
255                 FREE(alias);
256                 return 0;
257         }
258
259         /*
260          * now we can register the map
261          */
262         if (map_present && (mpp = add_map_without_path(vecs, minor, alias,
263                                         start_waiter_thread))) {
264                 sync_map_state(mpp);
265                 condlog(3, "%s: devmap %s added", alias, devname);
266                 return 0;
267         }
268         refwwid = get_refwwid(devname, DEV_DEVMAP, vecs->pathvec);
269
270         if (refwwid) {
271                 r = coalesce_paths(vecs, NULL, refwwid);
272                 dm_lib_release();
273         }
274         
275         if (!r)
276                 condlog(3, "%s: devmap %s added", alias, devname);
277         else
278                 condlog(0, "%s: uev_add_map %s failed", alias, devname);
279
280         FREE(refwwid);
281         FREE(alias);
282         return r;
283 }
284
285 static int
286 uev_remove_map (char * devname, struct vectors * vecs)
287 {
288         condlog(2, "%s: remove map (uevent)", devname);
289         return ev_remove_map(devname, 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(3, "%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 (char * devname, struct vectors * vecs)
311 {
312         struct multipath * mpp;
313
314         condlog(2, "%s: umount map (uevent)", devname);
315
316         mpp = find_mp_by_str(vecs->mpvec, devname);
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 (char * devname, struct vectors * vecs)
332 {
333         condlog(2, "%s: add path (uevent)", devname);
334         return (ev_add_path(devname, 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 (blacklist_path(conf, pp)){
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(3, "%s path added to devmap %s", devname, mpp->alias);
442         return 0;
443
444 out:
445         remove_map(mpp, vecs, NULL, 1);
446         return 1;
447 }
448
449 static int
450 uev_remove_path (char * devname, struct vectors * vecs)
451 {
452         condlog(2, "%s: remove path (uevent)", devname);
453         return ev_remove_path(devname, vecs);
454 }
455
456 int
457 ev_remove_path (char * devname, struct vectors * vecs)
458 {
459         struct multipath * mpp;
460         struct path * pp;
461         int i;
462         int rm_path = 1;
463
464         pp = find_path_by_dev(vecs->pathvec, devname);
465
466         if (!pp) {
467                 condlog(0, "%s: spurious uevent, path not in pathvec", devname);
468                 return 1;
469         }
470
471         /*
472          * avoid referring to the map of an orphanned path
473          */
474         if ((mpp = pp->mpp)) {
475
476                 /*
477                  * remove the map IFF removing the last path
478                  */
479                 if (pathcount(mpp, PATH_WILD) > 1) {
480                         vector rpvec = vector_alloc();
481
482                         /*
483                          * transform the mp->pg vector of vectors of paths
484                          * into a mp->params string to feed the device-mapper
485                          */
486                         update_mpp_paths(mpp, vecs->pathvec);
487                         if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
488                                 vector_del_slot(mpp->paths, i);
489
490                         if (VECTOR_SIZE(mpp->paths) == 0) {
491                                 char alias[WWID_SIZE];
492
493                                 /*
494                                  * flush_map will fail if the device is open
495                                  */
496                                 strncpy(alias, mpp->alias, WWID_SIZE);
497                                 if (flush_map(mpp, vecs))
498                                         rm_path = 0;
499                                 else
500                                         condlog(3, "%s: removed map after removing"
501                                                 " multiple paths", alias);
502                         }
503                         else {
504                                 if (setup_map(mpp)) {
505                                         condlog(0, "%s: failed to setup map for"
506                                                 " removal of path %s", mpp->alias, devname);
507                                         free_pathvec(rpvec, KEEP_PATHS);
508                                         goto out;
509                                 }
510                                 /*
511                                  * reload the map
512                                  */
513                                 mpp->action = ACT_RELOAD;
514                                 if (domap(mpp) <= 0) {
515                                         condlog(0, "%s: failed in domap for "
516                                                 "removal of path %s",
517                                                 mpp->alias, devname);
518                                         /*
519                                          * Delete path from pathvec so that
520                                          * update_mpp_paths wont find it later
521                                          * when/if another path is removed.
522                                          */
523                                         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
524                                                 vector_del_slot(vecs->pathvec, i);
525                                         free_path(pp);
526                                         return 1;
527                                 }
528                                 /*
529                                  * update our state from kernel
530                                  */
531                                 if (setup_multipath(vecs, mpp)) {
532                                         free_pathvec(rpvec, KEEP_PATHS);
533                                         goto out;
534                                 }
535                                 sync_map_state(mpp);
536
537                                 condlog(3, "%s path removed from devmap %s",
538                                         devname, mpp->alias);
539                         }
540                         free_pathvec(rpvec, KEEP_PATHS);
541                 }
542                 else {
543                         char alias[WWID_SIZE];
544
545                         /*
546                          * flush_map will fail if the device is open
547                          */
548                         strncpy(alias, mpp->alias, WWID_SIZE);
549                         if (flush_map(mpp, vecs))
550                                 rm_path = 0;
551                         else
552                                 condlog(3, "%s: removed map", alias);
553                 }
554         }
555
556         if (rm_path) {
557                 if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
558                         vector_del_slot(vecs->pathvec, i);
559                 free_path(pp);
560         }
561
562         return 0;
563
564 out:
565         remove_map(mpp, vecs, stop_waiter_thread, 1);
566         return 1;
567 }
568
569 static int
570 map_discovery (struct vectors * vecs)
571 {
572         int i;
573         struct multipath * mpp;
574
575         if (dm_get_maps(vecs->mpvec, "multipath"))
576                 return 1;
577
578         vector_foreach_slot (vecs->mpvec, mpp, i)
579                 if (setup_multipath(vecs, mpp))
580                         return 1;
581
582         return 0;
583 }
584
585 int
586 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
587 {
588         struct vectors * vecs;
589         int r;
590         
591         *reply = NULL;
592         *len = 0;
593         vecs = (struct vectors *)trigger_data;
594
595         pthread_cleanup_push(cleanup_lock, vecs->lock);
596         lock(vecs->lock);
597
598         r = parse_cmd(str, reply, len, vecs);
599
600         if (r > 0) {
601                 *reply = STRDUP("fail\n");
602                 *len = strlen(*reply) + 1;
603                 r = 1;
604         }
605         else if (!r && *len == 0) {
606                 *reply = STRDUP("ok\n");
607                 *len = strlen(*reply) + 1;
608                 r = 0;
609         }
610         /* else if (r < 0) leave *reply alone */
611
612         lock_cleanup_pop(vecs->lock);
613         return r;
614 }
615
616 static int
617 uev_discard(char * devpath)
618 {
619         char a[10], b[10];
620
621         /*
622          * keep only block devices, discard partitions
623          */
624         if (sscanf(devpath, "/block/%10s", a) != 1 ||
625             sscanf(devpath, "/block/%10[^/]/%10s", a, b) == 2) {
626                 condlog(4, "discard event on %s", devpath);
627                 return 1;
628         }
629         return 0;
630 }
631
632 int 
633 uev_trigger (struct uevent * uev, void * trigger_data)
634 {
635         int r = 0;
636         char devname[32];
637         struct vectors * vecs;
638
639         vecs = (struct vectors *)trigger_data;
640
641         if (uev_discard(uev->devpath))
642                 return 0;
643
644         basename(uev->devpath, devname);
645         lock(vecs->lock);
646
647         /*
648          * device map add/remove event
649          */
650         if (!strncmp(devname, "dm-", 3)) {
651                 if (!strncmp(uev->action, "add", 3)) {
652                         r = uev_add_map(devname, vecs);
653                         goto out;
654                 }
655                 if (!strncmp(uev->action, "remove", 6)) {
656                         r = uev_remove_map(devname, vecs);
657                         goto out;
658                 }
659                 if (!strncmp(uev->action, "umount", 6)) {
660                         r = uev_umount_map(devname, vecs);
661                         goto out;
662                 }
663                 goto out;
664         }
665         
666         /*
667          * path add/remove event
668          */
669         if (blacklist(conf->blist_devnode, devname))
670                 goto out;
671
672         if (!strncmp(uev->action, "add", 3)) {
673                 r = uev_add_path(devname, vecs);
674                 goto out;
675         }
676         if (!strncmp(uev->action, "remove", 6)) {
677                 r = uev_remove_path(devname, vecs);
678                 goto out;
679         }
680
681 out:
682         unlock(vecs->lock);
683         return r;
684 }
685
686 static void *
687 ueventloop (void * ap)
688 {
689         if (uevent_listen(&uev_trigger, ap))
690                 fprintf(stderr, "error starting uevent listener");
691                 
692         return NULL;
693 }
694
695 static void *
696 uxlsnrloop (void * ap)
697 {
698         if (load_keys())
699                 return NULL;
700         
701         if (alloc_handlers())
702                 return NULL;
703
704         add_handler(LIST+PATHS, cli_list_paths);
705         add_handler(LIST+MAPS, cli_list_maps);
706         add_handler(LIST+MAPS+STATUS, cli_list_maps_status);
707         add_handler(LIST+MAPS+STATS, cli_list_maps_stats);
708         add_handler(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
709         add_handler(LIST+TOPOLOGY, cli_list_maps_topology);
710         add_handler(LIST+MAP+TOPOLOGY, cli_list_map_topology);
711         add_handler(LIST+CONFIG, cli_list_config);
712         add_handler(ADD+PATH, cli_add_path);
713         add_handler(DEL+PATH, cli_del_path);
714         add_handler(ADD+MAP, cli_add_map);
715         add_handler(DEL+MAP, cli_del_map);
716         add_handler(SWITCH+MAP+GROUP, cli_switch_group);
717         add_handler(RECONFIGURE, cli_reconfigure);
718         add_handler(SUSPEND+MAP, cli_suspend);
719         add_handler(RESUME+MAP, cli_resume);
720         add_handler(REINSTATE+PATH, cli_reinstate);
721         add_handler(FAIL+PATH, cli_fail);
722
723         uxsock_listen(&uxsock_trigger, ap);
724
725         return NULL;
726 }
727
728 static int
729 exit_daemon (int status)
730 {
731         if (status != 0)
732                 fprintf(stderr, "bad exit status. see daemon.log\n");
733
734         condlog(3, "unlink pidfile");
735         unlink(DEFAULT_PIDFILE);
736
737         lock(&exit_mutex);
738         pthread_cond_signal(&exit_cond);
739         unlock(&exit_mutex);
740
741         return status;
742 }
743
744 static void
745 fail_path (struct path * pp, int del_active)
746 {
747         if (!pp->mpp)
748                 return;
749
750         condlog(2, "checker failed path %s in map %s",
751                  pp->dev_t, pp->mpp->alias);
752
753         dm_fail_path(pp->mpp->alias, pp->dev_t);
754         if (del_active)
755                 update_queue_mode_del_path(pp->mpp);
756 }
757
758 /*
759  * caller must have locked the path list before calling that function
760  */
761 static void
762 reinstate_path (struct path * pp, int add_active)
763 {
764         if (!pp->mpp)
765                 return;
766
767         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
768                 condlog(0, "%s: reinstate failed", pp->dev_t);
769         else {
770                 condlog(2, "%s: reinstated", pp->dev_t);
771                 if (add_active)
772                         update_queue_mode_add_path(pp->mpp);
773         }
774 }
775
776 static void
777 enable_group(struct path * pp)
778 {
779         struct pathgroup * pgp;
780
781         /*
782          * if path is added through uev_add_path, pgindex can be unset.
783          * next update_strings() will set it, upon map reload event.
784          *
785          * we can safely return here, because upon map reload, all
786          * PG will be enabled.
787          */
788         if (!pp->mpp->pg || !pp->pgindex)
789                 return;
790
791         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
792         
793         if (pgp->status == PGSTATE_DISABLED) {
794                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
795                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
796         }
797 }
798
799 static void
800 mpvec_garbage_collector (struct vectors * vecs)
801 {
802         struct multipath * mpp;
803         int i;
804
805         vector_foreach_slot (vecs->mpvec, mpp, i) {
806                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
807                         condlog(2, "%s: remove dead map", mpp->alias);
808                         remove_map(mpp, vecs, stop_waiter_thread, 1);
809                         i--;
810                 }
811         }
812 }
813
814 static void
815 defered_failback_tick (vector mpvec)
816 {
817         struct multipath * mpp;
818         int i;
819
820         vector_foreach_slot (mpvec, mpp, i) {
821                 /*
822                  * defered failback getting sooner
823                  */
824                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
825                         mpp->failback_tick--;
826
827                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
828                                 switch_pathgroup(mpp);
829                 }
830         }
831 }
832
833 static void
834 retry_count_tick(vector mpvec)
835 {
836         struct multipath *mpp;
837         int i;
838
839         vector_foreach_slot (mpvec, mpp, i) {
840                 if (mpp->retry_tick) {
841                         mpp->stat_total_queueing_time++;
842                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
843                         if(--mpp->retry_tick == 0) {
844                                 dm_queue_if_no_path(mpp->alias, 0);
845                                 condlog(2, "%s: Disable queueing", mpp->alias);
846                         }
847                 }
848         }
849 }
850
851 static void *
852 checkerloop (void *ap)
853 {
854         struct vectors *vecs;
855         struct path *pp;
856         int i, count = 0;
857         int newstate;
858
859         mlockall(MCL_CURRENT | MCL_FUTURE);
860         vecs = (struct vectors *)ap;
861         condlog(2, "path checkers start up");
862
863         /*
864          * init the path check interval
865          */
866         vector_foreach_slot (vecs->pathvec, pp, i) {
867                 pp->checkint = conf->checkint;
868         }
869
870         while (1) {
871                 pthread_cleanup_push(cleanup_lock, vecs->lock);
872                 lock(vecs->lock);
873                 condlog(4, "tick");
874
875                 vector_foreach_slot (vecs->pathvec, pp, i) {
876                         if (!pp->mpp)
877                                 continue;
878
879                         if (pp->tick && --pp->tick)
880                                 continue; /* don't check this path yet */
881
882                         /*
883                          * provision a next check soonest,
884                          * in case we exit abnormaly from here
885                          */
886                         pp->tick = conf->checkint;
887                         
888                         if (!checker_selected(&pp->checker)) {
889                                 pathinfo(pp, conf->hwtable, DI_SYSFS);
890                                 select_checker(pp);
891                         }
892
893                         if (!checker_selected(&pp->checker)) {
894                                 condlog(0, "%s: checker is not set", pp->dev);
895                                 continue;
896                         }
897                         newstate = checker_check(&pp->checker);
898                         
899                         if (newstate < 0) {
900                                 condlog(2, "%s: unusable path", pp->dev);
901                                 pathinfo(pp, conf->hwtable, 0);
902                                 continue;
903                         }
904
905                         if (newstate != pp->state) {
906                                 int oldstate = pp->state;
907                                 pp->state = newstate;
908                                 LOG_MSG(1, checker_message(&pp->checker));
909
910                                 /*
911                                  * upon state change, reset the checkint
912                                  * to the shortest delay
913                                  */
914                                 pp->checkint = conf->checkint;
915
916                                 if (newstate == PATH_DOWN ||
917                                     newstate == PATH_SHAKY ||
918                                     update_multipath_strings(pp->mpp,
919                                                              vecs->pathvec)) {
920                                         /*
921                                          * proactively fail path in the DM
922                                          */
923                                         if (oldstate == PATH_UP ||
924                                             oldstate == PATH_GHOST)
925                                                 fail_path(pp, 1);
926                                         else
927                                                 fail_path(pp, 0);
928
929                                         /*
930                                          * cancel scheduled failback
931                                          */
932                                         pp->mpp->failback_tick = 0;
933
934                                         pp->mpp->stat_path_failures++;
935                                         continue;
936                                 }
937
938                                 /*
939                                  * reinstate this path
940                                  */
941                                 if (oldstate != PATH_UP &&
942                                     oldstate != PATH_GHOST)
943                                         reinstate_path(pp, 1);
944                                 else
945                                         reinstate_path(pp, 0);
946
947                                 /*
948                                  * schedule [defered] failback
949                                  */
950                                 if (pp->mpp->pgfailback > 0)
951                                         pp->mpp->failback_tick =
952                                                 pp->mpp->pgfailback + 1;
953                                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
954                                     need_switch_pathgroup(pp->mpp, 1))
955                                         switch_pathgroup(pp->mpp);
956
957                                 /*
958                                  * if at least one path is up in a group, and
959                                  * the group is disabled, re-enable it
960                                  */
961                                 if (newstate == PATH_UP)
962                                         enable_group(pp);
963                         }
964                         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
965                                 LOG_MSG(4, checker_message(&pp->checker));
966                                 /*
967                                  * double the next check delay.
968                                  * max at conf->max_checkint
969                                  */
970                                 if (pp->checkint < (conf->max_checkint / 2))
971                                         pp->checkint = 2 * pp->checkint;
972                                 else
973                                         pp->checkint = conf->max_checkint;
974
975                                 pp->tick = pp->checkint;
976                                 condlog(4, "%s: delay next check %is",
977                                                 pp->dev_t, pp->tick);
978                         }
979                         else if (newstate == PATH_DOWN)
980                                 LOG_MSG(2, checker_message(&pp->checker));
981
982                         pp->state = newstate;
983
984                         /*
985                          * path prio refreshing
986                          */
987                         condlog(4, "path prio refresh");
988                         pathinfo(pp, conf->hwtable, DI_PRIO);
989
990                         if (need_switch_pathgroup(pp->mpp, 0)) {
991                                 if (pp->mpp->pgfailback > 0 &&
992                                     pp->mpp->failback_tick <= 0)
993                                         pp->mpp->failback_tick =
994                                                 pp->mpp->pgfailback + 1;
995                                 else if (pp->mpp->pgfailback ==
996                                                 -FAILBACK_IMMEDIATE)
997                                         switch_pathgroup(pp->mpp);
998                         }
999                 }
1000                 defered_failback_tick(vecs->mpvec);
1001                 retry_count_tick(vecs->mpvec);
1002
1003                 if (count)
1004                         count--;
1005                 else {
1006                         condlog(4, "map garbage collection");
1007                         mpvec_garbage_collector(vecs);
1008                         count = MAPGCINT;
1009                 }
1010                 
1011                 lock_cleanup_pop(vecs->lock);
1012                 sleep(1);
1013         }
1014         return NULL;
1015 }
1016
1017 int
1018 configure (struct vectors * vecs, int start_waiters)
1019 {
1020         struct multipath * mpp;
1021         struct path * pp;
1022         vector mpvec;
1023         int i;
1024
1025         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1026                 return 1;
1027         
1028         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1029                 return 1;
1030         
1031         if (!(mpvec = vector_alloc()))
1032                 return 1;
1033
1034         /*
1035          * probe for current path (from sysfs) and map (from dm) sets
1036          */
1037         path_discovery(vecs->pathvec, conf, DI_ALL);
1038
1039         vector_foreach_slot (vecs->pathvec, pp, i){
1040                 if (blacklist_path(conf, pp)){
1041                         vector_del_slot(vecs->pathvec, i);
1042                         free_path(pp);
1043                         i--;
1044                 }       
1045                 else
1046                         pp->checkint = conf->checkint;
1047         }
1048         if (map_discovery(vecs))
1049                 return 1;
1050
1051         /*
1052          * create new set of maps & push changed ones into dm
1053          */
1054         if (coalesce_paths(vecs, mpvec, NULL))
1055                 return 1;
1056
1057         /*
1058          * may need to remove some maps which are no longer relevant
1059          * e.g., due to blacklist changes in conf file
1060          */
1061         if (coalesce_maps(vecs, mpvec))
1062                 return 1;
1063
1064         dm_lib_release();
1065
1066         sync_maps_state(mpvec);
1067
1068         if (conf->verbosity > 2)
1069                 vector_foreach_slot(mpvec, mpp, i)
1070                         print_map(mpp);
1071
1072         /*
1073          * purge dm of old maps
1074          */
1075         remove_maps(vecs, NULL);
1076
1077         /*
1078          * save new set of maps formed by considering current path state
1079          */
1080         vector_free(vecs->mpvec);
1081         vecs->mpvec = mpvec;
1082
1083         /*
1084          * start dm event waiter threads for these new maps
1085          */
1086         vector_foreach_slot(vecs->mpvec, mpp, i) {
1087                 if (setup_multipath(vecs, mpp))
1088                         return 1;
1089                 if (start_waiters)
1090                         if (start_waiter_thread(mpp, vecs))
1091                                 return 1;
1092         }
1093         return 0;
1094 }
1095
1096 int
1097 reconfigure (struct vectors * vecs)
1098 {
1099         struct config * old = conf;
1100
1101         /*
1102          * free old map and path vectors ... they use old conf state
1103          */
1104         if (VECTOR_SIZE(vecs->mpvec))
1105                 remove_maps(vecs, stop_waiter_thread);
1106
1107         if (VECTOR_SIZE(vecs->pathvec))
1108                 free_pathvec(vecs->pathvec, FREE_PATHS);
1109
1110         vecs->pathvec = NULL;
1111         conf = NULL;
1112
1113         if (load_config(DEFAULT_CONFIGFILE))
1114                 return 1;
1115
1116         conf->verbosity = old->verbosity;
1117
1118         if (!conf->checkint) {
1119                 conf->checkint = DEFAULT_CHECKINT;
1120                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1121         }
1122         configure(vecs, 1);
1123         free_config(old);
1124         return 0;
1125 }
1126
1127 static struct vectors *
1128 init_vecs (void)
1129 {
1130         struct vectors * vecs;
1131
1132         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1133
1134         if (!vecs)
1135                 return NULL;
1136
1137         vecs->lock = 
1138                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1139
1140         if (!vecs->lock)
1141                 goto out;
1142
1143         pthread_mutex_init(vecs->lock, NULL);
1144
1145         return vecs;
1146
1147 out:
1148         FREE(vecs);
1149         condlog(0, "failed to init paths");
1150         return NULL;
1151 }
1152
1153 static void *
1154 signal_set(int signo, void (*func) (int))
1155 {
1156         int r;
1157         struct sigaction sig;
1158         struct sigaction osig;
1159
1160         sig.sa_handler = func;
1161         sigemptyset(&sig.sa_mask);
1162         sig.sa_flags = 0;
1163
1164         r = sigaction(signo, &sig, &osig);
1165
1166         if (r < 0)
1167                 return (SIG_ERR);
1168         else
1169                 return (osig.sa_handler);
1170 }
1171
1172 static void
1173 sighup (int sig)
1174 {
1175         condlog(2, "reconfigure (SIGHUP)");
1176
1177         lock(gvecs->lock);
1178         reconfigure(gvecs);
1179         unlock(gvecs->lock);
1180
1181 #ifdef _DEBUG_
1182         dbg_free_final(NULL);
1183 #endif
1184 }
1185
1186 static void
1187 sigend (int sig)
1188 {
1189         exit_daemon(0);
1190 }
1191
1192 static void
1193 sigusr1 (int sig)
1194 {
1195         condlog(3, "SIGUSR1 received");
1196 }
1197
1198 static void
1199 signal_init(void)
1200 {
1201         signal_set(SIGHUP, sighup);
1202         signal_set(SIGUSR1, sigusr1);
1203         signal_set(SIGINT, sigend);
1204         signal_set(SIGTERM, sigend);
1205         signal(SIGPIPE, SIG_IGN);
1206 }
1207
1208 static void
1209 setscheduler (void)
1210 {
1211         int res;
1212         static struct sched_param sched_param = {
1213                 sched_priority: 99
1214         };
1215
1216         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1217
1218         if (res == -1)
1219                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1220         return;
1221 }
1222
1223 static void
1224 set_oom_adj (int val)
1225 {
1226         FILE *fp;
1227
1228         fp = fopen("/proc/self/oom_adj", "w");
1229
1230         if (!fp)
1231                 return;
1232
1233         fprintf(fp, "%i", val);
1234         fclose(fp);
1235 }
1236         
1237 static int
1238 child (void * param)
1239 {
1240         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1241         pthread_attr_t attr;
1242         struct vectors * vecs;
1243
1244         mlockall(MCL_CURRENT | MCL_FUTURE);
1245
1246         if (logsink)
1247                 log_thread_start();
1248
1249         condlog(2, "--------start up--------");
1250         condlog(2, "read " DEFAULT_CONFIGFILE);
1251
1252         if (load_config(DEFAULT_CONFIGFILE))
1253                 exit(1);
1254
1255         setlogmask(LOG_UPTO(conf->verbosity + 3));
1256
1257         /*
1258          * fill the voids left in the config file
1259          */
1260         if (!conf->checkint) {
1261                 conf->checkint = DEFAULT_CHECKINT;
1262                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1263         }
1264
1265         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1266                 if (logsink)
1267                         log_thread_stop();
1268
1269                 exit(1);
1270         }
1271         signal_init();
1272         setscheduler();
1273         set_oom_adj(-16);
1274         vecs = gvecs = init_vecs();
1275
1276         if (!vecs)
1277                 exit(1);
1278
1279         if (sysfs_get_mnt_path(sysfs_path, FILE_NAME_SIZE)) {
1280                 condlog(0, "can not find sysfs mount point");
1281                 exit(1);
1282         }
1283
1284         /*
1285          * fetch and configure both paths and multipaths
1286          */
1287         if (configure(vecs, 1)) {
1288                 condlog(0, "failure during configuration");
1289                 exit(1);
1290         }
1291
1292         /*
1293          * start threads
1294          */
1295         pthread_attr_init(&attr);
1296         pthread_attr_setstacksize(&attr, 64 * 1024);
1297         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1298         
1299         pthread_create(&check_thr, &attr, checkerloop, vecs);
1300         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1301         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1302
1303         pthread_cond_wait(&exit_cond, &exit_mutex);
1304
1305         /*
1306          * exit path
1307          */
1308         lock(vecs->lock);
1309         remove_maps(vecs, stop_waiter_thread);
1310         free_pathvec(vecs->pathvec, FREE_PATHS);
1311
1312         pthread_cancel(check_thr);
1313         pthread_cancel(uevent_thr);
1314         pthread_cancel(uxlsnr_thr);
1315
1316         free_keys(keys);
1317         keys = NULL;
1318         free_handlers(handlers);
1319         handlers = NULL;
1320         free_polls();
1321
1322         unlock(vecs->lock);
1323         pthread_mutex_destroy(vecs->lock);
1324         FREE(vecs->lock);
1325         vecs->lock = NULL;
1326         FREE(vecs);
1327         vecs = NULL;
1328         free_config(conf);
1329         conf = NULL;
1330
1331         condlog(2, "--------shut down-------");
1332         
1333         if (logsink)
1334                 log_thread_stop();
1335
1336         dm_lib_release();
1337         dm_lib_exit();
1338
1339 #ifdef _DEBUG_
1340         dbg_free_final(NULL);
1341 #endif
1342
1343         exit(0);
1344 }
1345
1346 static int
1347 daemonize(void)
1348 {
1349         int pid;
1350         int in_fd, out_fd;
1351
1352         if( (pid = fork()) < 0){
1353                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1354                 return -1;
1355         }
1356         else if (pid != 0)
1357                 return pid;
1358
1359         setsid();
1360
1361         if ( (pid = fork()) < 0)
1362                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1363         else if (pid != 0)
1364                 _exit(0);
1365
1366         in_fd = open("/dev/null", O_RDONLY);
1367         if (in_fd < 0){
1368                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1369                         strerror(errno));
1370                 _exit(0);
1371         }
1372         out_fd = open("/dev/console", O_WRONLY);
1373         if (out_fd < 0){
1374                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1375                         strerror(errno));
1376                 _exit(0);
1377         }
1378
1379         close(STDIN_FILENO);
1380         dup(in_fd);
1381         close(STDOUT_FILENO);
1382         dup(out_fd);
1383         close(STDERR_FILENO);
1384         dup(out_fd);
1385
1386         close(in_fd);
1387         close(out_fd);
1388         chdir("/");
1389         umask(0);
1390         return 0;
1391 }
1392
1393 int
1394 main (int argc, char *argv[])
1395 {
1396         extern char *optarg;
1397         extern int optind;
1398         int arg;
1399         int err;
1400         
1401         logsink = 1;
1402
1403         if (getuid() != 0) {
1404                 fprintf(stderr, "need to be root\n");
1405                 exit(1);
1406         }
1407
1408         /* make sure we don't lock any path */
1409         chdir("/");
1410         umask(umask(077) | 022);
1411
1412         conf = alloc_config();
1413
1414         if (!conf)
1415                 exit(1);
1416
1417         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1418         switch(arg) {
1419                 case 'd':
1420                         logsink = 0;
1421                         //debug=1; /* ### comment me out ### */
1422                         break;
1423                 case 'v':
1424                         if (sizeof(optarg) > sizeof(char *) ||
1425                             !isdigit(optarg[0]))
1426                                 exit(1);
1427
1428                         conf->verbosity = atoi(optarg);
1429                         break;
1430                 case 'k':
1431                         uxclnt(optarg);
1432                         exit(0);
1433                 default:
1434                         ;
1435                 }
1436         }
1437
1438         if (!logsink)
1439                 err = 0;
1440         else
1441                 err = daemonize();
1442         
1443         if (err < 0)
1444                 /* error */
1445                 exit(1);
1446         else if (err > 0)
1447                 /* parent dies */
1448                 exit(0);
1449         else
1450                 /* child lives */
1451                 return (child(NULL));
1452 }
1453