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