Support resizing of multipath maps.
[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 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[11], b[11];
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         block_signal(SIGUSR1, NULL);
692         block_signal(SIGHUP, NULL);
693
694         if (uevent_listen(&uev_trigger, ap))
695                 fprintf(stderr, "error starting uevent listener");
696
697         return NULL;
698 }
699
700 static void *
701 uxlsnrloop (void * ap)
702 {
703         block_signal(SIGUSR1, NULL);
704         block_signal(SIGHUP, NULL);
705
706         if (cli_init())
707                 return NULL;
708
709         set_handler_callback(LIST+PATHS, cli_list_paths);
710         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
711         set_handler_callback(LIST+MAPS, cli_list_maps);
712         set_handler_callback(LIST+STATUS, cli_list_status);
713         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
714         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
715         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
716         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
717         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
718         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
719         set_handler_callback(LIST+CONFIG, cli_list_config);
720         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
721         set_handler_callback(LIST+DEVICES, cli_list_devices);
722         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
723         set_handler_callback(ADD+PATH, cli_add_path);
724         set_handler_callback(DEL+PATH, cli_del_path);
725         set_handler_callback(ADD+MAP, cli_add_map);
726         set_handler_callback(DEL+MAP, cli_del_map);
727         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
728         set_handler_callback(RECONFIGURE, cli_reconfigure);
729         set_handler_callback(SUSPEND+MAP, cli_suspend);
730         set_handler_callback(RESUME+MAP, cli_resume);
731         set_handler_callback(RESIZE+MAP, cli_resize);
732         set_handler_callback(REINSTATE+PATH, cli_reinstate);
733         set_handler_callback(FAIL+PATH, cli_fail);
734         set_handler_callback(QUIT, cli_quit);
735
736         uxsock_listen(&uxsock_trigger, ap);
737
738         return NULL;
739 }
740
741 static int
742 exit_daemon (int status)
743 {
744         if (status != 0)
745                 fprintf(stderr, "bad exit status. see daemon.log\n");
746
747         condlog(3, "unlink pidfile");
748         unlink(DEFAULT_PIDFILE);
749
750         pthread_mutex_lock(&exit_mutex);
751         pthread_cond_signal(&exit_cond);
752         pthread_mutex_unlock(&exit_mutex);
753
754         return status;
755 }
756
757 static void
758 fail_path (struct path * pp, int del_active)
759 {
760         if (!pp->mpp)
761                 return;
762
763         condlog(2, "checker failed path %s in map %s",
764                  pp->dev_t, pp->mpp->alias);
765
766         dm_fail_path(pp->mpp->alias, pp->dev_t);
767         if (del_active)
768                 update_queue_mode_del_path(pp->mpp);
769 }
770
771 /*
772  * caller must have locked the path list before calling that function
773  */
774 static void
775 reinstate_path (struct path * pp, int add_active)
776 {
777         if (!pp->mpp)
778                 return;
779
780         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
781                 condlog(0, "%s: reinstate failed", pp->dev_t);
782         else {
783                 condlog(2, "%s: reinstated", pp->dev_t);
784                 if (add_active)
785                         update_queue_mode_add_path(pp->mpp);
786         }
787 }
788
789 static void
790 enable_group(struct path * pp)
791 {
792         struct pathgroup * pgp;
793
794         /*
795          * if path is added through uev_add_path, pgindex can be unset.
796          * next update_strings() will set it, upon map reload event.
797          *
798          * we can safely return here, because upon map reload, all
799          * PG will be enabled.
800          */
801         if (!pp->mpp->pg || !pp->pgindex)
802                 return;
803
804         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
805
806         if (pgp->status == PGSTATE_DISABLED) {
807                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
808                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
809         }
810 }
811
812 static void
813 mpvec_garbage_collector (struct vectors * vecs)
814 {
815         struct multipath * mpp;
816         unsigned int i;
817
818         vector_foreach_slot (vecs->mpvec, mpp, i) {
819                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
820                         condlog(2, "%s: remove dead map", mpp->alias);
821                         remove_map_and_stop_waiter(mpp, vecs, 1);
822                         i--;
823                 }
824         }
825 }
826
827 static void
828 defered_failback_tick (vector mpvec)
829 {
830         struct multipath * mpp;
831         unsigned int i;
832
833         vector_foreach_slot (mpvec, mpp, i) {
834                 /*
835                  * defered failback getting sooner
836                  */
837                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
838                         mpp->failback_tick--;
839
840                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
841                                 switch_pathgroup(mpp);
842                 }
843         }
844 }
845
846 static void
847 retry_count_tick(vector mpvec)
848 {
849         struct multipath *mpp;
850         unsigned int i;
851
852         vector_foreach_slot (mpvec, mpp, i) {
853                 if (mpp->retry_tick) {
854                         mpp->stat_total_queueing_time++;
855                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
856                         if(--mpp->retry_tick == 0) {
857                                 dm_queue_if_no_path(mpp->alias, 0);
858                                 condlog(2, "%s: Disable queueing", mpp->alias);
859                         }
860                 }
861         }
862 }
863
864 void
865 check_path (struct vectors * vecs, struct path * pp)
866 {
867         int newstate;
868
869         if (!pp->mpp)
870                 return;
871
872         if (pp->tick && --pp->tick)
873                 return; /* don't check this path yet */
874
875         /*
876          * provision a next check soonest,
877          * in case we exit abnormaly from here
878          */
879         pp->tick = conf->checkint;
880
881         if (!checker_selected(&pp->checker)) {
882                 pathinfo(pp, conf->hwtable, DI_SYSFS);
883                 select_checker(pp);
884         }
885         if (!checker_selected(&pp->checker)) {
886                 condlog(0, "%s: checker is not set", pp->dev);
887                 return;
888         }
889         /*
890          * Set checker in async mode.
891          * Honored only by checker implementing the said mode.
892          */
893         checker_set_async(&pp->checker);
894
895         if (path_offline(pp))
896                 newstate = PATH_DOWN;
897         else
898                 newstate = checker_check(&pp->checker);
899
900         if (newstate < 0) {
901                 condlog(2, "%s: unusable path", pp->dev);
902                 pathinfo(pp, conf->hwtable, 0);
903                 return;
904         }
905         /*
906          * Async IO in flight. Keep the previous path state
907          * and reschedule as soon as possible
908          */
909         if (newstate == PATH_PENDING) {
910                 pp->tick = 1;
911                 return;
912         }
913         if (newstate != pp->state) {
914                 int oldstate = pp->state;
915                 pp->state = newstate;
916                 LOG_MSG(1, checker_message(&pp->checker));
917
918                 /*
919                  * upon state change, reset the checkint
920                  * to the shortest delay
921                  */
922                 pp->checkint = conf->checkint;
923
924                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY ||
925                     update_multipath_strings(pp->mpp, vecs->pathvec)) {
926                         /*
927                          * proactively fail path in the DM
928                          */
929                         if (oldstate == PATH_UP ||
930                             oldstate == PATH_GHOST)
931                                 fail_path(pp, 1);
932                         else
933                                 fail_path(pp, 0);
934
935                         /*
936                          * cancel scheduled failback
937                          */
938                         pp->mpp->failback_tick = 0;
939
940                         pp->mpp->stat_path_failures++;
941                         return;
942                 }
943
944                 /*
945                  * reinstate this path
946                  */
947                 if (oldstate != PATH_UP &&
948                     oldstate != PATH_GHOST)
949                         reinstate_path(pp, 1);
950                 else
951                         reinstate_path(pp, 0);
952
953                 /*
954                  * schedule [defered] failback
955                  */
956                 if (pp->mpp->pgfailback > 0)
957                         pp->mpp->failback_tick =
958                                 pp->mpp->pgfailback + 1;
959                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE &&
960                     need_switch_pathgroup(pp->mpp, 1))
961                         switch_pathgroup(pp->mpp);
962
963                 /*
964                  * if at least one path is up in a group, and
965                  * the group is disabled, re-enable it
966                  */
967                 if (newstate == PATH_UP)
968                         enable_group(pp);
969         }
970         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
971                 LOG_MSG(4, checker_message(&pp->checker));
972                 /*
973                  * double the next check delay.
974                  * max at conf->max_checkint
975                  */
976                 if (pp->checkint < (conf->max_checkint / 2))
977                         pp->checkint = 2 * pp->checkint;
978                 else
979                         pp->checkint = conf->max_checkint;
980
981                 pp->tick = pp->checkint;
982                 condlog(4, "%s: delay next check %is",
983                                 pp->dev_t, pp->tick);
984         }
985         else if (newstate == PATH_DOWN)
986                 LOG_MSG(2, checker_message(&pp->checker));
987
988         pp->state = newstate;
989
990         /*
991          * path prio refreshing
992          */
993         condlog(4, "path prio refresh");
994         pathinfo(pp, conf->hwtable, DI_PRIO);
995
996         /*
997          * pathgroup failback policy
998          */
999         if (need_switch_pathgroup(pp->mpp, 0)) {
1000                 if (pp->mpp->pgfailback > 0 &&
1001                     pp->mpp->failback_tick <= 0)
1002                         pp->mpp->failback_tick =
1003                                 pp->mpp->pgfailback + 1;
1004                 else if (pp->mpp->pgfailback ==
1005                                 -FAILBACK_IMMEDIATE)
1006                         switch_pathgroup(pp->mpp);
1007         }
1008 }
1009
1010 static void *
1011 checkerloop (void *ap)
1012 {
1013         struct vectors *vecs;
1014         struct path *pp;
1015         int count = 0;
1016         unsigned int i;
1017         sigset_t old;
1018
1019         mlockall(MCL_CURRENT | MCL_FUTURE);
1020         vecs = (struct vectors *)ap;
1021         condlog(2, "path checkers start up");
1022
1023         /*
1024          * init the path check interval
1025          */
1026         vector_foreach_slot (vecs->pathvec, pp, i) {
1027                 pp->checkint = conf->checkint;
1028         }
1029
1030         while (1) {
1031                 block_signal(SIGHUP, &old);
1032                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1033                 lock(vecs->lock);
1034                 condlog(4, "tick");
1035
1036                 if (vecs->pathvec) {
1037                         vector_foreach_slot (vecs->pathvec, pp, i) {
1038                                 check_path(vecs, pp);
1039                         }
1040                 }
1041                 if (vecs->mpvec) {
1042                         defered_failback_tick(vecs->mpvec);
1043                         retry_count_tick(vecs->mpvec);
1044                 }
1045                 if (count)
1046                         count--;
1047                 else {
1048                         condlog(4, "map garbage collection");
1049                         mpvec_garbage_collector(vecs);
1050                         count = MAPGCINT;
1051                 }
1052
1053                 lock_cleanup_pop(vecs->lock);
1054                 pthread_sigmask(SIG_SETMASK, &old, NULL);
1055                 sleep(1);
1056         }
1057         return NULL;
1058 }
1059
1060 int
1061 configure (struct vectors * vecs, int start_waiters)
1062 {
1063         struct multipath * mpp;
1064         struct path * pp;
1065         vector mpvec;
1066         int i;
1067
1068         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1069                 return 1;
1070
1071         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1072                 return 1;
1073
1074         if (!(mpvec = vector_alloc()))
1075                 return 1;
1076
1077         /*
1078          * probe for current path (from sysfs) and map (from dm) sets
1079          */
1080         path_discovery(vecs->pathvec, conf, DI_ALL);
1081
1082         vector_foreach_slot (vecs->pathvec, pp, i){
1083                 if (filter_path(conf, pp) > 0){
1084                         vector_del_slot(vecs->pathvec, i);
1085                         free_path(pp);
1086                         i--;
1087                 }
1088                 else
1089                         pp->checkint = conf->checkint;
1090         }
1091         if (map_discovery(vecs))
1092                 return 1;
1093
1094         /*
1095          * create new set of maps & push changed ones into dm
1096          */
1097         if (coalesce_paths(vecs, mpvec, NULL, 0))
1098                 return 1;
1099
1100         /*
1101          * may need to remove some maps which are no longer relevant
1102          * e.g., due to blacklist changes in conf file
1103          */
1104         if (coalesce_maps(vecs, mpvec))
1105                 return 1;
1106
1107         dm_lib_release();
1108
1109         sync_maps_state(mpvec);
1110
1111         /*
1112          * purge dm of old maps
1113          */
1114         remove_maps(vecs);
1115
1116         /*
1117          * save new set of maps formed by considering current path state
1118          */
1119         vector_free(vecs->mpvec);
1120         vecs->mpvec = mpvec;
1121
1122         /*
1123          * start dm event waiter threads for these new maps
1124          */
1125         vector_foreach_slot(vecs->mpvec, mpp, i) {
1126                 if (setup_multipath(vecs, mpp))
1127                         return 1;
1128                 if (start_waiters)
1129                         if (start_waiter_thread(mpp, vecs))
1130                                 return 1;
1131         }
1132         return 0;
1133 }
1134
1135 int
1136 reconfigure (struct vectors * vecs)
1137 {
1138         struct config * old = conf;
1139
1140         /*
1141          * free old map and path vectors ... they use old conf state
1142          */
1143         if (VECTOR_SIZE(vecs->mpvec))
1144                 remove_maps_and_stop_waiters(vecs);
1145
1146         if (VECTOR_SIZE(vecs->pathvec))
1147                 free_pathvec(vecs->pathvec, FREE_PATHS);
1148
1149         vecs->pathvec = NULL;
1150         conf = NULL;
1151
1152         if (load_config(DEFAULT_CONFIGFILE))
1153                 return 1;
1154
1155         conf->verbosity = old->verbosity;
1156
1157         if (!conf->checkint) {
1158                 conf->checkint = DEFAULT_CHECKINT;
1159                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1160         }
1161         configure(vecs, 1);
1162         free_config(old);
1163         return 0;
1164 }
1165
1166 static struct vectors *
1167 init_vecs (void)
1168 {
1169         struct vectors * vecs;
1170
1171         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1172
1173         if (!vecs)
1174                 return NULL;
1175
1176         vecs->lock.mutex =
1177                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1178
1179         if (!vecs->lock.mutex)
1180                 goto out;
1181
1182         pthread_mutex_init(vecs->lock.mutex, NULL);
1183         vecs->lock.depth = 0;
1184
1185         return vecs;
1186
1187 out:
1188         FREE(vecs);
1189         condlog(0, "failed to init paths");
1190         return NULL;
1191 }
1192
1193 static void *
1194 signal_set(int signo, void (*func) (int))
1195 {
1196         int r;
1197         struct sigaction sig;
1198         struct sigaction osig;
1199
1200         sig.sa_handler = func;
1201         sigemptyset(&sig.sa_mask);
1202         sig.sa_flags = 0;
1203
1204         r = sigaction(signo, &sig, &osig);
1205
1206         if (r < 0)
1207                 return (SIG_ERR);
1208         else
1209                 return (osig.sa_handler);
1210 }
1211
1212 static void
1213 sighup (int sig)
1214 {
1215         condlog(2, "reconfigure (SIGHUP)");
1216
1217         lock(gvecs->lock);
1218         reconfigure(gvecs);
1219         unlock(gvecs->lock);
1220
1221 #ifdef _DEBUG_
1222         dbg_free_final(NULL);
1223 #endif
1224 }
1225
1226 static void
1227 sigend (int sig)
1228 {
1229         exit_daemon(0);
1230 }
1231
1232 static void
1233 sigusr1 (int sig)
1234 {
1235         condlog(3, "SIGUSR1 received");
1236 }
1237
1238 static void
1239 signal_init(void)
1240 {
1241         signal_set(SIGHUP, sighup);
1242         signal_set(SIGUSR1, sigusr1);
1243         signal_set(SIGINT, sigend);
1244         signal_set(SIGTERM, sigend);
1245         signal(SIGPIPE, SIG_IGN);
1246 }
1247
1248 static void
1249 setscheduler (void)
1250 {
1251         int res;
1252         static struct sched_param sched_param = {
1253                 .sched_priority = 99
1254         };
1255
1256         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1257
1258         if (res == -1)
1259                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1260         return;
1261 }
1262
1263 static void
1264 set_oom_adj (int val)
1265 {
1266         FILE *fp;
1267
1268         fp = fopen("/proc/self/oom_adj", "w");
1269
1270         if (!fp)
1271                 return;
1272
1273         fprintf(fp, "%i", val);
1274         fclose(fp);
1275 }
1276
1277 static int
1278 child (void * param)
1279 {
1280         pthread_t check_thr, uevent_thr, uxlsnr_thr;
1281         pthread_attr_t attr;
1282         struct vectors * vecs;
1283
1284         mlockall(MCL_CURRENT | MCL_FUTURE);
1285
1286         if (logsink)
1287                 log_thread_start();
1288
1289         condlog(2, "--------start up--------");
1290         condlog(2, "read " DEFAULT_CONFIGFILE);
1291
1292         if (load_config(DEFAULT_CONFIGFILE))
1293                 exit(1);
1294
1295         if (init_checkers()) {
1296                 condlog(0, "failed to initialize checkers");
1297                 exit(1);
1298         }
1299         if (init_prio()) {
1300                 condlog(0, "failed to initialize prioritizers");
1301                 exit(1);
1302         }
1303
1304         setlogmask(LOG_UPTO(conf->verbosity + 3));
1305
1306         /*
1307          * fill the voids left in the config file
1308          */
1309         if (!conf->checkint) {
1310                 conf->checkint = DEFAULT_CHECKINT;
1311                 conf->max_checkint = MAX_CHECKINT(conf->checkint);
1312         }
1313
1314         if (conf->max_fds) {
1315                 struct rlimit fd_limit;
1316                 if (conf->max_fds > 0) {
1317                         fd_limit.rlim_cur = conf->max_fds;
1318                         fd_limit.rlim_max = conf->max_fds;
1319                 }
1320                 else {
1321                         fd_limit.rlim_cur = RLIM_INFINITY;
1322                         fd_limit.rlim_max = RLIM_INFINITY;
1323                 }
1324                 if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0)
1325                         condlog(0, "can't set open fds limit to %d : %s\n",
1326                                 conf->max_fds, strerror(errno));
1327         }
1328
1329         if (pidfile_create(DEFAULT_PIDFILE, getpid())) {
1330                 if (logsink)
1331                         log_thread_stop();
1332
1333                 exit(1);
1334         }
1335         signal_init();
1336         setscheduler();
1337         set_oom_adj(-16);
1338         vecs = gvecs = init_vecs();
1339
1340         if (!vecs)
1341                 exit(1);
1342
1343         if (sysfs_init(conf->sysfs_dir, FILE_NAME_SIZE)) {
1344                 condlog(0, "can not find sysfs mount point");
1345                 exit(1);
1346         }
1347         conf->daemon = 1;
1348         /*
1349          * fetch and configure both paths and multipaths
1350          */
1351         if (configure(vecs, 1)) {
1352                 condlog(0, "failure during configuration");
1353                 exit(1);
1354         }
1355         /*
1356          * start threads
1357          */
1358         pthread_attr_init(&attr);
1359         pthread_attr_setstacksize(&attr, 64 * 1024);
1360         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1361
1362         pthread_create(&check_thr, &attr, checkerloop, vecs);
1363         pthread_create(&uevent_thr, &attr, ueventloop, vecs);
1364         pthread_create(&uxlsnr_thr, &attr, uxlsnrloop, vecs);
1365
1366         pthread_cond_wait(&exit_cond, &exit_mutex);
1367
1368         /*
1369          * exit path
1370          */
1371         block_signal(SIGHUP, NULL);
1372         lock(vecs->lock);
1373         remove_maps_and_stop_waiters(vecs);
1374         free_pathvec(vecs->pathvec, FREE_PATHS);
1375
1376         pthread_cancel(check_thr);
1377         pthread_cancel(uevent_thr);
1378         pthread_cancel(uxlsnr_thr);
1379
1380         sysfs_cleanup();
1381
1382         free_keys(keys);
1383         keys = NULL;
1384         free_handlers(handlers);
1385         handlers = NULL;
1386         free_polls();
1387
1388         unlock(vecs->lock);
1389         /* Now all the waitevent threads will start rushing in. */
1390         while (vecs->lock.depth > 0) {
1391                 sleep (1); /* This is weak. */
1392                 condlog(3,"Have %d wait event checkers threads to de-alloc, waiting..\n", vecs->lock.depth);
1393         }
1394         pthread_mutex_destroy(vecs->lock.mutex);
1395         FREE(vecs->lock.mutex);
1396         vecs->lock.depth = 0;
1397         vecs->lock.mutex = NULL;
1398         FREE(vecs);
1399         vecs = NULL;
1400
1401         condlog(2, "--------shut down-------");
1402
1403         if (logsink)
1404                 log_thread_stop();
1405
1406         dm_lib_release();
1407         dm_lib_exit();
1408
1409         cleanup_prio();
1410         cleanup_checkers();
1411         /*
1412          * Freeing config must be done after condlog() and dm_lib_exit(),
1413          * because logging functions like dlog() and dm_write_log()
1414          * reference the config.
1415          */
1416         free_config(conf);
1417         conf = NULL;
1418
1419 #ifdef _DEBUG_
1420         dbg_free_final(NULL);
1421 #endif
1422
1423         exit(0);
1424 }
1425
1426 static int
1427 daemonize(void)
1428 {
1429         int pid;
1430         int in_fd, out_fd;
1431
1432         if( (pid = fork()) < 0){
1433                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1434                 return -1;
1435         }
1436         else if (pid != 0)
1437                 return pid;
1438
1439         setsid();
1440
1441         if ( (pid = fork()) < 0)
1442                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1443         else if (pid != 0)
1444                 _exit(0);
1445
1446         in_fd = open("/dev/null", O_RDONLY);
1447         if (in_fd < 0){
1448                 fprintf(stderr, "cannot open /dev/null for input : %s\n",
1449                         strerror(errno));
1450                 _exit(0);
1451         }
1452         out_fd = open("/dev/console", O_WRONLY);
1453         if (out_fd < 0){
1454                 fprintf(stderr, "cannot open /dev/console for output : %s\n",
1455                         strerror(errno));
1456                 _exit(0);
1457         }
1458
1459         close(STDIN_FILENO);
1460         dup(in_fd);
1461         close(STDOUT_FILENO);
1462         dup(out_fd);
1463         close(STDERR_FILENO);
1464         dup(out_fd);
1465
1466         close(in_fd);
1467         close(out_fd);
1468         if (chdir("/") < 0)
1469                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1470
1471         return 0;
1472 }
1473
1474 int
1475 main (int argc, char *argv[])
1476 {
1477         extern char *optarg;
1478         extern int optind;
1479         int arg;
1480         int err;
1481
1482         logsink = 1;
1483         dm_init();
1484
1485         if (getuid() != 0) {
1486                 fprintf(stderr, "need to be root\n");
1487                 exit(1);
1488         }
1489
1490         /* make sure we don't lock any path */
1491         chdir("/");
1492         umask(umask(077) | 022);
1493
1494         conf = alloc_config();
1495
1496         if (!conf)
1497                 exit(1);
1498
1499         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1500         switch(arg) {
1501                 case 'd':
1502                         logsink = 0;
1503                         //debug=1; /* ### comment me out ### */
1504                         break;
1505                 case 'v':
1506                         if (sizeof(optarg) > sizeof(char *) ||
1507                             !isdigit(optarg[0]))
1508                                 exit(1);
1509
1510                         conf->verbosity = atoi(optarg);
1511                         break;
1512                 case 'k':
1513                         uxclnt(optarg);
1514                         exit(0);
1515                 default:
1516                         ;
1517                 }
1518         }
1519         if (optind < argc) {
1520                 char cmd[CMDSIZE];
1521                 char * s = cmd;
1522                 char * c = s;
1523
1524                 while (optind < argc) {
1525                         if (strchr(argv[optind], ' '))
1526                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1527                         else
1528                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1529                         optind++;
1530                 }
1531                 c += snprintf(c, s + CMDSIZE - c, "\n");
1532                 uxclnt(s);
1533                 exit(0);
1534         }
1535
1536         if (!logsink)
1537                 err = 0;
1538         else
1539                 err = daemonize();
1540
1541         if (err < 0)
1542                 /* error */
1543                 exit(1);
1544         else if (err > 0)
1545                 /* parent dies */
1546                 exit(0);
1547         else
1548                 /* child lives */
1549                 return (child(NULL));
1550 }
1551