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