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