ipc: fix missing mutex unlocks on failed send
[dpdk.git] / lib / librte_eal / common / eal_common_proc.c
1 /* SPDX-License-Identifier: BSD-3-Clause
2  * Copyright(c) 2016-2018 Intel Corporation
3  */
4
5 #include <dirent.h>
6 #include <errno.h>
7 #include <fcntl.h>
8 #include <fnmatch.h>
9 #include <inttypes.h>
10 #include <libgen.h>
11 #include <limits.h>
12 #include <pthread.h>
13 #include <stdio.h>
14 #include <stdlib.h>
15 #include <string.h>
16 #include <sys/file.h>
17 #include <sys/time.h>
18 #include <sys/types.h>
19 #include <sys/socket.h>
20 #include <sys/un.h>
21 #include <unistd.h>
22
23 #include <rte_common.h>
24 #include <rte_cycles.h>
25 #include <rte_eal.h>
26 #include <rte_errno.h>
27 #include <rte_lcore.h>
28 #include <rte_log.h>
29 #include <rte_tailq.h>
30
31 #include "eal_private.h"
32 #include "eal_filesystem.h"
33 #include "eal_internal_cfg.h"
34
35 static int mp_fd = -1;
36 static char mp_filter[PATH_MAX];   /* Filter for secondary process sockets */
37 static char mp_dir_path[PATH_MAX]; /* The directory path for all mp sockets */
38 static pthread_mutex_t mp_mutex_action = PTHREAD_MUTEX_INITIALIZER;
39
40 struct action_entry {
41         TAILQ_ENTRY(action_entry) next;
42         char action_name[RTE_MP_MAX_NAME_LEN];
43         rte_mp_t action;
44 };
45
46 /** Double linked list of actions. */
47 TAILQ_HEAD(action_entry_list, action_entry);
48
49 static struct action_entry_list action_entry_list =
50         TAILQ_HEAD_INITIALIZER(action_entry_list);
51
52 enum mp_type {
53         MP_MSG, /* Share message with peers, will not block */
54         MP_REQ, /* Request for information, Will block for a reply */
55         MP_REP, /* Response to previously-received request */
56         MP_IGN, /* Response telling requester to ignore this response */
57 };
58
59 struct mp_msg_internal {
60         int type;
61         struct rte_mp_msg msg;
62 };
63
64 struct async_request_param {
65         rte_mp_async_reply_t clb;
66         struct rte_mp_reply user_reply;
67         struct timespec end;
68         int n_responses_processed;
69 };
70
71 struct pending_request {
72         TAILQ_ENTRY(pending_request) next;
73         enum {
74                 REQUEST_TYPE_SYNC,
75                 REQUEST_TYPE_ASYNC
76         } type;
77         char dst[PATH_MAX];
78         struct rte_mp_msg *request;
79         struct rte_mp_msg *reply;
80         int reply_received;
81         RTE_STD_C11
82         union {
83                 struct {
84                         struct async_request_param *param;
85                 } async;
86                 struct {
87                         pthread_cond_t cond;
88                 } sync;
89         };
90 };
91
92 TAILQ_HEAD(pending_request_list, pending_request);
93
94 static struct {
95         struct pending_request_list requests;
96         pthread_mutex_t lock;
97         pthread_cond_t async_cond;
98 } pending_requests = {
99         .requests = TAILQ_HEAD_INITIALIZER(pending_requests.requests),
100         .lock = PTHREAD_MUTEX_INITIALIZER,
101         .async_cond = PTHREAD_COND_INITIALIZER
102         /**< used in async requests only */
103 };
104
105 /* forward declarations */
106 static int
107 mp_send(struct rte_mp_msg *msg, const char *peer, int type);
108
109
110 static struct pending_request *
111 find_sync_request(const char *dst, const char *act_name)
112 {
113         struct pending_request *r;
114
115         TAILQ_FOREACH(r, &pending_requests.requests, next) {
116                 if (!strcmp(r->dst, dst) &&
117                     !strcmp(r->request->name, act_name))
118                         break;
119         }
120
121         return r;
122 }
123
124 static void
125 create_socket_path(const char *name, char *buf, int len)
126 {
127         const char *prefix = eal_mp_socket_path();
128
129         if (strlen(name) > 0)
130                 snprintf(buf, len, "%s_%s", prefix, name);
131         else
132                 snprintf(buf, len, "%s", prefix);
133 }
134
135 int
136 rte_eal_primary_proc_alive(const char *config_file_path)
137 {
138         int config_fd;
139
140         if (config_file_path)
141                 config_fd = open(config_file_path, O_RDONLY);
142         else {
143                 const char *path;
144
145                 path = eal_runtime_config_path();
146                 config_fd = open(path, O_RDONLY);
147         }
148         if (config_fd < 0)
149                 return 0;
150
151         int ret = lockf(config_fd, F_TEST, 0);
152         close(config_fd);
153
154         return !!ret;
155 }
156
157 static struct action_entry *
158 find_action_entry_by_name(const char *name)
159 {
160         struct action_entry *entry;
161
162         TAILQ_FOREACH(entry, &action_entry_list, next) {
163                 if (strncmp(entry->action_name, name, RTE_MP_MAX_NAME_LEN) == 0)
164                         break;
165         }
166
167         return entry;
168 }
169
170 static int
171 validate_action_name(const char *name)
172 {
173         if (name == NULL) {
174                 RTE_LOG(ERR, EAL, "Action name cannot be NULL\n");
175                 rte_errno = EINVAL;
176                 return -1;
177         }
178         if (strnlen(name, RTE_MP_MAX_NAME_LEN) == 0) {
179                 RTE_LOG(ERR, EAL, "Length of action name is zero\n");
180                 rte_errno = EINVAL;
181                 return -1;
182         }
183         if (strnlen(name, RTE_MP_MAX_NAME_LEN) == RTE_MP_MAX_NAME_LEN) {
184                 rte_errno = E2BIG;
185                 return -1;
186         }
187         return 0;
188 }
189
190 int __rte_experimental
191 rte_mp_action_register(const char *name, rte_mp_t action)
192 {
193         struct action_entry *entry;
194
195         if (validate_action_name(name))
196                 return -1;
197
198         entry = malloc(sizeof(struct action_entry));
199         if (entry == NULL) {
200                 rte_errno = ENOMEM;
201                 return -1;
202         }
203         strcpy(entry->action_name, name);
204         entry->action = action;
205
206         pthread_mutex_lock(&mp_mutex_action);
207         if (find_action_entry_by_name(name) != NULL) {
208                 pthread_mutex_unlock(&mp_mutex_action);
209                 rte_errno = EEXIST;
210                 free(entry);
211                 return -1;
212         }
213         TAILQ_INSERT_TAIL(&action_entry_list, entry, next);
214         pthread_mutex_unlock(&mp_mutex_action);
215         return 0;
216 }
217
218 void __rte_experimental
219 rte_mp_action_unregister(const char *name)
220 {
221         struct action_entry *entry;
222
223         if (validate_action_name(name))
224                 return;
225
226         pthread_mutex_lock(&mp_mutex_action);
227         entry = find_action_entry_by_name(name);
228         if (entry == NULL) {
229                 pthread_mutex_unlock(&mp_mutex_action);
230                 return;
231         }
232         TAILQ_REMOVE(&action_entry_list, entry, next);
233         pthread_mutex_unlock(&mp_mutex_action);
234         free(entry);
235 }
236
237 static int
238 read_msg(struct mp_msg_internal *m, struct sockaddr_un *s)
239 {
240         int msglen;
241         struct iovec iov;
242         struct msghdr msgh;
243         char control[CMSG_SPACE(sizeof(m->msg.fds))];
244         struct cmsghdr *cmsg;
245         int buflen = sizeof(*m) - sizeof(m->msg.fds);
246
247         memset(&msgh, 0, sizeof(msgh));
248         iov.iov_base = m;
249         iov.iov_len  = buflen;
250
251         msgh.msg_name = s;
252         msgh.msg_namelen = sizeof(*s);
253         msgh.msg_iov = &iov;
254         msgh.msg_iovlen = 1;
255         msgh.msg_control = control;
256         msgh.msg_controllen = sizeof(control);
257
258         msglen = recvmsg(mp_fd, &msgh, 0);
259         if (msglen < 0) {
260                 RTE_LOG(ERR, EAL, "recvmsg failed, %s\n", strerror(errno));
261                 return -1;
262         }
263
264         if (msglen != buflen || (msgh.msg_flags & (MSG_TRUNC | MSG_CTRUNC))) {
265                 RTE_LOG(ERR, EAL, "truncted msg\n");
266                 return -1;
267         }
268
269         /* read auxiliary FDs if any */
270         for (cmsg = CMSG_FIRSTHDR(&msgh); cmsg != NULL;
271                 cmsg = CMSG_NXTHDR(&msgh, cmsg)) {
272                 if ((cmsg->cmsg_level == SOL_SOCKET) &&
273                         (cmsg->cmsg_type == SCM_RIGHTS)) {
274                         memcpy(m->msg.fds, CMSG_DATA(cmsg), sizeof(m->msg.fds));
275                         break;
276                 }
277         }
278
279         return 0;
280 }
281
282 static void
283 process_msg(struct mp_msg_internal *m, struct sockaddr_un *s)
284 {
285         struct pending_request *sync_req;
286         struct action_entry *entry;
287         struct rte_mp_msg *msg = &m->msg;
288         rte_mp_t action = NULL;
289
290         RTE_LOG(DEBUG, EAL, "msg: %s\n", msg->name);
291
292         if (m->type == MP_REP || m->type == MP_IGN) {
293                 pthread_mutex_lock(&pending_requests.lock);
294                 sync_req = find_sync_request(s->sun_path, msg->name);
295                 if (sync_req) {
296                         memcpy(sync_req->reply, msg, sizeof(*msg));
297                         /* -1 indicates that we've been asked to ignore */
298                         sync_req->reply_received = m->type == MP_REP ? 1 : -1;
299
300                         if (sync_req->type == REQUEST_TYPE_SYNC)
301                                 pthread_cond_signal(&sync_req->sync.cond);
302                         else if (sync_req->type == REQUEST_TYPE_ASYNC)
303                                 pthread_cond_signal(
304                                         &pending_requests.async_cond);
305                 } else
306                         RTE_LOG(ERR, EAL, "Drop mp reply: %s\n", msg->name);
307                 pthread_mutex_unlock(&pending_requests.lock);
308                 return;
309         }
310
311         pthread_mutex_lock(&mp_mutex_action);
312         entry = find_action_entry_by_name(msg->name);
313         if (entry != NULL)
314                 action = entry->action;
315         pthread_mutex_unlock(&mp_mutex_action);
316
317         if (!action) {
318                 if (m->type == MP_REQ && !internal_config.init_complete) {
319                         /* if this is a request, and init is not yet complete,
320                          * and callback wasn't registered, we should tell the
321                          * requester to ignore our existence because we're not
322                          * yet ready to process this request.
323                          */
324                         struct rte_mp_msg dummy;
325                         memset(&dummy, 0, sizeof(dummy));
326                         snprintf(dummy.name, sizeof(dummy.name),
327                                         "%s", msg->name);
328                         mp_send(&dummy, s->sun_path, MP_IGN);
329                 } else {
330                         RTE_LOG(ERR, EAL, "Cannot find action: %s\n",
331                                 msg->name);
332                 }
333         } else if (action(msg, s->sun_path) < 0) {
334                 RTE_LOG(ERR, EAL, "Fail to handle message: %s\n", msg->name);
335         }
336 }
337
338 static void *
339 mp_handle(void *arg __rte_unused)
340 {
341         struct mp_msg_internal msg;
342         struct sockaddr_un sa;
343
344         while (1) {
345                 if (read_msg(&msg, &sa) == 0)
346                         process_msg(&msg, &sa);
347         }
348
349         return NULL;
350 }
351
352 static int
353 timespec_cmp(const struct timespec *a, const struct timespec *b)
354 {
355         if (a->tv_sec < b->tv_sec)
356                 return -1;
357         if (a->tv_sec > b->tv_sec)
358                 return 1;
359         if (a->tv_nsec < b->tv_nsec)
360                 return -1;
361         if (a->tv_nsec > b->tv_nsec)
362                 return 1;
363         return 0;
364 }
365
366 enum async_action {
367         ACTION_NONE, /**< don't do anything */
368         ACTION_FREE, /**< free the action entry, but don't trigger callback */
369         ACTION_TRIGGER /**< trigger callback, then free action entry */
370 };
371
372 static enum async_action
373 process_async_request(struct pending_request *sr, const struct timespec *now)
374 {
375         struct async_request_param *param;
376         struct rte_mp_reply *reply;
377         bool timeout, received, last_msg;
378
379         param = sr->async.param;
380         reply = &param->user_reply;
381
382         /* did we timeout? */
383         timeout = timespec_cmp(&param->end, now) <= 0;
384
385         /* did we receive a response? */
386         received = sr->reply_received != 0;
387
388         /* if we didn't time out, and we didn't receive a response, ignore */
389         if (!timeout && !received)
390                 return ACTION_NONE;
391
392         /* if we received a response, adjust relevant data and copy mesasge. */
393         if (sr->reply_received == 1 && sr->reply) {
394                 struct rte_mp_msg *msg, *user_msgs, *tmp;
395
396                 msg = sr->reply;
397                 user_msgs = reply->msgs;
398
399                 tmp = realloc(user_msgs, sizeof(*msg) *
400                                 (reply->nb_received + 1));
401                 if (!tmp) {
402                         RTE_LOG(ERR, EAL, "Fail to alloc reply for request %s:%s\n",
403                                 sr->dst, sr->request->name);
404                         /* this entry is going to be removed and its message
405                          * dropped, but we don't want to leak memory, so
406                          * continue.
407                          */
408                 } else {
409                         user_msgs = tmp;
410                         reply->msgs = user_msgs;
411                         memcpy(&user_msgs[reply->nb_received],
412                                         msg, sizeof(*msg));
413                         reply->nb_received++;
414                 }
415
416                 /* mark this request as processed */
417                 param->n_responses_processed++;
418         } else if (sr->reply_received == -1) {
419                 /* we were asked to ignore this process */
420                 reply->nb_sent--;
421         }
422         free(sr->reply);
423
424         last_msg = param->n_responses_processed == reply->nb_sent;
425
426         return last_msg ? ACTION_TRIGGER : ACTION_FREE;
427 }
428
429 static void
430 trigger_async_action(struct pending_request *sr)
431 {
432         struct async_request_param *param;
433         struct rte_mp_reply *reply;
434
435         param = sr->async.param;
436         reply = &param->user_reply;
437
438         param->clb(sr->request, reply);
439
440         /* clean up */
441         free(sr->async.param->user_reply.msgs);
442         free(sr->async.param);
443         free(sr->request);
444 }
445
446 static struct pending_request *
447 check_trigger(struct timespec *ts)
448 {
449         struct pending_request *next, *cur, *trigger = NULL;
450
451         TAILQ_FOREACH_SAFE(cur, &pending_requests.requests, next, next) {
452                 enum async_action action;
453                 if (cur->type != REQUEST_TYPE_ASYNC)
454                         continue;
455
456                 action = process_async_request(cur, ts);
457                 if (action == ACTION_FREE) {
458                         TAILQ_REMOVE(&pending_requests.requests, cur, next);
459                         free(cur);
460                 } else if (action == ACTION_TRIGGER) {
461                         TAILQ_REMOVE(&pending_requests.requests, cur, next);
462                         trigger = cur;
463                         break;
464                 }
465         }
466         return trigger;
467 }
468
469 static void
470 wait_for_async_messages(void)
471 {
472         struct pending_request *sr;
473         struct timespec timeout;
474         bool timedwait = false;
475         bool nowait = false;
476         int ret;
477
478         /* scan through the list and see if there are any timeouts that
479          * are earlier than our current timeout.
480          */
481         TAILQ_FOREACH(sr, &pending_requests.requests, next) {
482                 if (sr->type != REQUEST_TYPE_ASYNC)
483                         continue;
484                 if (!timedwait || timespec_cmp(&sr->async.param->end,
485                                 &timeout) < 0) {
486                         memcpy(&timeout, &sr->async.param->end,
487                                 sizeof(timeout));
488                         timedwait = true;
489                 }
490
491                 /* sometimes, we don't even wait */
492                 if (sr->reply_received) {
493                         nowait = true;
494                         break;
495                 }
496         }
497
498         if (nowait)
499                 return;
500
501         do {
502                 ret = timedwait ?
503                         pthread_cond_timedwait(
504                                 &pending_requests.async_cond,
505                                 &pending_requests.lock,
506                                 &timeout) :
507                         pthread_cond_wait(
508                                 &pending_requests.async_cond,
509                                 &pending_requests.lock);
510         } while (ret != 0 && ret != ETIMEDOUT);
511
512         /* we've been woken up or timed out */
513 }
514
515 static void *
516 async_reply_handle(void *arg __rte_unused)
517 {
518         struct timeval now;
519         struct timespec ts_now;
520         while (1) {
521                 struct pending_request *trigger = NULL;
522
523                 pthread_mutex_lock(&pending_requests.lock);
524
525                 /* we exit this function holding the lock */
526                 wait_for_async_messages();
527
528                 if (gettimeofday(&now, NULL) < 0) {
529                         RTE_LOG(ERR, EAL, "Cannot get current time\n");
530                         break;
531                 }
532                 ts_now.tv_nsec = now.tv_usec * 1000;
533                 ts_now.tv_sec = now.tv_sec;
534
535                 do {
536                         trigger = check_trigger(&ts_now);
537                         /* unlock request list */
538                         pthread_mutex_unlock(&pending_requests.lock);
539
540                         if (trigger) {
541                                 trigger_async_action(trigger);
542                                 free(trigger);
543
544                                 /* we've triggered a callback, but there may be
545                                  * more, so lock the list and check again.
546                                  */
547                                 pthread_mutex_lock(&pending_requests.lock);
548                         }
549                 } while (trigger);
550         }
551
552         RTE_LOG(ERR, EAL, "ERROR: asynchronous requests disabled\n");
553
554         return NULL;
555 }
556
557 static int
558 open_socket_fd(void)
559 {
560         char peer_name[PATH_MAX] = {0};
561         struct sockaddr_un un;
562
563         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
564                 snprintf(peer_name, sizeof(peer_name),
565                                 "%d_%"PRIx64, getpid(), rte_rdtsc());
566
567         mp_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
568         if (mp_fd < 0) {
569                 RTE_LOG(ERR, EAL, "failed to create unix socket\n");
570                 return -1;
571         }
572
573         memset(&un, 0, sizeof(un));
574         un.sun_family = AF_UNIX;
575
576         create_socket_path(peer_name, un.sun_path, sizeof(un.sun_path));
577
578         unlink(un.sun_path); /* May still exist since last run */
579
580         if (bind(mp_fd, (struct sockaddr *)&un, sizeof(un)) < 0) {
581                 RTE_LOG(ERR, EAL, "failed to bind %s: %s\n",
582                         un.sun_path, strerror(errno));
583                 close(mp_fd);
584                 return -1;
585         }
586
587         RTE_LOG(INFO, EAL, "Multi-process socket %s\n", un.sun_path);
588         return mp_fd;
589 }
590
591 static int
592 unlink_sockets(const char *filter)
593 {
594         int dir_fd;
595         DIR *mp_dir;
596         struct dirent *ent;
597
598         mp_dir = opendir(mp_dir_path);
599         if (!mp_dir) {
600                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n", mp_dir_path);
601                 return -1;
602         }
603         dir_fd = dirfd(mp_dir);
604
605         while ((ent = readdir(mp_dir))) {
606                 if (fnmatch(filter, ent->d_name, 0) == 0)
607                         unlinkat(dir_fd, ent->d_name, 0);
608         }
609
610         closedir(mp_dir);
611         return 0;
612 }
613
614 int
615 rte_mp_channel_init(void)
616 {
617         char thread_name[RTE_MAX_THREAD_NAME_LEN];
618         char path[PATH_MAX];
619         int dir_fd;
620         pthread_t mp_handle_tid, async_reply_handle_tid;
621
622         /* create filter path */
623         create_socket_path("*", path, sizeof(path));
624         snprintf(mp_filter, sizeof(mp_filter), "%s", basename(path));
625
626         /* path may have been modified, so recreate it */
627         create_socket_path("*", path, sizeof(path));
628         snprintf(mp_dir_path, sizeof(mp_dir_path), "%s", dirname(path));
629
630         /* lock the directory */
631         dir_fd = open(mp_dir_path, O_RDONLY);
632         if (dir_fd < 0) {
633                 RTE_LOG(ERR, EAL, "failed to open %s: %s\n",
634                         mp_dir_path, strerror(errno));
635                 return -1;
636         }
637
638         if (flock(dir_fd, LOCK_EX)) {
639                 RTE_LOG(ERR, EAL, "failed to lock %s: %s\n",
640                         mp_dir_path, strerror(errno));
641                 close(dir_fd);
642                 return -1;
643         }
644
645         if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
646                         unlink_sockets(mp_filter)) {
647                 RTE_LOG(ERR, EAL, "failed to unlink mp sockets\n");
648                 close(dir_fd);
649                 return -1;
650         }
651
652         if (open_socket_fd() < 0) {
653                 close(dir_fd);
654                 return -1;
655         }
656
657         if (pthread_create(&mp_handle_tid, NULL, mp_handle, NULL) < 0) {
658                 RTE_LOG(ERR, EAL, "failed to create mp thead: %s\n",
659                         strerror(errno));
660                 close(mp_fd);
661                 mp_fd = -1;
662                 return -1;
663         }
664
665         if (pthread_create(&async_reply_handle_tid, NULL,
666                         async_reply_handle, NULL) < 0) {
667                 RTE_LOG(ERR, EAL, "failed to create mp thead: %s\n",
668                         strerror(errno));
669                 close(mp_fd);
670                 close(dir_fd);
671                 mp_fd = -1;
672                 return -1;
673         }
674
675         /* try best to set thread name */
676         snprintf(thread_name, RTE_MAX_THREAD_NAME_LEN, "rte_mp_handle");
677         rte_thread_setname(mp_handle_tid, thread_name);
678
679         /* try best to set thread name */
680         snprintf(thread_name, RTE_MAX_THREAD_NAME_LEN, "rte_mp_async_handle");
681         rte_thread_setname(async_reply_handle_tid, thread_name);
682
683         /* unlock the directory */
684         flock(dir_fd, LOCK_UN);
685         close(dir_fd);
686
687         return 0;
688 }
689
690 /**
691  * Return -1, as fail to send message and it's caused by the local side.
692  * Return 0, as fail to send message and it's caused by the remote side.
693  * Return 1, as succeed to send message.
694  *
695  */
696 static int
697 send_msg(const char *dst_path, struct rte_mp_msg *msg, int type)
698 {
699         int snd;
700         struct iovec iov;
701         struct msghdr msgh;
702         struct cmsghdr *cmsg;
703         struct sockaddr_un dst;
704         struct mp_msg_internal m;
705         int fd_size = msg->num_fds * sizeof(int);
706         char control[CMSG_SPACE(fd_size)];
707
708         m.type = type;
709         memcpy(&m.msg, msg, sizeof(*msg));
710
711         memset(&dst, 0, sizeof(dst));
712         dst.sun_family = AF_UNIX;
713         snprintf(dst.sun_path, sizeof(dst.sun_path), "%s", dst_path);
714
715         memset(&msgh, 0, sizeof(msgh));
716         memset(control, 0, sizeof(control));
717
718         iov.iov_base = &m;
719         iov.iov_len = sizeof(m) - sizeof(msg->fds);
720
721         msgh.msg_name = &dst;
722         msgh.msg_namelen = sizeof(dst);
723         msgh.msg_iov = &iov;
724         msgh.msg_iovlen = 1;
725         msgh.msg_control = control;
726         msgh.msg_controllen = sizeof(control);
727
728         cmsg = CMSG_FIRSTHDR(&msgh);
729         cmsg->cmsg_len = CMSG_LEN(fd_size);
730         cmsg->cmsg_level = SOL_SOCKET;
731         cmsg->cmsg_type = SCM_RIGHTS;
732         memcpy(CMSG_DATA(cmsg), msg->fds, fd_size);
733
734         do {
735                 snd = sendmsg(mp_fd, &msgh, 0);
736         } while (snd < 0 && errno == EINTR);
737
738         if (snd < 0) {
739                 rte_errno = errno;
740                 /* Check if it caused by peer process exits */
741                 if (errno == ECONNREFUSED &&
742                                 rte_eal_process_type() == RTE_PROC_PRIMARY) {
743                         unlink(dst_path);
744                         return 0;
745                 }
746                 if (errno == ENOBUFS) {
747                         RTE_LOG(ERR, EAL, "Peer cannot receive message %s\n",
748                                 dst_path);
749                         return 0;
750                 }
751                 RTE_LOG(ERR, EAL, "failed to send to (%s) due to %s\n",
752                         dst_path, strerror(errno));
753                 return -1;
754         }
755
756         return 1;
757 }
758
759 static int
760 mp_send(struct rte_mp_msg *msg, const char *peer, int type)
761 {
762         int dir_fd, ret = 0;
763         DIR *mp_dir;
764         struct dirent *ent;
765
766         if (!peer && (rte_eal_process_type() == RTE_PROC_SECONDARY))
767                 peer = eal_mp_socket_path();
768
769         if (peer) {
770                 if (send_msg(peer, msg, type) < 0)
771                         return -1;
772                 else
773                         return 0;
774         }
775
776         /* broadcast to all secondary processes */
777         mp_dir = opendir(mp_dir_path);
778         if (!mp_dir) {
779                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n",
780                                 mp_dir_path);
781                 rte_errno = errno;
782                 return -1;
783         }
784
785         dir_fd = dirfd(mp_dir);
786         /* lock the directory to prevent processes spinning up while we send */
787         if (flock(dir_fd, LOCK_EX)) {
788                 RTE_LOG(ERR, EAL, "Unable to lock directory %s\n",
789                         mp_dir_path);
790                 rte_errno = errno;
791                 closedir(mp_dir);
792                 return -1;
793         }
794
795         while ((ent = readdir(mp_dir))) {
796                 char path[PATH_MAX];
797
798                 if (fnmatch(mp_filter, ent->d_name, 0) != 0)
799                         continue;
800
801                 snprintf(path, sizeof(path), "%s/%s", mp_dir_path,
802                          ent->d_name);
803                 if (send_msg(path, msg, type) < 0)
804                         ret = -1;
805         }
806         /* unlock the dir */
807         flock(dir_fd, LOCK_UN);
808
809         /* dir_fd automatically closed on closedir */
810         closedir(mp_dir);
811         return ret;
812 }
813
814 static bool
815 check_input(const struct rte_mp_msg *msg)
816 {
817         if (msg == NULL) {
818                 RTE_LOG(ERR, EAL, "Msg cannot be NULL\n");
819                 rte_errno = EINVAL;
820                 return false;
821         }
822
823         if (validate_action_name(msg->name))
824                 return false;
825
826         if (msg->len_param > RTE_MP_MAX_PARAM_LEN) {
827                 RTE_LOG(ERR, EAL, "Message data is too long\n");
828                 rte_errno = E2BIG;
829                 return false;
830         }
831
832         if (msg->num_fds > RTE_MP_MAX_FD_NUM) {
833                 RTE_LOG(ERR, EAL, "Cannot send more than %d FDs\n",
834                         RTE_MP_MAX_FD_NUM);
835                 rte_errno = E2BIG;
836                 return false;
837         }
838
839         return true;
840 }
841
842 int __rte_experimental
843 rte_mp_sendmsg(struct rte_mp_msg *msg)
844 {
845         if (!check_input(msg))
846                 return -1;
847
848         RTE_LOG(DEBUG, EAL, "sendmsg: %s\n", msg->name);
849         return mp_send(msg, NULL, MP_MSG);
850 }
851
852 static int
853 mp_request_async(const char *dst, struct rte_mp_msg *req,
854                 struct async_request_param *param)
855 {
856         struct rte_mp_msg *reply_msg;
857         struct pending_request *sync_req, *exist;
858         int ret;
859
860         sync_req = malloc(sizeof(*sync_req));
861         reply_msg = malloc(sizeof(*reply_msg));
862         if (sync_req == NULL || reply_msg == NULL) {
863                 RTE_LOG(ERR, EAL, "Could not allocate space for sync request\n");
864                 rte_errno = ENOMEM;
865                 ret = -1;
866                 goto fail;
867         }
868
869         memset(sync_req, 0, sizeof(*sync_req));
870         memset(reply_msg, 0, sizeof(*reply_msg));
871
872         sync_req->type = REQUEST_TYPE_ASYNC;
873         strcpy(sync_req->dst, dst);
874         sync_req->request = req;
875         sync_req->reply = reply_msg;
876         sync_req->async.param = param;
877
878         /* queue already locked by caller */
879
880         exist = find_sync_request(dst, req->name);
881         if (exist) {
882                 RTE_LOG(ERR, EAL, "A pending request %s:%s\n", dst, req->name);
883                 rte_errno = EEXIST;
884                 ret = -1;
885                 goto fail;
886         }
887
888         ret = send_msg(dst, req, MP_REQ);
889         if (ret < 0) {
890                 RTE_LOG(ERR, EAL, "Fail to send request %s:%s\n",
891                         dst, req->name);
892                 ret = -1;
893                 goto fail;
894         } else if (ret == 0) {
895                 ret = 0;
896                 goto fail;
897         }
898         TAILQ_INSERT_TAIL(&pending_requests.requests, sync_req, next);
899
900         param->user_reply.nb_sent++;
901
902         return 0;
903 fail:
904         free(sync_req);
905         free(reply_msg);
906         return ret;
907 }
908
909 static int
910 mp_request_sync(const char *dst, struct rte_mp_msg *req,
911                struct rte_mp_reply *reply, const struct timespec *ts)
912 {
913         int ret;
914         struct rte_mp_msg msg, *tmp;
915         struct pending_request sync_req, *exist;
916
917         sync_req.type = REQUEST_TYPE_SYNC;
918         sync_req.reply_received = 0;
919         strcpy(sync_req.dst, dst);
920         sync_req.request = req;
921         sync_req.reply = &msg;
922         pthread_cond_init(&sync_req.sync.cond, NULL);
923
924         exist = find_sync_request(dst, req->name);
925         if (exist) {
926                 RTE_LOG(ERR, EAL, "A pending request %s:%s\n", dst, req->name);
927                 rte_errno = EEXIST;
928                 return -1;
929         }
930
931         ret = send_msg(dst, req, MP_REQ);
932         if (ret < 0) {
933                 RTE_LOG(ERR, EAL, "Fail to send request %s:%s\n",
934                         dst, req->name);
935                 return -1;
936         } else if (ret == 0)
937                 return 0;
938
939         TAILQ_INSERT_TAIL(&pending_requests.requests, &sync_req, next);
940
941         reply->nb_sent++;
942
943         do {
944                 ret = pthread_cond_timedwait(&sync_req.sync.cond,
945                                 &pending_requests.lock, ts);
946         } while (ret != 0 && ret != ETIMEDOUT);
947
948         TAILQ_REMOVE(&pending_requests.requests, &sync_req, next);
949
950         if (sync_req.reply_received == 0) {
951                 RTE_LOG(ERR, EAL, "Fail to recv reply for request %s:%s\n",
952                         dst, req->name);
953                 rte_errno = ETIMEDOUT;
954                 return -1;
955         }
956         if (sync_req.reply_received == -1) {
957                 RTE_LOG(DEBUG, EAL, "Asked to ignore response\n");
958                 /* not receiving this message is not an error, so decrement
959                  * number of sent messages
960                  */
961                 reply->nb_sent--;
962                 return 0;
963         }
964
965         tmp = realloc(reply->msgs, sizeof(msg) * (reply->nb_received + 1));
966         if (!tmp) {
967                 RTE_LOG(ERR, EAL, "Fail to alloc reply for request %s:%s\n",
968                         dst, req->name);
969                 rte_errno = ENOMEM;
970                 return -1;
971         }
972         memcpy(&tmp[reply->nb_received], &msg, sizeof(msg));
973         reply->msgs = tmp;
974         reply->nb_received++;
975         return 0;
976 }
977
978 int __rte_experimental
979 rte_mp_request_sync(struct rte_mp_msg *req, struct rte_mp_reply *reply,
980                 const struct timespec *ts)
981 {
982         int dir_fd, ret = 0;
983         DIR *mp_dir;
984         struct dirent *ent;
985         struct timeval now;
986         struct timespec end;
987
988         RTE_LOG(DEBUG, EAL, "request: %s\n", req->name);
989
990         if (check_input(req) == false)
991                 return -1;
992         if (gettimeofday(&now, NULL) < 0) {
993                 RTE_LOG(ERR, EAL, "Faile to get current time\n");
994                 rte_errno = errno;
995                 return -1;
996         }
997
998         end.tv_nsec = (now.tv_usec * 1000 + ts->tv_nsec) % 1000000000;
999         end.tv_sec = now.tv_sec + ts->tv_sec +
1000                         (now.tv_usec * 1000 + ts->tv_nsec) / 1000000000;
1001
1002         reply->nb_sent = 0;
1003         reply->nb_received = 0;
1004         reply->msgs = NULL;
1005
1006         /* for secondary process, send request to the primary process only */
1007         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1008                 pthread_mutex_lock(&pending_requests.lock);
1009                 ret = mp_request_sync(eal_mp_socket_path(), req, reply, &end);
1010                 pthread_mutex_unlock(&pending_requests.lock);
1011                 return ret;
1012         }
1013
1014         /* for primary process, broadcast request, and collect reply 1 by 1 */
1015         mp_dir = opendir(mp_dir_path);
1016         if (!mp_dir) {
1017                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n", mp_dir_path);
1018                 rte_errno = errno;
1019                 return -1;
1020         }
1021
1022         dir_fd = dirfd(mp_dir);
1023         /* lock the directory to prevent processes spinning up while we send */
1024         if (flock(dir_fd, LOCK_EX)) {
1025                 RTE_LOG(ERR, EAL, "Unable to lock directory %s\n",
1026                         mp_dir_path);
1027                 closedir(mp_dir);
1028                 rte_errno = errno;
1029                 return -1;
1030         }
1031
1032         pthread_mutex_lock(&pending_requests.lock);
1033         while ((ent = readdir(mp_dir))) {
1034                 char path[PATH_MAX];
1035
1036                 if (fnmatch(mp_filter, ent->d_name, 0) != 0)
1037                         continue;
1038
1039                 snprintf(path, sizeof(path), "%s/%s", mp_dir_path,
1040                          ent->d_name);
1041
1042                 /* unlocks the mutex while waiting for response,
1043                  * locks on receive
1044                  */
1045                 if (mp_request_sync(path, req, reply, &end))
1046                         ret = -1;
1047         }
1048         pthread_mutex_unlock(&pending_requests.lock);
1049         /* unlock the directory */
1050         flock(dir_fd, LOCK_UN);
1051
1052         /* dir_fd automatically closed on closedir */
1053         closedir(mp_dir);
1054         return ret;
1055 }
1056
1057 int __rte_experimental
1058 rte_mp_request_async(struct rte_mp_msg *req, const struct timespec *ts,
1059                 rte_mp_async_reply_t clb)
1060 {
1061         struct rte_mp_msg *copy;
1062         struct pending_request *dummy;
1063         struct async_request_param *param;
1064         struct rte_mp_reply *reply;
1065         int dir_fd, ret = 0;
1066         DIR *mp_dir;
1067         struct dirent *ent;
1068         struct timeval now;
1069         struct timespec *end;
1070         bool dummy_used = false;
1071
1072         RTE_LOG(DEBUG, EAL, "request: %s\n", req->name);
1073
1074         if (check_input(req) == false)
1075                 return -1;
1076         if (gettimeofday(&now, NULL) < 0) {
1077                 RTE_LOG(ERR, EAL, "Faile to get current time\n");
1078                 rte_errno = errno;
1079                 return -1;
1080         }
1081         copy = malloc(sizeof(*copy));
1082         dummy = malloc(sizeof(*dummy));
1083         param = malloc(sizeof(*param));
1084         if (copy == NULL || dummy == NULL || param == NULL) {
1085                 RTE_LOG(ERR, EAL, "Failed to allocate memory for async reply\n");
1086                 rte_errno = ENOMEM;
1087                 goto fail;
1088         }
1089
1090         memset(copy, 0, sizeof(*copy));
1091         memset(dummy, 0, sizeof(*dummy));
1092         memset(param, 0, sizeof(*param));
1093
1094         /* copy message */
1095         memcpy(copy, req, sizeof(*copy));
1096
1097         param->n_responses_processed = 0;
1098         param->clb = clb;
1099         end = &param->end;
1100         reply = &param->user_reply;
1101
1102         end->tv_nsec = (now.tv_usec * 1000 + ts->tv_nsec) % 1000000000;
1103         end->tv_sec = now.tv_sec + ts->tv_sec +
1104                         (now.tv_usec * 1000 + ts->tv_nsec) / 1000000000;
1105         reply->nb_sent = 0;
1106         reply->nb_received = 0;
1107         reply->msgs = NULL;
1108
1109         /* we have to lock the request queue here, as we will be adding a bunch
1110          * of requests to the queue at once, and some of the replies may arrive
1111          * before we add all of the requests to the queue.
1112          */
1113         pthread_mutex_lock(&pending_requests.lock);
1114
1115         /* we have to ensure that callback gets triggered even if we don't send
1116          * anything, therefore earlier we have allocated a dummy request. fill
1117          * it, and put it on the queue if we don't send any requests.
1118          */
1119         dummy->type = REQUEST_TYPE_ASYNC;
1120         dummy->request = copy;
1121         dummy->reply = NULL;
1122         dummy->async.param = param;
1123         dummy->reply_received = 1; /* short-circuit the timeout */
1124
1125         /* for secondary process, send request to the primary process only */
1126         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1127                 ret = mp_request_async(eal_mp_socket_path(), copy, param);
1128
1129                 /* if we didn't send anything, put dummy request on the queue */
1130                 if (ret == 0 && reply->nb_sent == 0) {
1131                         TAILQ_INSERT_TAIL(&pending_requests.requests, dummy,
1132                                         next);
1133                         dummy_used = true;
1134                 }
1135
1136                 pthread_mutex_unlock(&pending_requests.lock);
1137
1138                 /* if we couldn't send anything, clean up */
1139                 if (ret != 0)
1140                         goto fail;
1141                 return 0;
1142         }
1143
1144         /* for primary process, broadcast request */
1145         mp_dir = opendir(mp_dir_path);
1146         if (!mp_dir) {
1147                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n", mp_dir_path);
1148                 rte_errno = errno;
1149                 goto unlock_fail;
1150         }
1151         dir_fd = dirfd(mp_dir);
1152
1153         /* lock the directory to prevent processes spinning up while we send */
1154         if (flock(dir_fd, LOCK_EX)) {
1155                 RTE_LOG(ERR, EAL, "Unable to lock directory %s\n",
1156                         mp_dir_path);
1157                 rte_errno = errno;
1158                 goto closedir_fail;
1159         }
1160
1161         while ((ent = readdir(mp_dir))) {
1162                 char path[PATH_MAX];
1163
1164                 if (fnmatch(mp_filter, ent->d_name, 0) != 0)
1165                         continue;
1166
1167                 snprintf(path, sizeof(path), "%s/%s", mp_dir_path,
1168                          ent->d_name);
1169
1170                 if (mp_request_async(path, copy, param))
1171                         ret = -1;
1172         }
1173         /* if we didn't send anything, put dummy request on the queue */
1174         if (ret == 0 && reply->nb_sent == 0) {
1175                 TAILQ_INSERT_HEAD(&pending_requests.requests, dummy, next);
1176                 dummy_used = true;
1177         }
1178
1179         /* trigger async request thread wake up */
1180         pthread_cond_signal(&pending_requests.async_cond);
1181
1182         /* finally, unlock the queue */
1183         pthread_mutex_unlock(&pending_requests.lock);
1184
1185         /* unlock the directory */
1186         flock(dir_fd, LOCK_UN);
1187
1188         /* dir_fd automatically closed on closedir */
1189         closedir(mp_dir);
1190
1191         /* if dummy was unused, free it */
1192         if (!dummy_used)
1193                 free(dummy);
1194
1195         return ret;
1196 closedir_fail:
1197         closedir(mp_dir);
1198 unlock_fail:
1199         pthread_mutex_unlock(&pending_requests.lock);
1200 fail:
1201         free(dummy);
1202         free(param);
1203         free(copy);
1204         return -1;
1205 }
1206
1207 int __rte_experimental
1208 rte_mp_reply(struct rte_mp_msg *msg, const char *peer)
1209 {
1210         RTE_LOG(DEBUG, EAL, "reply: %s\n", msg->name);
1211
1212         if (check_input(msg) == false)
1213                 return -1;
1214
1215         if (peer == NULL) {
1216                 RTE_LOG(ERR, EAL, "peer is not specified\n");
1217                 rte_errno = EINVAL;
1218                 return -1;
1219         }
1220
1221         return mp_send(msg, peer, MP_REP);
1222 }