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