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