69cef3c23752773efd8f61d44af9f74848f96195
[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 #include <limits.h>
18 #include <linux/oom.h>
19 #include <libudev.h>
20 #include <mpath_persist.h>
21
22 /*
23  * libcheckers
24  */
25 #include <checkers.h>
26
27 /*
28  * libmultipath
29  */
30 #include <parser.h>
31 #include <vector.h>
32 #include <memory.h>
33 #include <config.h>
34 #include <util.h>
35 #include <hwtable.h>
36 #include <defaults.h>
37 #include <structs.h>
38 #include <callout.h>
39 #include <blacklist.h>
40 #include <structs_vec.h>
41 #include <dmparser.h>
42 #include <devmapper.h>
43 #include <sysfs.h>
44 #include <dict.h>
45 #include <discovery.h>
46 #include <debug.h>
47 #include <propsel.h>
48 #include <uevent.h>
49 #include <switchgroup.h>
50 #include <print.h>
51 #include <configure.h>
52 #include <prio.h>
53 #include <pgpolicies.h>
54 #include <uevent.h>
55
56 #include "main.h"
57 #include "pidfile.h"
58 #include "uxlsnr.h"
59 #include "uxclnt.h"
60 #include "cli.h"
61 #include "cli_handlers.h"
62 #include "lock.h"
63 #include "waiter.h"
64
65 #define FILE_NAME_SIZE 256
66 #define CMDSIZE 160
67
68 #define LOG_MSG(a, b) \
69 do { \
70         if (pp->offline) \
71                 condlog(a, "%s: %s - path offline", pp->mpp->alias, pp->dev); \
72         else if (strlen(b)) \
73                 condlog(a, "%s: %s - %s", pp->mpp->alias, pp->dev, b); \
74 } while(0)
75
76 struct mpath_event_param
77 {
78         char * devname;
79         struct multipath *mpp;
80 };
81
82 unsigned int mpath_mx_alloc_len;
83
84 pthread_cond_t exit_cond = PTHREAD_COND_INITIALIZER;
85 pthread_mutex_t exit_mutex = PTHREAD_MUTEX_INITIALIZER;
86
87 int logsink;
88 enum daemon_status running_state;
89 pid_t daemon_pid;
90
91 /*
92  * global copy of vecs for use in sig handlers
93  */
94 struct vectors * gvecs;
95
96 static int
97 need_switch_pathgroup (struct multipath * mpp, int refresh)
98 {
99         struct pathgroup * pgp;
100         struct path * pp;
101         unsigned int i, j;
102
103         if (!mpp || mpp->pgfailback == -FAILBACK_MANUAL)
104                 return 0;
105
106         /*
107          * Refresh path priority values
108          */
109         if (refresh)
110                 vector_foreach_slot (mpp->pg, pgp, i)
111                         vector_foreach_slot (pgp->paths, pp, j)
112                                 pathinfo(pp, conf->hwtable, DI_PRIO);
113
114         mpp->bestpg = select_path_group(mpp);
115
116         if (mpp->bestpg != mpp->nextpg)
117                 return 1;
118
119         return 0;
120 }
121
122 static void
123 switch_pathgroup (struct multipath * mpp)
124 {
125         mpp->stat_switchgroup++;
126         dm_switchgroup(mpp->alias, mpp->bestpg);
127         condlog(2, "%s: switch to path group #%i",
128                  mpp->alias, mpp->bestpg);
129 }
130
131 static int
132 coalesce_maps(struct vectors *vecs, vector nmpv)
133 {
134         struct multipath * ompp;
135         vector ompv = vecs->mpvec;
136         unsigned int i;
137         int j;
138
139         vector_foreach_slot (ompv, ompp, i) {
140                 if (!find_mp_by_wwid(nmpv, ompp->wwid)) {
141                         /*
142                          * remove all current maps not allowed by the
143                          * current configuration
144                          */
145                         if (dm_flush_map(ompp->alias)) {
146                                 condlog(0, "%s: unable to flush devmap",
147                                         ompp->alias);
148                                 /*
149                                  * may be just because the device is open
150                                  */
151                                 if (!vector_alloc_slot(nmpv))
152                                         return 1;
153
154                                 vector_set_slot(nmpv, ompp);
155                                 setup_multipath(vecs, ompp);
156
157                                 if ((j = find_slot(ompv, (void *)ompp)) != -1)
158                                         vector_del_slot(ompv, j);
159
160                                 continue;
161                         }
162                         else {
163                                 dm_lib_release();
164                                 condlog(2, "%s devmap removed", ompp->alias);
165                         }
166                 } else if (conf->reassign_maps) {
167                         condlog(3, "%s: Reassign existing device-mapper"
168                                 " devices", ompp->alias);
169                         dm_reassign(ompp->alias);
170                 }
171         }
172         return 0;
173 }
174
175 void
176 sync_map_state(struct multipath *mpp)
177 {
178         struct pathgroup *pgp;
179         struct path *pp;
180         unsigned int i, j;
181
182         if (!mpp->pg)
183                 return;
184
185         vector_foreach_slot (mpp->pg, pgp, i){
186                 vector_foreach_slot (pgp->paths, pp, j){
187                         if (pp->state == PATH_UNCHECKED || 
188                             pp->state == PATH_WILD)
189                                 continue;
190                         if ((pp->dmstate == PSTATE_FAILED ||
191                              pp->dmstate == PSTATE_UNDEF) &&
192                             (pp->state == PATH_UP || pp->state == PATH_GHOST))
193                                 dm_reinstate_path(mpp->alias, pp->dev_t);
194                         else if ((pp->dmstate == PSTATE_ACTIVE ||
195                                   pp->dmstate == PSTATE_UNDEF) &&
196                                  (pp->state == PATH_DOWN ||
197                                   pp->state == PATH_SHAKY))
198                                 dm_fail_path(mpp->alias, pp->dev_t);
199                 }
200         }
201 }
202
203 static void
204 sync_maps_state(vector mpvec)
205 {
206         unsigned int i;
207         struct multipath *mpp;
208
209         vector_foreach_slot (mpvec, mpp, i)
210                 sync_map_state(mpp);
211 }
212
213 static int
214 flush_map(struct multipath * mpp, struct vectors * vecs)
215 {
216         /*
217          * clear references to this map before flushing so we can ignore
218          * the spurious uevent we may generate with the dm_flush_map call below
219          */
220         if (dm_flush_map(mpp->alias)) {
221                 /*
222                  * May not really be an error -- if the map was already flushed
223                  * from the device mapper by dmsetup(8) for instance.
224                  */
225                 condlog(0, "%s: can't flush", mpp->alias);
226                 return 1;
227         }
228         else {
229                 dm_lib_release();
230                 condlog(2, "%s: devmap removed", mpp->alias);
231         }
232
233         orphan_paths(vecs->pathvec, mpp);
234         remove_map_and_stop_waiter(mpp, vecs, 1);
235
236         return 0;
237 }
238
239 static int
240 uev_add_map (struct uevent * uev, struct vectors * vecs)
241 {
242         char *alias;
243         int major = -1, minor = -1, rc;
244
245         condlog(3, "%s: add map (uevent)", uev->kernel);
246         alias = uevent_get_dm_name(uev);
247         if (!alias) {
248                 condlog(3, "%s: No DM_NAME in uevent", uev->kernel);
249                 major = uevent_get_major(uev);
250                 minor = uevent_get_minor(uev);
251                 alias = dm_mapname(major, minor);
252                 if (!alias) {
253                         condlog(2, "%s: mapname not found for %d:%d",
254                                 uev->kernel, major, minor);
255                         return 1;
256                 }
257         }
258         rc = ev_add_map(uev->kernel, alias, vecs);
259         FREE(alias);
260         return rc;
261 }
262
263 int
264 ev_add_map (char * dev, char * alias, struct vectors * vecs)
265 {
266         char * refwwid;
267         struct multipath * mpp;
268         int map_present;
269         int r = 1;
270
271         map_present = dm_map_present(alias);
272
273         if (map_present && dm_type(alias, TGT_MPATH) <= 0) {
274                 condlog(4, "%s: not a multipath map", alias);
275                 return 0;
276         }
277
278         mpp = find_mp_by_alias(vecs->mpvec, alias);
279
280         if (mpp) {
281                 /*
282                  * Not really an error -- we generate our own uevent
283                  * if we create a multipath mapped device as a result
284                  * of uev_add_path
285                  */
286                 if (conf->reassign_maps) {
287                         condlog(3, "%s: Reassign existing device-mapper devices",
288                                 alias);
289                         dm_reassign(alias);
290                 }
291                 return 0;
292         }
293         condlog(2, "%s: adding map", alias);
294
295         /*
296          * now we can register the map
297          */
298         if (map_present && (mpp = add_map_without_path(vecs, alias))) {
299                 sync_map_state(mpp);
300                 condlog(2, "%s: devmap %s registered", alias, dev);
301                 return 0;
302         }
303         refwwid = get_refwwid(dev, DEV_DEVMAP, vecs->pathvec);
304
305         if (refwwid) {
306                 r = coalesce_paths(vecs, NULL, refwwid, 0);
307                 dm_lib_release();
308         }
309
310         if (!r)
311                 condlog(2, "%s: devmap %s added", alias, dev);
312         else
313                 condlog(0, "%s: uev_add_map %s failed", alias, dev);
314
315         FREE(refwwid);
316         return r;
317 }
318
319 static int
320 uev_remove_map (struct uevent * uev, struct vectors * vecs)
321 {
322         char *alias;
323         int minor;
324         struct multipath *mpp;
325
326         condlog(2, "%s: remove map (uevent)", uev->kernel);
327         alias = uevent_get_dm_name(uev);
328         if (!alias) {
329                 condlog(3, "%s: No DM_NAME in uevent, ignoring", uev->kernel);
330                 return 0;
331         }
332         minor = uevent_get_minor(uev);
333         mpp = find_mp_by_minor(vecs->mpvec, minor);
334
335         if (!mpp) {
336                 condlog(2, "%s: devmap not registered, can't remove",
337                         uev->kernel);
338                 goto out;
339         }
340         if (strcmp(mpp->alias, alias)) {
341                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
342                         mpp->alias, mpp->dmi->minor, minor);
343                 goto out;
344         }
345
346         orphan_paths(vecs->pathvec, mpp);
347         remove_map_and_stop_waiter(mpp, vecs, 1);
348 out:
349         FREE(alias);
350         return 0;
351 }
352
353 int
354 ev_remove_map (char * devname, char * alias, int minor, struct vectors * vecs)
355 {
356         struct multipath * mpp;
357
358         mpp = find_mp_by_minor(vecs->mpvec, minor);
359
360         if (!mpp) {
361                 condlog(2, "%s: devmap not registered, can't remove",
362                         devname);
363                 return 0;
364         }
365         if (strcmp(mpp->alias, alias)) {
366                 condlog(2, "%s: minor number mismatch (map %d, event %d)",
367                         mpp->alias, mpp->dmi->minor, minor);
368                 return 0;
369         }
370         return flush_map(mpp, vecs);
371 }
372
373 static int
374 uev_add_path (struct uevent *uev, struct vectors * vecs)
375 {
376         struct path *pp;
377
378         condlog(2, "%s: add path (uevent)", uev->kernel);
379         if (strstr(uev->kernel, "..") != NULL) {
380                 /*
381                  * Don't allow relative device names in the pathvec
382                  */
383                 condlog(0, "%s: path name is invalid", uev->kernel);
384                 return 1;
385         }
386
387         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
388         if (pp) {
389                 condlog(0, "%s: spurious uevent, path already in pathvec",
390                         uev->kernel);
391                 if (pp->mpp)
392                         return 0;
393         } else {
394                 struct udev_device *udevice;
395
396                 /*
397                  * get path vital state
398                  */
399                 udevice = udev_device_ref(uev->udev);
400                 if (!(pp = store_pathinfo(vecs->pathvec, conf->hwtable,
401                                           udevice, DI_ALL))) {
402                         condlog(0, "%s: failed to store path info",
403                                 uev->kernel);
404                         udev_device_unref(udevice);
405                         return 1;
406                 }
407                 pp->checkint = conf->checkint;
408         }
409
410         return (ev_add_path(pp, vecs) != 1)? 0 : 1;
411 }
412
413 /*
414  * returns:
415  * 0: added
416  * 1: error
417  * 2: blacklisted
418  */
419 int
420 ev_add_path (struct path * pp, struct vectors * vecs)
421 {
422         struct multipath * mpp;
423         char empty_buff[WWID_SIZE] = {0};
424         char params[PARAMS_SIZE] = {0};
425         int retries = 3;
426         int start_waiter = 0;
427
428         /*
429          * need path UID to go any further
430          */
431         if (memcmp(empty_buff, pp->wwid, WWID_SIZE) == 0) {
432                 condlog(0, "%s: failed to get path uid", pp->dev);
433                 goto fail; /* leave path added to pathvec */
434         }
435         if (filter_path(conf, pp) > 0){
436                 int i = find_slot(vecs->pathvec, (void *)pp);
437                 if (i != -1)
438                         vector_del_slot(vecs->pathvec, i);
439                 free_path(pp);
440                 return 2;
441         }
442         mpp = pp->mpp = find_mp_by_wwid(vecs->mpvec, pp->wwid);
443 rescan:
444         if (mpp) {
445                 if ((!pp->size) || (mpp->size != pp->size)) {
446                         if (!pp->size)
447                                 condlog(0, "%s: failed to add new path %s, "
448                                         "device size is 0",
449                                         mpp->alias, pp->dev);
450                         else
451                                 condlog(0, "%s: failed to add new path %s, "
452                                         "device size mismatch",
453                                         mpp->alias, pp->dev);
454                         int i = find_slot(vecs->pathvec, (void *)pp);
455                         if (i != -1)
456                                 vector_del_slot(vecs->pathvec, i);
457                         free_path(pp);
458                         return 1;
459                 }
460
461                 condlog(4,"%s: adopting all paths for path %s",
462                         mpp->alias, pp->dev);
463                 if (adopt_paths(vecs->pathvec, mpp, 1))
464                         goto fail; /* leave path added to pathvec */
465
466                 verify_paths(mpp, vecs, NULL);
467                 mpp->flush_on_last_del = FLUSH_UNDEF;
468                 mpp->action = ACT_RELOAD;
469         }
470         else {
471                 if (!pp->size) {
472                         condlog(0, "%s: failed to create new map,"
473                                 " device size is 0 ", pp->dev);
474                         int i = find_slot(vecs->pathvec, (void *)pp);
475                         if (i != -1)
476                                 vector_del_slot(vecs->pathvec, i);
477                         free_path(pp);
478                         return 1;
479                 }
480
481                 condlog(4,"%s: creating new map", pp->dev);
482                 if ((mpp = add_map_with_path(vecs, pp, 1))) {
483                         mpp->action = ACT_CREATE;
484                         /*
485                          * We don't depend on ACT_CREATE, as domap will
486                          * set it to ACT_NOTHING when complete.
487                          */
488                         start_waiter = 1;
489                 }
490                 else
491                         goto fail; /* leave path added to pathvec */
492         }
493
494         /* persistent reseravtion check*/
495         mpath_pr_event_handle(pp);      
496
497         /*
498          * push the map to the device-mapper
499          */
500         if (setup_map(mpp, params, PARAMS_SIZE)) {
501                 condlog(0, "%s: failed to setup map for addition of new "
502                         "path %s", mpp->alias, pp->dev);
503                 goto fail_map;
504         }
505         /*
506          * reload the map for the multipath mapped device
507          */
508         if (domap(mpp, params) <= 0) {
509                 condlog(0, "%s: failed in domap for addition of new "
510                         "path %s", mpp->alias, pp->dev);
511                 /*
512                  * deal with asynchronous uevents :((
513                  */
514                 if (mpp->action == ACT_RELOAD && retries-- > 0) {
515                         condlog(0, "%s: uev_add_path sleep", mpp->alias);
516                         sleep(1);
517                         update_mpp_paths(mpp, vecs->pathvec);
518                         goto rescan;
519                 }
520                 else if (mpp->action == ACT_RELOAD)
521                         condlog(0, "%s: giving up reload", mpp->alias);
522                 else
523                         goto fail_map;
524         }
525         dm_lib_release();
526
527         /*
528          * update our state from kernel regardless of create or reload
529          */
530         if (setup_multipath(vecs, mpp))
531                 goto fail; /* if setup_multipath fails, it removes the map */
532
533         sync_map_state(mpp);
534
535         if ((mpp->action == ACT_CREATE ||
536              (mpp->action == ACT_NOTHING && start_waiter && !mpp->waiter)) &&
537             start_waiter_thread(mpp, vecs))
538                         goto fail_map;
539
540         if (retries >= 0) {
541                 condlog(2, "%s path added to devmap %s", pp->dev, mpp->alias);
542                 return 0;
543         }
544         else
545                 return 1;
546
547 fail_map:
548         remove_map(mpp, vecs, 1);
549 fail:
550         orphan_path(pp);
551         return 1;
552 }
553
554 static int
555 uev_remove_path (struct uevent *uev, struct vectors * vecs)
556 {
557         struct path *pp;
558
559         condlog(2, "%s: remove path (uevent)", uev->kernel);
560         pp = find_path_by_dev(vecs->pathvec, uev->kernel);
561
562         if (!pp) {
563                 /* Not an error; path might have been purged earlier */
564                 condlog(0, "%s: path already removed", uev->kernel);
565                 return 0;
566         }
567
568         return ev_remove_path(pp, vecs);
569 }
570
571 int
572 ev_remove_path (struct path *pp, struct vectors * vecs)
573 {
574         struct multipath * mpp;
575         int i, retval = 0;
576         char params[PARAMS_SIZE] = {0};
577
578         /*
579          * avoid referring to the map of an orphaned path
580          */
581         if ((mpp = pp->mpp)) {
582                 /*
583                  * transform the mp->pg vector of vectors of paths
584                  * into a mp->params string to feed the device-mapper
585                  */
586                 if (update_mpp_paths(mpp, vecs->pathvec)) {
587                         condlog(0, "%s: failed to update paths",
588                                 mpp->alias);
589                         goto fail;
590                 }
591                 if ((i = find_slot(mpp->paths, (void *)pp)) != -1)
592                         vector_del_slot(mpp->paths, i);
593
594                 /*
595                  * remove the map IFF removing the last path
596                  */
597                 if (VECTOR_SIZE(mpp->paths) == 0) {
598                         char alias[WWID_SIZE];
599
600                         /*
601                          * flush_map will fail if the device is open
602                          */
603                         strncpy(alias, mpp->alias, WWID_SIZE);
604                         if (mpp->flush_on_last_del == FLUSH_ENABLED) {
605                                 condlog(2, "%s Last path deleted, disabling queueing", mpp->alias);
606                                 mpp->retry_tick = 0;
607                                 mpp->no_path_retry = NO_PATH_RETRY_FAIL;
608                                 mpp->flush_on_last_del = FLUSH_IN_PROGRESS;
609                                 dm_queue_if_no_path(mpp->alias, 0);
610                         }
611                         if (!flush_map(mpp, vecs)) {
612                                 condlog(2, "%s: removed map after"
613                                         " removing all paths",
614                                         alias);
615                                 retval = 0;
616                                 goto out;
617                         }
618                         /*
619                          * Not an error, continue
620                          */
621                 }
622
623                 if (setup_map(mpp, params, PARAMS_SIZE)) {
624                         condlog(0, "%s: failed to setup map for"
625                                 " removal of path %s", mpp->alias, pp->dev);
626                         goto fail;
627                 }
628                 /*
629                  * reload the map
630                  */
631                 mpp->action = ACT_RELOAD;
632                 if (domap(mpp, params) <= 0) {
633                         condlog(0, "%s: failed in domap for "
634                                 "removal of path %s",
635                                 mpp->alias, pp->dev);
636                         retval = 1;
637                 } else {
638                         /*
639                          * update our state from kernel
640                          */
641                         if (setup_multipath(vecs, mpp)) {
642                                 goto fail;
643                         }
644                         sync_map_state(mpp);
645
646                         condlog(2, "%s: path removed from map %s",
647                                 pp->dev, mpp->alias);
648                 }
649         }
650
651 out:
652         if ((i = find_slot(vecs->pathvec, (void *)pp)) != -1)
653                 vector_del_slot(vecs->pathvec, i);
654
655         free_path(pp);
656
657         return retval;
658
659 fail:
660         remove_map_and_stop_waiter(mpp, vecs, 1);
661         return 1;
662 }
663
664 static int
665 uev_update_path (struct uevent *uev, struct vectors * vecs)
666 {
667         int retval, ro;
668
669         ro = uevent_get_disk_ro(uev);
670
671         if (ro >= 0) {
672                 struct path * pp;
673
674                 condlog(2, "%s: update path write_protect to '%d' (uevent)",
675                         uev->kernel, ro);
676                 pp = find_path_by_dev(vecs->pathvec, uev->kernel);
677                 if (!pp) {
678                         condlog(0, "%s: spurious uevent, path not found",
679                                 uev->kernel);
680                         return 1;
681                 }
682                 if (pp->mpp)
683                         retval = reload_map(vecs, pp->mpp);
684
685                 condlog(2, "%s: map %s reloaded (retval %d)",
686                         uev->kernel, pp->mpp->alias, retval);
687
688         }
689
690         return retval;
691 }
692
693 static int
694 map_discovery (struct vectors * vecs)
695 {
696         struct multipath * mpp;
697         unsigned int i;
698
699         if (dm_get_maps(vecs->mpvec))
700                 return 1;
701
702         vector_foreach_slot (vecs->mpvec, mpp, i)
703                 if (setup_multipath(vecs, mpp))
704                         return 1;
705
706         return 0;
707 }
708
709 int
710 uxsock_trigger (char * str, char ** reply, int * len, void * trigger_data)
711 {
712         struct vectors * vecs;
713         int r;
714
715         *reply = NULL;
716         *len = 0;
717         vecs = (struct vectors *)trigger_data;
718
719         pthread_cleanup_push(cleanup_lock, &vecs->lock);
720         lock(vecs->lock);
721         pthread_testcancel();
722
723         r = parse_cmd(str, reply, len, vecs);
724
725         if (r > 0) {
726                 *reply = STRDUP("fail\n");
727                 *len = strlen(*reply) + 1;
728                 r = 1;
729         }
730         else if (!r && *len == 0) {
731                 *reply = STRDUP("ok\n");
732                 *len = strlen(*reply) + 1;
733                 r = 0;
734         }
735         /* else if (r < 0) leave *reply alone */
736
737         lock_cleanup_pop(vecs->lock);
738         return r;
739 }
740
741 static int
742 uev_discard(char * devpath)
743 {
744         char *tmp;
745         char a[11], b[11];
746
747         /*
748          * keep only block devices, discard partitions
749          */
750         tmp = strstr(devpath, "/block/");
751         if (tmp == NULL){
752                 condlog(4, "no /block/ in '%s'", devpath);
753                 return 1;
754         }
755         if (sscanf(tmp, "/block/%10s", a) != 1 ||
756             sscanf(tmp, "/block/%10[^/]/%10s", a, b) == 2) {
757                 condlog(4, "discard event on %s", devpath);
758                 return 1;
759         }
760         return 0;
761 }
762
763 int
764 uev_trigger (struct uevent * uev, void * trigger_data)
765 {
766         int r = 0;
767         struct vectors * vecs;
768
769         vecs = (struct vectors *)trigger_data;
770
771         if (uev_discard(uev->devpath))
772                 return 0;
773
774         pthread_cleanup_push(cleanup_lock, &vecs->lock);
775         lock(vecs->lock);
776         pthread_testcancel();
777
778         /*
779          * device map event
780          * Add events are ignored here as the tables
781          * are not fully initialised then.
782          */
783         if (!strncmp(uev->kernel, "dm-", 3)) {
784                 if (!strncmp(uev->action, "change", 6)) {
785                         r = uev_add_map(uev, vecs);
786                         goto out;
787                 }
788                 if (!strncmp(uev->action, "remove", 6)) {
789                         r = uev_remove_map(uev, vecs);
790                         goto out;
791                 }
792                 goto out;
793         }
794
795         /*
796          * path add/remove event
797          */
798         if (filter_devnode(conf->blist_devnode, conf->elist_devnode,
799                            uev->kernel) > 0)
800                 goto out;
801
802         if (!strncmp(uev->action, "add", 3)) {
803                 r = uev_add_path(uev, vecs);
804                 goto out;
805         }
806         if (!strncmp(uev->action, "remove", 6)) {
807                 r = uev_remove_path(uev, vecs);
808                 goto out;
809         }
810         if (!strncmp(uev->action, "change", 6)) {
811                 r = uev_update_path(uev, vecs);
812                 goto out;
813         }
814
815 out:
816         lock_cleanup_pop(vecs->lock);
817         return r;
818 }
819
820 static void *
821 ueventloop (void * ap)
822 {
823         block_signal(SIGUSR1, NULL);
824         block_signal(SIGHUP, NULL);
825
826         if (uevent_listen())
827                 condlog(0, "error starting uevent listener");
828
829         return NULL;
830 }
831
832 static void *
833 uevqloop (void * ap)
834 {
835         block_signal(SIGUSR1, NULL);
836         block_signal(SIGHUP, NULL);
837
838         if (uevent_dispatch(&uev_trigger, ap))
839                 condlog(0, "error starting uevent dispatcher");
840
841         return NULL;
842 }
843 static void *
844 uxlsnrloop (void * ap)
845 {
846         block_signal(SIGUSR1, NULL);
847         block_signal(SIGHUP, NULL);
848
849         if (cli_init())
850                 return NULL;
851
852         set_handler_callback(LIST+PATHS, cli_list_paths);
853         set_handler_callback(LIST+PATHS+FMT, cli_list_paths_fmt);
854         set_handler_callback(LIST+MAPS, cli_list_maps);
855         set_handler_callback(LIST+STATUS, cli_list_status);
856         set_handler_callback(LIST+DAEMON, cli_list_daemon);
857         set_handler_callback(LIST+MAPS+STATUS, cli_list_maps_status);
858         set_handler_callback(LIST+MAPS+STATS, cli_list_maps_stats);
859         set_handler_callback(LIST+MAPS+FMT, cli_list_maps_fmt);
860         set_handler_callback(LIST+MAPS+TOPOLOGY, cli_list_maps_topology);
861         set_handler_callback(LIST+TOPOLOGY, cli_list_maps_topology);
862         set_handler_callback(LIST+MAP+TOPOLOGY, cli_list_map_topology);
863         set_handler_callback(LIST+CONFIG, cli_list_config);
864         set_handler_callback(LIST+BLACKLIST, cli_list_blacklist);
865         set_handler_callback(LIST+DEVICES, cli_list_devices);
866         set_handler_callback(LIST+WILDCARDS, cli_list_wildcards);
867         set_handler_callback(ADD+PATH, cli_add_path);
868         set_handler_callback(DEL+PATH, cli_del_path);
869         set_handler_callback(ADD+MAP, cli_add_map);
870         set_handler_callback(DEL+MAP, cli_del_map);
871         set_handler_callback(SWITCH+MAP+GROUP, cli_switch_group);
872         set_handler_callback(RECONFIGURE, cli_reconfigure);
873         set_handler_callback(SUSPEND+MAP, cli_suspend);
874         set_handler_callback(RESUME+MAP, cli_resume);
875         set_handler_callback(RESIZE+MAP, cli_resize);
876         set_handler_callback(RELOAD+MAP, cli_reload);
877         set_handler_callback(RESET+MAP, cli_reassign);
878         set_handler_callback(REINSTATE+PATH, cli_reinstate);
879         set_handler_callback(FAIL+PATH, cli_fail);
880         set_handler_callback(DISABLEQ+MAP, cli_disable_queueing);
881         set_handler_callback(RESTOREQ+MAP, cli_restore_queueing);
882         set_handler_callback(DISABLEQ+MAPS, cli_disable_all_queueing);
883         set_handler_callback(RESTOREQ+MAPS, cli_restore_all_queueing);
884         set_handler_callback(QUIT, cli_quit);
885         set_handler_callback(SHUTDOWN, cli_shutdown);
886         set_handler_callback(GETPRSTATUS+MAP, cli_getprstatus);
887         set_handler_callback(SETPRSTATUS+MAP, cli_setprstatus);
888         set_handler_callback(UNSETPRSTATUS+MAP, cli_unsetprstatus);
889
890         umask(077);
891         uxsock_listen(&uxsock_trigger, ap);
892
893         return NULL;
894 }
895
896 int
897 exit_daemon (int status)
898 {
899         if (status != 0)
900                 fprintf(stderr, "bad exit status. see daemon.log\n");
901
902         condlog(3, "unlink pidfile");
903         unlink(DEFAULT_PIDFILE);
904
905         pthread_mutex_lock(&exit_mutex);
906         pthread_cond_signal(&exit_cond);
907         pthread_mutex_unlock(&exit_mutex);
908
909         return status;
910 }
911
912 const char *
913 daemon_status(void)
914 {
915         switch (running_state) {
916         case DAEMON_INIT:
917                 return "init";
918         case DAEMON_START:
919                 return "startup";
920         case DAEMON_CONFIGURE:
921                 return "configure";
922         case DAEMON_RUNNING:
923                 return "running";
924         case DAEMON_SHUTDOWN:
925                 return "shutdown";
926         }
927         return NULL;
928 }
929
930 static void
931 fail_path (struct path * pp, int del_active)
932 {
933         if (!pp->mpp)
934                 return;
935
936         condlog(2, "checker failed path %s in map %s",
937                  pp->dev_t, pp->mpp->alias);
938
939         dm_fail_path(pp->mpp->alias, pp->dev_t);
940         if (del_active)
941                 update_queue_mode_del_path(pp->mpp);
942 }
943
944 /*
945  * caller must have locked the path list before calling that function
946  */
947 static void
948 reinstate_path (struct path * pp, int add_active)
949 {
950         if (!pp->mpp)
951                 return;
952
953         if (dm_reinstate_path(pp->mpp->alias, pp->dev_t))
954                 condlog(0, "%s: reinstate failed", pp->dev_t);
955         else {
956                 condlog(2, "%s: reinstated", pp->dev_t);
957                 if (add_active)
958                         update_queue_mode_add_path(pp->mpp);
959         }
960 }
961
962 static void
963 enable_group(struct path * pp)
964 {
965         struct pathgroup * pgp;
966
967         /*
968          * if path is added through uev_add_path, pgindex can be unset.
969          * next update_strings() will set it, upon map reload event.
970          *
971          * we can safely return here, because upon map reload, all
972          * PG will be enabled.
973          */
974         if (!pp->mpp->pg || !pp->pgindex)
975                 return;
976
977         pgp = VECTOR_SLOT(pp->mpp->pg, pp->pgindex - 1);
978
979         if (pgp->status == PGSTATE_DISABLED) {
980                 condlog(2, "%s: enable group #%i", pp->mpp->alias, pp->pgindex);
981                 dm_enablegroup(pp->mpp->alias, pp->pgindex);
982         }
983 }
984
985 static void
986 mpvec_garbage_collector (struct vectors * vecs)
987 {
988         struct multipath * mpp;
989         unsigned int i;
990
991         if (!vecs->mpvec)
992                 return;
993
994         vector_foreach_slot (vecs->mpvec, mpp, i) {
995                 if (mpp && mpp->alias && !dm_map_present(mpp->alias)) {
996                         condlog(2, "%s: remove dead map", mpp->alias);
997                         remove_map_and_stop_waiter(mpp, vecs, 1);
998                         i--;
999                 }
1000         }
1001 }
1002
1003 static void
1004 defered_failback_tick (vector mpvec)
1005 {
1006         struct multipath * mpp;
1007         unsigned int i;
1008
1009         vector_foreach_slot (mpvec, mpp, i) {
1010                 /*
1011                  * defered failback getting sooner
1012                  */
1013                 if (mpp->pgfailback > 0 && mpp->failback_tick > 0) {
1014                         mpp->failback_tick--;
1015
1016                         if (!mpp->failback_tick && need_switch_pathgroup(mpp, 1))
1017                                 switch_pathgroup(mpp);
1018                 }
1019         }
1020 }
1021
1022 static void
1023 retry_count_tick(vector mpvec)
1024 {
1025         struct multipath *mpp;
1026         unsigned int i;
1027
1028         vector_foreach_slot (mpvec, mpp, i) {
1029                 if (mpp->retry_tick) {
1030                         mpp->stat_total_queueing_time++;
1031                         condlog(4, "%s: Retrying.. No active path", mpp->alias);
1032                         if(--mpp->retry_tick == 0) {
1033                                 dm_queue_if_no_path(mpp->alias, 0);
1034                                 condlog(2, "%s: Disable queueing", mpp->alias);
1035                         }
1036                 }
1037         }
1038 }
1039
1040 int update_prio(struct path *pp, int refresh_all)
1041 {
1042         int oldpriority;
1043         struct path *pp1;
1044         struct pathgroup * pgp;
1045         int i, j, changed = 0;
1046
1047         if (refresh_all) {
1048                 vector_foreach_slot (pp->mpp->pg, pgp, i) {
1049                         vector_foreach_slot (pgp->paths, pp1, j) {
1050                                 oldpriority = pp1->priority;
1051                                 pathinfo(pp1, conf->hwtable, DI_PRIO);
1052                                 if (pp1->priority != oldpriority)
1053                                         changed = 1;
1054                         }
1055                 }
1056                 return changed;
1057         }
1058         oldpriority = pp->priority;
1059         pathinfo(pp, conf->hwtable, DI_PRIO);
1060
1061         if (pp->priority == oldpriority)
1062                 return 0;
1063         return 1;
1064 }
1065
1066 int update_path_groups(struct multipath *mpp, struct vectors *vecs, int refresh)
1067 {
1068         int i;
1069         struct path * pp;
1070         char params[PARAMS_SIZE];
1071
1072         update_mpp_paths(mpp, vecs->pathvec);
1073         if (refresh) {
1074                 vector_foreach_slot (mpp->paths, pp, i)
1075                         pathinfo(pp, conf->hwtable, DI_PRIO);
1076         }
1077         params[0] = '\0';
1078         if (setup_map(mpp, params, PARAMS_SIZE))
1079                 return 1;
1080
1081         mpp->action = ACT_RELOAD;
1082         if (domap(mpp, params) <= 0) {
1083                 condlog(0, "%s: failed to update map : %s", mpp->alias,
1084                         strerror(errno));
1085                 return 1;
1086         }
1087         dm_lib_release();
1088         if (setup_multipath(vecs, mpp) != 0)
1089                 return 1;
1090         sync_map_state(mpp);
1091
1092         return 0;
1093 }
1094
1095 void
1096 check_path (struct vectors * vecs, struct path * pp)
1097 {
1098         int newstate;
1099         int new_path_up = 0;
1100
1101         if (!pp->mpp)
1102                 return;
1103
1104         if (pp->tick && --pp->tick)
1105                 return; /* don't check this path yet */
1106
1107         /*
1108          * provision a next check soonest,
1109          * in case we exit abnormaly from here
1110          */
1111         pp->tick = conf->checkint;
1112
1113         newstate = path_offline(pp);
1114         if (newstate == PATH_UP)
1115                 newstate = get_state(pp, 1);
1116
1117         if (newstate == PATH_WILD || newstate == PATH_UNCHECKED) {
1118                 condlog(2, "%s: unusable path", pp->dev);
1119                 pathinfo(pp, conf->hwtable, 0);
1120                 return;
1121         }
1122         /*
1123          * Async IO in flight. Keep the previous path state
1124          * and reschedule as soon as possible
1125          */
1126         if (newstate == PATH_PENDING) {
1127                 pp->tick = 1;
1128                 return;
1129         }
1130         /*
1131          * Synchronize with kernel state
1132          */
1133         if (update_multipath_strings(pp->mpp, vecs->pathvec)) {
1134                 condlog(1, "%s: Could not synchronize with kernel state\n",
1135                         pp->dev);
1136                 pp->dmstate = PSTATE_UNDEF;
1137         }
1138         if (newstate != pp->state) {
1139                 int oldstate = pp->state;
1140                 pp->state = newstate;
1141                 LOG_MSG(1, checker_message(&pp->checker));
1142
1143                 /*
1144                  * upon state change, reset the checkint
1145                  * to the shortest delay
1146                  */
1147                 pp->checkint = conf->checkint;
1148
1149                 if (newstate == PATH_DOWN || newstate == PATH_SHAKY) {
1150                         /*
1151                          * proactively fail path in the DM
1152                          */
1153                         if (oldstate == PATH_UP ||
1154                             oldstate == PATH_GHOST)
1155                                 fail_path(pp, 1);
1156                         else
1157                                 fail_path(pp, 0);
1158
1159                         /*
1160                          * cancel scheduled failback
1161                          */
1162                         pp->mpp->failback_tick = 0;
1163
1164                         pp->mpp->stat_path_failures++;
1165                         return;
1166                 }
1167
1168                 if(newstate == PATH_UP || newstate == PATH_GHOST){
1169                         if ( pp->mpp && pp->mpp->prflag ){
1170                                 /*
1171                                  * Check Persistent Reservation.
1172                                  */
1173                         condlog(2, "%s: checking persistent reservation "
1174                                 "registration", pp->dev);
1175                         mpath_pr_event_handle(pp);
1176                         }
1177                 }
1178
1179                 /*
1180                  * reinstate this path
1181                  */
1182                 if (oldstate != PATH_UP &&
1183                     oldstate != PATH_GHOST)
1184                         reinstate_path(pp, 1);
1185                 else
1186                         reinstate_path(pp, 0);
1187
1188                 new_path_up = 1;
1189
1190                 /*
1191                  * if at least one path is up in a group, and
1192                  * the group is disabled, re-enable it
1193                  */
1194                 if (newstate == PATH_UP)
1195                         enable_group(pp);
1196         }
1197         else if (newstate == PATH_UP || newstate == PATH_GHOST) {
1198                 if (pp->dmstate == PSTATE_FAILED ||
1199                     pp->dmstate == PSTATE_UNDEF) {
1200                         /* Clear IO errors */
1201                         reinstate_path(pp, 0);
1202                 } else {
1203                         LOG_MSG(4, checker_message(&pp->checker));
1204                         /*
1205                          * double the next check delay.
1206                          * max at conf->max_checkint
1207                          */
1208                         if (pp->checkint < (conf->max_checkint / 2))
1209                                 pp->checkint = 2 * pp->checkint;
1210                         else
1211                                 pp->checkint = conf->max_checkint;
1212
1213                         pp->tick = pp->checkint;
1214                         condlog(4, "%s: delay next check %is",
1215                                 pp->dev_t, pp->tick);
1216                 }
1217         }
1218         else if (newstate == PATH_DOWN) {
1219                 if (conf->log_checker_err == LOG_CHKR_ERR_ONCE)
1220                         LOG_MSG(3, checker_message(&pp->checker));
1221                 else
1222                         LOG_MSG(2, checker_message(&pp->checker));
1223         }
1224
1225         pp->state = newstate;
1226
1227         /*
1228          * path prio refreshing
1229          */
1230         condlog(4, "path prio refresh");
1231
1232         if (update_prio(pp, new_path_up) &&
1233             (pp->mpp->pgpolicyfn == (pgpolicyfn *)group_by_prio) &&
1234              pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1235                 update_path_groups(pp->mpp, vecs, !new_path_up);
1236         else if (need_switch_pathgroup(pp->mpp, 0)) {
1237                 if (pp->mpp->pgfailback > 0 &&
1238                     (new_path_up || pp->mpp->failback_tick <= 0))
1239                         pp->mpp->failback_tick =
1240                                 pp->mpp->pgfailback + 1;
1241                 else if (pp->mpp->pgfailback == -FAILBACK_IMMEDIATE)
1242                         switch_pathgroup(pp->mpp);
1243         }
1244 }
1245
1246 static void *
1247 checkerloop (void *ap)
1248 {
1249         struct vectors *vecs;
1250         struct path *pp;
1251         int count = 0;
1252         unsigned int i;
1253         sigset_t old;
1254
1255         mlockall(MCL_CURRENT | MCL_FUTURE);
1256         vecs = (struct vectors *)ap;
1257         condlog(2, "path checkers start up");
1258
1259         /*
1260          * init the path check interval
1261          */
1262         vector_foreach_slot (vecs->pathvec, pp, i) {
1263                 pp->checkint = conf->checkint;
1264         }
1265
1266         while (1) {
1267                 block_signal(SIGHUP, &old);
1268                 pthread_cleanup_push(cleanup_lock, &vecs->lock);
1269                 lock(vecs->lock);
1270                 pthread_testcancel();
1271                 condlog(4, "tick");
1272
1273                 if (vecs->pathvec) {
1274                         vector_foreach_slot (vecs->pathvec, pp, i) {
1275                                 check_path(vecs, pp);
1276                         }
1277                 }
1278                 if (vecs->mpvec) {
1279                         defered_failback_tick(vecs->mpvec);
1280                         retry_count_tick(vecs->mpvec);
1281                 }
1282                 if (count)
1283                         count--;
1284                 else {
1285                         condlog(4, "map garbage collection");
1286                         mpvec_garbage_collector(vecs);
1287                         count = MAPGCINT;
1288                 }
1289
1290                 lock_cleanup_pop(vecs->lock);
1291                 pthread_sigmask(SIG_SETMASK, &old, NULL);
1292                 sleep(1);
1293         }
1294         return NULL;
1295 }
1296
1297 int
1298 configure (struct vectors * vecs, int start_waiters)
1299 {
1300         struct multipath * mpp;
1301         struct path * pp;
1302         vector mpvec;
1303         int i;
1304
1305         if (!vecs->pathvec && !(vecs->pathvec = vector_alloc()))
1306                 return 1;
1307
1308         if (!vecs->mpvec && !(vecs->mpvec = vector_alloc()))
1309                 return 1;
1310
1311         if (!(mpvec = vector_alloc()))
1312                 return 1;
1313
1314         /*
1315          * probe for current path (from sysfs) and map (from dm) sets
1316          */
1317         path_discovery(vecs->pathvec, conf, DI_ALL);
1318
1319         vector_foreach_slot (vecs->pathvec, pp, i){
1320                 if (filter_path(conf, pp) > 0){
1321                         vector_del_slot(vecs->pathvec, i);
1322                         free_path(pp);
1323                         i--;
1324                 }
1325                 else
1326                         pp->checkint = conf->checkint;
1327         }
1328         if (map_discovery(vecs))
1329                 return 1;
1330
1331         /*
1332          * create new set of maps & push changed ones into dm
1333          */
1334         if (coalesce_paths(vecs, mpvec, NULL, 1))
1335                 return 1;
1336
1337         /*
1338          * may need to remove some maps which are no longer relevant
1339          * e.g., due to blacklist changes in conf file
1340          */
1341         if (coalesce_maps(vecs, mpvec))
1342                 return 1;
1343
1344         dm_lib_release();
1345
1346         sync_maps_state(mpvec);
1347         vector_foreach_slot(mpvec, mpp, i){
1348                 update_map_pr(mpp);
1349         }
1350
1351         /*
1352          * purge dm of old maps
1353          */
1354         remove_maps(vecs);
1355
1356         /*
1357          * save new set of maps formed by considering current path state
1358          */
1359         vector_free(vecs->mpvec);
1360         vecs->mpvec = mpvec;
1361
1362         /*
1363          * start dm event waiter threads for these new maps
1364          */
1365         vector_foreach_slot(vecs->mpvec, mpp, i) {
1366                 if (setup_multipath(vecs, mpp))
1367                         return 1;
1368                 if (start_waiters)
1369                         if (start_waiter_thread(mpp, vecs))
1370                                 return 1;
1371         }
1372         return 0;
1373 }
1374
1375 int
1376 reconfigure (struct vectors * vecs)
1377 {
1378         struct config * old = conf;
1379         int retval = 1;
1380
1381         /*
1382          * free old map and path vectors ... they use old conf state
1383          */
1384         if (VECTOR_SIZE(vecs->mpvec))
1385                 remove_maps_and_stop_waiters(vecs);
1386
1387         if (VECTOR_SIZE(vecs->pathvec))
1388                 free_pathvec(vecs->pathvec, FREE_PATHS);
1389
1390         vecs->pathvec = NULL;
1391         conf = NULL;
1392
1393         if (!load_config(DEFAULT_CONFIGFILE)) {
1394                 conf->verbosity = old->verbosity;
1395                 conf->daemon = 1;
1396                 configure(vecs, 1);
1397                 free_config(old);
1398                 retval = 0;
1399         }
1400
1401         return retval;
1402 }
1403
1404 static struct vectors *
1405 init_vecs (void)
1406 {
1407         struct vectors * vecs;
1408
1409         vecs = (struct vectors *)MALLOC(sizeof(struct vectors));
1410
1411         if (!vecs)
1412                 return NULL;
1413
1414         vecs->lock.mutex =
1415                 (pthread_mutex_t *)MALLOC(sizeof(pthread_mutex_t));
1416
1417         if (!vecs->lock.mutex)
1418                 goto out;
1419
1420         pthread_mutex_init(vecs->lock.mutex, NULL);
1421         vecs->lock.depth = 0;
1422
1423         return vecs;
1424
1425 out:
1426         FREE(vecs);
1427         condlog(0, "failed to init paths");
1428         return NULL;
1429 }
1430
1431 static void *
1432 signal_set(int signo, void (*func) (int))
1433 {
1434         int r;
1435         struct sigaction sig;
1436         struct sigaction osig;
1437
1438         sig.sa_handler = func;
1439         sigemptyset(&sig.sa_mask);
1440         sig.sa_flags = 0;
1441
1442         r = sigaction(signo, &sig, &osig);
1443
1444         if (r < 0)
1445                 return (SIG_ERR);
1446         else
1447                 return (osig.sa_handler);
1448 }
1449
1450 static void
1451 sighup (int sig)
1452 {
1453         condlog(2, "reconfigure (SIGHUP)");
1454
1455         if (running_state != DAEMON_RUNNING)
1456                 return;
1457
1458         lock(gvecs->lock);
1459         reconfigure(gvecs);
1460         unlock(gvecs->lock);
1461
1462 #ifdef _DEBUG_
1463         dbg_free_final(NULL);
1464 #endif
1465 }
1466
1467 static void
1468 sigend (int sig)
1469 {
1470         exit_daemon(0);
1471 }
1472
1473 static void
1474 sigusr1 (int sig)
1475 {
1476         condlog(3, "SIGUSR1 received");
1477 }
1478
1479 static void
1480 signal_init(void)
1481 {
1482         signal_set(SIGHUP, sighup);
1483         signal_set(SIGUSR1, sigusr1);
1484         signal_set(SIGINT, sigend);
1485         signal_set(SIGTERM, sigend);
1486         signal(SIGPIPE, SIG_IGN);
1487 }
1488
1489 static void
1490 setscheduler (void)
1491 {
1492         int res;
1493         static struct sched_param sched_param = {
1494                 .sched_priority = 99
1495         };
1496
1497         res = sched_setscheduler (0, SCHED_RR, &sched_param);
1498
1499         if (res == -1)
1500                 condlog(LOG_WARNING, "Could not set SCHED_RR at priority 99");
1501         return;
1502 }
1503
1504 static void
1505 set_oom_adj (void)
1506 {
1507 #ifdef OOM_SCORE_ADJ_MIN
1508         int retry = 1;
1509         char *file = "/proc/self/oom_score_adj";
1510         int score = OOM_SCORE_ADJ_MIN;
1511 #else
1512         int retry = 0;
1513         char *file = "/proc/self/oom_adj";
1514         int score = OOM_ADJUST_MIN;
1515 #endif
1516         FILE *fp;
1517         struct stat st;
1518
1519         do {
1520                 if (stat(file, &st) == 0){
1521                         fp = fopen(file, "w");
1522                         if (!fp) {
1523                                 condlog(0, "couldn't fopen %s : %s", file,
1524                                         strerror(errno));
1525                                 return;
1526                         }
1527                         fprintf(fp, "%i", score);
1528                         fclose(fp);
1529                         return;
1530                 }
1531                 if (errno != ENOENT) {
1532                         condlog(0, "couldn't stat %s : %s", file,
1533                                 strerror(errno));
1534                         return;
1535                 }
1536                 file = "/proc/self/oom_adj";
1537                 score = OOM_ADJUST_MIN;
1538         } while (retry--);
1539         condlog(0, "couldn't adjust oom score");
1540 }
1541
1542 static int
1543 child (void * param)
1544 {
1545         pthread_t check_thr, uevent_thr, uxlsnr_thr, uevq_thr;
1546         pthread_attr_t log_attr, misc_attr;
1547         struct vectors * vecs;
1548         struct multipath * mpp;
1549         int i;
1550         int rc;
1551
1552         mlockall(MCL_CURRENT | MCL_FUTURE);
1553
1554         setup_thread_attr(&misc_attr, 64 * 1024, 1);
1555         setup_thread_attr(&waiter_attr, 32 * 1024, 1);
1556
1557         if (logsink) {
1558                 setup_thread_attr(&log_attr, 64 * 1024, 0);
1559                 log_thread_start(&log_attr);
1560                 pthread_attr_destroy(&log_attr);
1561         }
1562
1563         running_state = DAEMON_START;
1564
1565         condlog(2, "--------start up--------");
1566         condlog(2, "read " DEFAULT_CONFIGFILE);
1567
1568         if (load_config(DEFAULT_CONFIGFILE))
1569                 exit(1);
1570
1571         if (init_checkers()) {
1572                 condlog(0, "failed to initialize checkers");
1573                 exit(1);
1574         }
1575         if (init_prio()) {
1576                 condlog(0, "failed to initialize prioritizers");
1577                 exit(1);
1578         }
1579
1580         setlogmask(LOG_UPTO(conf->verbosity + 3));
1581
1582         if (conf->max_fds) {
1583                 struct rlimit fd_limit;
1584
1585                 if (getrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1586                         condlog(0, "can't get open fds limit: %s\n",
1587                                 strerror(errno));
1588                         fd_limit.rlim_cur = 0;
1589                         fd_limit.rlim_max = 0;
1590                 }
1591                 if (fd_limit.rlim_cur < conf->max_fds) {
1592                         fd_limit.rlim_cur = conf->max_fds;
1593                         if (fd_limit.rlim_max < conf->max_fds)
1594                                 fd_limit.rlim_max = conf->max_fds;
1595                         if (setrlimit(RLIMIT_NOFILE, &fd_limit) < 0) {
1596                                 condlog(0, "can't set open fds limit to "
1597                                         "%lu/%lu : %s\n",
1598                                         fd_limit.rlim_cur, fd_limit.rlim_max,
1599                                         strerror(errno));
1600                         } else {
1601                                 condlog(3, "set open fds limit to %lu/%lu\n",
1602                                         fd_limit.rlim_cur, fd_limit.rlim_max);
1603                         }
1604                 }
1605
1606         }
1607
1608         signal_init();
1609         setscheduler();
1610         set_oom_adj();
1611         vecs = gvecs = init_vecs();
1612
1613         if (!vecs)
1614                 exit(1);
1615
1616         conf->daemon = 1;
1617         udev_set_sync_support(0);
1618         /*
1619          * Start uevent listener early to catch events
1620          */
1621         if ((rc = pthread_create(&uevent_thr, &misc_attr, ueventloop, vecs))) {
1622                 condlog(0, "failed to create uevent thread: %d", rc);
1623                 exit(1);
1624         }
1625         if ((rc = pthread_create(&uxlsnr_thr, &misc_attr, uxlsnrloop, vecs))) {
1626                 condlog(0, "failed to create cli listener: %d", rc);
1627                 exit(1);
1628         }
1629         /*
1630          * fetch and configure both paths and multipaths
1631          */
1632         lock(vecs->lock);
1633         running_state = DAEMON_CONFIGURE;
1634
1635         if (configure(vecs, 1)) {
1636                 unlock(vecs->lock);
1637                 condlog(0, "failure during configuration");
1638                 exit(1);
1639         }
1640         unlock(vecs->lock);
1641
1642         /*
1643          * start threads
1644          */
1645         if ((rc = pthread_create(&check_thr, &misc_attr, checkerloop, vecs))) {
1646                 condlog(0,"failed to create checker loop thread: %d", rc);
1647                 exit(1);
1648         }
1649         if ((rc = pthread_create(&uevq_thr, &misc_attr, uevqloop, vecs))) {
1650                 condlog(0, "failed to create uevent dispatcher: %d", rc);
1651                 exit(1);
1652         }
1653         pthread_attr_destroy(&misc_attr);
1654
1655         pthread_mutex_lock(&exit_mutex);
1656         /* Startup complete, create logfile */
1657         if (pidfile_create(DEFAULT_PIDFILE, daemon_pid))
1658                 /* Ignore errors, we can live without */
1659                 condlog(1, "failed to create pidfile");
1660
1661         running_state = DAEMON_RUNNING;
1662         pthread_cond_wait(&exit_cond, &exit_mutex);
1663
1664         /*
1665          * exit path
1666          */
1667         running_state = DAEMON_SHUTDOWN;
1668         block_signal(SIGHUP, NULL);
1669         lock(vecs->lock);
1670         if (conf->queue_without_daemon == QUE_NO_DAEMON_OFF)
1671                 vector_foreach_slot(vecs->mpvec, mpp, i)
1672                         dm_queue_if_no_path(mpp->alias, 0);
1673         remove_maps_and_stop_waiters(vecs);
1674         unlock(vecs->lock);
1675
1676         pthread_cancel(check_thr);
1677         pthread_cancel(uevent_thr);
1678         pthread_cancel(uxlsnr_thr);
1679         pthread_cancel(uevq_thr);
1680
1681         lock(vecs->lock);
1682         free_pathvec(vecs->pathvec, FREE_PATHS);
1683         vecs->pathvec = NULL;
1684         unlock(vecs->lock);
1685         /* Now all the waitevent threads will start rushing in. */
1686         while (vecs->lock.depth > 0) {
1687                 sleep (1); /* This is weak. */
1688                 condlog(3,"Have %d wait event checkers threads to de-alloc, waiting..\n", vecs->lock.depth);
1689         }
1690         pthread_mutex_destroy(vecs->lock.mutex);
1691         FREE(vecs->lock.mutex);
1692         vecs->lock.depth = 0;
1693         vecs->lock.mutex = NULL;
1694         FREE(vecs);
1695         vecs = NULL;
1696
1697         cleanup_checkers();
1698         cleanup_prio();
1699
1700         dm_lib_release();
1701         dm_lib_exit();
1702
1703         /* We're done here */
1704         condlog(3, "unlink pidfile");
1705         unlink(DEFAULT_PIDFILE);
1706
1707         condlog(2, "--------shut down-------");
1708
1709         if (logsink)
1710                 log_thread_stop();
1711
1712         /*
1713          * Freeing config must be done after condlog() and dm_lib_exit(),
1714          * because logging functions like dlog() and dm_write_log()
1715          * reference the config.
1716          */
1717         free_config(conf);
1718         conf = NULL;
1719
1720 #ifdef _DEBUG_
1721         dbg_free_final(NULL);
1722 #endif
1723
1724         exit(0);
1725 }
1726
1727 static int
1728 daemonize(void)
1729 {
1730         int pid;
1731         int dev_null_fd;
1732
1733         if( (pid = fork()) < 0){
1734                 fprintf(stderr, "Failed first fork : %s\n", strerror(errno));
1735                 return -1;
1736         }
1737         else if (pid != 0)
1738                 return pid;
1739
1740         setsid();
1741
1742         if ( (pid = fork()) < 0)
1743                 fprintf(stderr, "Failed second fork : %s\n", strerror(errno));
1744         else if (pid != 0)
1745                 _exit(0);
1746
1747         if (chdir("/") < 0)
1748                 fprintf(stderr, "cannot chdir to '/', continuing\n");
1749
1750         dev_null_fd = open("/dev/null", O_RDWR);
1751         if (dev_null_fd < 0){
1752                 fprintf(stderr, "cannot open /dev/null for input & output : %s\n",
1753                         strerror(errno));
1754                 _exit(0);
1755         }
1756
1757         close(STDIN_FILENO);
1758         dup(dev_null_fd);
1759         close(STDOUT_FILENO);
1760         dup(dev_null_fd);
1761         close(STDERR_FILENO);
1762         dup(dev_null_fd);
1763         close(dev_null_fd);
1764         daemon_pid = getpid();
1765         return 0;
1766 }
1767
1768 int
1769 main (int argc, char *argv[])
1770 {
1771         extern char *optarg;
1772         extern int optind;
1773         int arg;
1774         int err;
1775
1776         logsink = 1;
1777         running_state = DAEMON_INIT;
1778         dm_init();
1779
1780         if (getuid() != 0) {
1781                 fprintf(stderr, "need to be root\n");
1782                 exit(1);
1783         }
1784
1785         /* make sure we don't lock any path */
1786         chdir("/");
1787         umask(umask(077) | 022);
1788
1789         conf = alloc_config();
1790
1791         if (!conf)
1792                 exit(1);
1793
1794         while ((arg = getopt(argc, argv, ":dv:k::")) != EOF ) {
1795         switch(arg) {
1796                 case 'd':
1797                         logsink = 0;
1798                         //debug=1; /* ### comment me out ### */
1799                         break;
1800                 case 'v':
1801                         if (sizeof(optarg) > sizeof(char *) ||
1802                             !isdigit(optarg[0]))
1803                                 exit(1);
1804
1805                         conf->verbosity = atoi(optarg);
1806                         break;
1807                 case 'k':
1808                         uxclnt(optarg);
1809                         exit(0);
1810                 default:
1811                         ;
1812                 }
1813         }
1814         if (optind < argc) {
1815                 char cmd[CMDSIZE];
1816                 char * s = cmd;
1817                 char * c = s;
1818
1819                 while (optind < argc) {
1820                         if (strchr(argv[optind], ' '))
1821                                 c += snprintf(c, s + CMDSIZE - c, "\"%s\" ", argv[optind]);
1822                         else
1823                                 c += snprintf(c, s + CMDSIZE - c, "%s ", argv[optind]);
1824                         optind++;
1825                 }
1826                 c += snprintf(c, s + CMDSIZE - c, "\n");
1827                 uxclnt(s);
1828                 exit(0);
1829         }
1830
1831         if (!logsink)
1832                 err = 0;
1833         else
1834                 err = daemonize();
1835
1836         if (err < 0)
1837                 /* error */
1838                 exit(1);
1839         else if (err > 0)
1840                 /* parent dies */
1841                 exit(0);
1842         else
1843                 /* child lives */
1844                 return (child(NULL));
1845 }
1846
1847 void *  mpath_pr_event_handler_fn (void * pathp )
1848 {
1849         struct multipath * mpp;
1850         int i,j, ret, isFound;
1851         struct path * pp = (struct path *)pathp;
1852         unsigned char *keyp;
1853         uint64_t prkey;
1854         struct prout_param_descriptor *param;
1855         struct prin_resp *resp;
1856
1857         mpp = pp->mpp;
1858
1859         resp = mpath_alloc_prin_response(MPATH_PRIN_RKEY_SA);
1860         if (!resp){
1861                 condlog(0,"%s Alloc failed for prin response \n", pp->dev);
1862                 return NULL;
1863         }
1864
1865         ret = prin_do_scsi_ioctl(pp->dev, MPATH_PRIN_RKEY_SA, resp, 0);
1866         if (ret != MPATH_PR_SUCCESS )
1867         {
1868                 condlog(0,"%s : pr in read keys service action failed. Error=%d\n", pp->dev, ret);
1869                 goto out;
1870         }
1871
1872         condlog(3, " event pr=%d addlen=%d\n",resp->prin_descriptor.prin_readkeys.prgeneration,
1873                         resp->prin_descriptor.prin_readkeys.additional_length );
1874
1875         if (resp->prin_descriptor.prin_readkeys.additional_length == 0 )
1876         {
1877                 condlog(1, "%s: No key found. Device may not be registered.", pp->dev);
1878                 ret = MPATH_PR_SUCCESS;
1879                 goto out;
1880         }
1881         prkey = 0;
1882         keyp = (unsigned char *)mpp->reservation_key;
1883         for (j = 0; j < 8; ++j) {
1884                 if (j > 0)
1885                         prkey <<= 8;
1886                 prkey |= *keyp;
1887                 ++keyp;
1888         }
1889         condlog(2, "Multipath  reservation_key: 0x%" PRIx64 " ", prkey);
1890
1891         isFound =0;
1892         for (i = 0; i < resp->prin_descriptor.prin_readkeys.additional_length/8; i++ )
1893         {
1894                 condlog(2, "PR IN READKEYS[%d]  reservation key:\n",i);
1895                 dumpHex((char *)&resp->prin_descriptor.prin_readkeys.key_list[i*8], 8 , -1);
1896                 if (!memcmp(mpp->reservation_key, &resp->prin_descriptor.prin_readkeys.key_list[i*8], 8))
1897                 {
1898                         condlog(2, "%s: pr key found in prin readkeys response", mpp->alias);
1899                         isFound =1;
1900                         break;
1901                 }
1902         }
1903         if (!isFound)
1904         {
1905                 condlog(0, "%s: Either device not registered or ", pp->dev);
1906                 condlog(0, "host is not authorised for registration. Skip path\n");
1907                 ret = MPATH_PR_OTHER;
1908                 goto out;
1909         }
1910
1911         param= malloc(sizeof(struct prout_param_descriptor));
1912         memset(param, 0 , sizeof(struct prout_param_descriptor));
1913
1914         for (j = 7; j >= 0; --j) {
1915                 param->sa_key[j] = (prkey & 0xff);
1916                 prkey >>= 8;
1917         }
1918         param->num_transportid = 0;
1919
1920         condlog(3, "device %s:%s \n", pp->dev, pp->mpp->wwid);
1921
1922         ret = prout_do_scsi_ioctl(pp->dev, MPATH_PROUT_REG_IGN_SA, 0, 0, param, 0);
1923         if (ret != MPATH_PR_SUCCESS )
1924         {
1925                 condlog(0,"%s: Reservation registration failed. Error: %d\n", pp->dev, ret);
1926         }
1927         mpp->prflag = 1;
1928
1929         free(param);
1930 out:
1931         free(resp);
1932         return NULL;
1933 }
1934
1935 int mpath_pr_event_handle(struct path *pp)
1936 {
1937         pthread_t thread;
1938         int rc;
1939         pthread_attr_t attr;
1940         struct multipath * mpp;
1941
1942         mpp = pp->mpp;
1943
1944         if (!mpp->reservation_key)
1945                 return -1;
1946
1947         pthread_attr_init(&attr);
1948         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
1949
1950         rc = pthread_create(&thread, NULL , mpath_pr_event_handler_fn, pp);
1951         if (rc) {
1952                 condlog(0, "%s: ERROR; return code from pthread_create() is %d\n", pp->dev, rc);
1953                 return -1;
1954         }
1955         pthread_attr_destroy(&attr);
1956         rc = pthread_join(thread, NULL);
1957         return 0;
1958 }
1959