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