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