ipc: use strlcpy where applicable
[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                 strlcpy(buf, prefix, len);
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         strlcpy(entry->action_name, name, sizeof(entry->action_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                         strlcpy(dummy.name, msg->name, sizeof(dummy.name));
327                         mp_send(&dummy, s->sun_path, MP_IGN);
328                 } else {
329                         RTE_LOG(ERR, EAL, "Cannot find action: %s\n",
330                                 msg->name);
331                 }
332         } else if (action(msg, s->sun_path) < 0) {
333                 RTE_LOG(ERR, EAL, "Fail to handle message: %s\n", msg->name);
334         }
335 }
336
337 static void *
338 mp_handle(void *arg __rte_unused)
339 {
340         struct mp_msg_internal msg;
341         struct sockaddr_un sa;
342
343         while (1) {
344                 if (read_msg(&msg, &sa) == 0)
345                         process_msg(&msg, &sa);
346         }
347
348         return NULL;
349 }
350
351 static int
352 timespec_cmp(const struct timespec *a, const struct timespec *b)
353 {
354         if (a->tv_sec < b->tv_sec)
355                 return -1;
356         if (a->tv_sec > b->tv_sec)
357                 return 1;
358         if (a->tv_nsec < b->tv_nsec)
359                 return -1;
360         if (a->tv_nsec > b->tv_nsec)
361                 return 1;
362         return 0;
363 }
364
365 enum async_action {
366         ACTION_NONE, /**< don't do anything */
367         ACTION_FREE, /**< free the action entry, but don't trigger callback */
368         ACTION_TRIGGER /**< trigger callback, then free action entry */
369 };
370
371 static enum async_action
372 process_async_request(struct pending_request *sr, const struct timespec *now)
373 {
374         struct async_request_param *param;
375         struct rte_mp_reply *reply;
376         bool timeout, received, last_msg;
377
378         param = sr->async.param;
379         reply = &param->user_reply;
380
381         /* did we timeout? */
382         timeout = timespec_cmp(&param->end, now) <= 0;
383
384         /* did we receive a response? */
385         received = sr->reply_received != 0;
386
387         /* if we didn't time out, and we didn't receive a response, ignore */
388         if (!timeout && !received)
389                 return ACTION_NONE;
390
391         /* if we received a response, adjust relevant data and copy mesasge. */
392         if (sr->reply_received == 1 && sr->reply) {
393                 struct rte_mp_msg *msg, *user_msgs, *tmp;
394
395                 msg = sr->reply;
396                 user_msgs = reply->msgs;
397
398                 tmp = realloc(user_msgs, sizeof(*msg) *
399                                 (reply->nb_received + 1));
400                 if (!tmp) {
401                         RTE_LOG(ERR, EAL, "Fail to alloc reply for request %s:%s\n",
402                                 sr->dst, sr->request->name);
403                         /* this entry is going to be removed and its message
404                          * dropped, but we don't want to leak memory, so
405                          * continue.
406                          */
407                 } else {
408                         user_msgs = tmp;
409                         reply->msgs = user_msgs;
410                         memcpy(&user_msgs[reply->nb_received],
411                                         msg, sizeof(*msg));
412                         reply->nb_received++;
413                 }
414
415                 /* mark this request as processed */
416                 param->n_responses_processed++;
417         } else if (sr->reply_received == -1) {
418                 /* we were asked to ignore this process */
419                 reply->nb_sent--;
420         }
421         free(sr->reply);
422
423         last_msg = param->n_responses_processed == reply->nb_sent;
424
425         return last_msg ? ACTION_TRIGGER : ACTION_FREE;
426 }
427
428 static void
429 trigger_async_action(struct pending_request *sr)
430 {
431         struct async_request_param *param;
432         struct rte_mp_reply *reply;
433
434         param = sr->async.param;
435         reply = &param->user_reply;
436
437         param->clb(sr->request, reply);
438
439         /* clean up */
440         free(sr->async.param->user_reply.msgs);
441         free(sr->async.param);
442         free(sr->request);
443 }
444
445 static struct pending_request *
446 check_trigger(struct timespec *ts)
447 {
448         struct pending_request *next, *cur, *trigger = NULL;
449
450         TAILQ_FOREACH_SAFE(cur, &pending_requests.requests, next, next) {
451                 enum async_action action;
452                 if (cur->type != REQUEST_TYPE_ASYNC)
453                         continue;
454
455                 action = process_async_request(cur, ts);
456                 if (action == ACTION_FREE) {
457                         TAILQ_REMOVE(&pending_requests.requests, cur, next);
458                         free(cur);
459                 } else if (action == ACTION_TRIGGER) {
460                         TAILQ_REMOVE(&pending_requests.requests, cur, next);
461                         trigger = cur;
462                         break;
463                 }
464         }
465         return trigger;
466 }
467
468 static void
469 wait_for_async_messages(void)
470 {
471         struct pending_request *sr;
472         struct timespec timeout;
473         bool timedwait = false;
474         bool nowait = false;
475         int ret;
476
477         /* scan through the list and see if there are any timeouts that
478          * are earlier than our current timeout.
479          */
480         TAILQ_FOREACH(sr, &pending_requests.requests, next) {
481                 if (sr->type != REQUEST_TYPE_ASYNC)
482                         continue;
483                 if (!timedwait || timespec_cmp(&sr->async.param->end,
484                                 &timeout) < 0) {
485                         memcpy(&timeout, &sr->async.param->end,
486                                 sizeof(timeout));
487                         timedwait = true;
488                 }
489
490                 /* sometimes, we don't even wait */
491                 if (sr->reply_received) {
492                         nowait = true;
493                         break;
494                 }
495         }
496
497         if (nowait)
498                 return;
499
500         do {
501                 ret = timedwait ?
502                         pthread_cond_timedwait(
503                                 &pending_requests.async_cond,
504                                 &pending_requests.lock,
505                                 &timeout) :
506                         pthread_cond_wait(
507                                 &pending_requests.async_cond,
508                                 &pending_requests.lock);
509         } while (ret != 0 && ret != ETIMEDOUT);
510
511         /* we've been woken up or timed out */
512 }
513
514 static void *
515 async_reply_handle(void *arg __rte_unused)
516 {
517         struct timeval now;
518         struct timespec ts_now;
519         while (1) {
520                 struct pending_request *trigger = NULL;
521
522                 pthread_mutex_lock(&pending_requests.lock);
523
524                 /* we exit this function holding the lock */
525                 wait_for_async_messages();
526
527                 if (gettimeofday(&now, NULL) < 0) {
528                         RTE_LOG(ERR, EAL, "Cannot get current time\n");
529                         break;
530                 }
531                 ts_now.tv_nsec = now.tv_usec * 1000;
532                 ts_now.tv_sec = now.tv_sec;
533
534                 do {
535                         trigger = check_trigger(&ts_now);
536                         /* unlock request list */
537                         pthread_mutex_unlock(&pending_requests.lock);
538
539                         if (trigger) {
540                                 trigger_async_action(trigger);
541                                 free(trigger);
542
543                                 /* we've triggered a callback, but there may be
544                                  * more, so lock the list and check again.
545                                  */
546                                 pthread_mutex_lock(&pending_requests.lock);
547                         }
548                 } while (trigger);
549         }
550
551         RTE_LOG(ERR, EAL, "ERROR: asynchronous requests disabled\n");
552
553         return NULL;
554 }
555
556 static int
557 open_socket_fd(void)
558 {
559         char peer_name[PATH_MAX] = {0};
560         struct sockaddr_un un;
561
562         if (rte_eal_process_type() == RTE_PROC_SECONDARY)
563                 snprintf(peer_name, sizeof(peer_name),
564                                 "%d_%"PRIx64, getpid(), rte_rdtsc());
565
566         mp_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
567         if (mp_fd < 0) {
568                 RTE_LOG(ERR, EAL, "failed to create unix socket\n");
569                 return -1;
570         }
571
572         memset(&un, 0, sizeof(un));
573         un.sun_family = AF_UNIX;
574
575         create_socket_path(peer_name, un.sun_path, sizeof(un.sun_path));
576
577         unlink(un.sun_path); /* May still exist since last run */
578
579         if (bind(mp_fd, (struct sockaddr *)&un, sizeof(un)) < 0) {
580                 RTE_LOG(ERR, EAL, "failed to bind %s: %s\n",
581                         un.sun_path, strerror(errno));
582                 close(mp_fd);
583                 return -1;
584         }
585
586         RTE_LOG(INFO, EAL, "Multi-process socket %s\n", un.sun_path);
587         return mp_fd;
588 }
589
590 static int
591 unlink_sockets(const char *filter)
592 {
593         int dir_fd;
594         DIR *mp_dir;
595         struct dirent *ent;
596
597         mp_dir = opendir(mp_dir_path);
598         if (!mp_dir) {
599                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n", mp_dir_path);
600                 return -1;
601         }
602         dir_fd = dirfd(mp_dir);
603
604         while ((ent = readdir(mp_dir))) {
605                 if (fnmatch(filter, ent->d_name, 0) == 0)
606                         unlinkat(dir_fd, ent->d_name, 0);
607         }
608
609         closedir(mp_dir);
610         return 0;
611 }
612
613 int
614 rte_mp_channel_init(void)
615 {
616         char thread_name[RTE_MAX_THREAD_NAME_LEN];
617         char path[PATH_MAX];
618         int dir_fd;
619         pthread_t mp_handle_tid, async_reply_handle_tid;
620
621         /* create filter path */
622         create_socket_path("*", path, sizeof(path));
623         strlcpy(mp_filter, basename(path), sizeof(mp_filter));
624
625         /* path may have been modified, so recreate it */
626         create_socket_path("*", path, sizeof(path));
627         strlcpy(mp_dir_path, dirname(path), sizeof(mp_dir_path));
628
629         /* lock the directory */
630         dir_fd = open(mp_dir_path, O_RDONLY);
631         if (dir_fd < 0) {
632                 RTE_LOG(ERR, EAL, "failed to open %s: %s\n",
633                         mp_dir_path, strerror(errno));
634                 return -1;
635         }
636
637         if (flock(dir_fd, LOCK_EX)) {
638                 RTE_LOG(ERR, EAL, "failed to lock %s: %s\n",
639                         mp_dir_path, strerror(errno));
640                 close(dir_fd);
641                 return -1;
642         }
643
644         if (rte_eal_process_type() == RTE_PROC_PRIMARY &&
645                         unlink_sockets(mp_filter)) {
646                 RTE_LOG(ERR, EAL, "failed to unlink mp sockets\n");
647                 close(dir_fd);
648                 return -1;
649         }
650
651         if (open_socket_fd() < 0) {
652                 close(dir_fd);
653                 return -1;
654         }
655
656         if (pthread_create(&mp_handle_tid, NULL, mp_handle, NULL) < 0) {
657                 RTE_LOG(ERR, EAL, "failed to create mp thead: %s\n",
658                         strerror(errno));
659                 close(mp_fd);
660                 mp_fd = -1;
661                 return -1;
662         }
663
664         if (pthread_create(&async_reply_handle_tid, NULL,
665                         async_reply_handle, NULL) < 0) {
666                 RTE_LOG(ERR, EAL, "failed to create mp thead: %s\n",
667                         strerror(errno));
668                 close(mp_fd);
669                 close(dir_fd);
670                 mp_fd = -1;
671                 return -1;
672         }
673
674         /* try best to set thread name */
675         strlcpy(thread_name, "rte_mp_handle", RTE_MAX_THREAD_NAME_LEN);
676         rte_thread_setname(mp_handle_tid, thread_name);
677
678         /* try best to set thread name */
679         strlcpy(thread_name, "rte_mp_async_handle", RTE_MAX_THREAD_NAME_LEN);
680         rte_thread_setname(async_reply_handle_tid, thread_name);
681
682         /* unlock the directory */
683         flock(dir_fd, LOCK_UN);
684         close(dir_fd);
685
686         return 0;
687 }
688
689 /**
690  * Return -1, as fail to send message and it's caused by the local side.
691  * Return 0, as fail to send message and it's caused by the remote side.
692  * Return 1, as succeed to send message.
693  *
694  */
695 static int
696 send_msg(const char *dst_path, struct rte_mp_msg *msg, int type)
697 {
698         int snd;
699         struct iovec iov;
700         struct msghdr msgh;
701         struct cmsghdr *cmsg;
702         struct sockaddr_un dst;
703         struct mp_msg_internal m;
704         int fd_size = msg->num_fds * sizeof(int);
705         char control[CMSG_SPACE(fd_size)];
706
707         m.type = type;
708         memcpy(&m.msg, msg, sizeof(*msg));
709
710         memset(&dst, 0, sizeof(dst));
711         dst.sun_family = AF_UNIX;
712         strlcpy(dst.sun_path, dst_path, sizeof(dst.sun_path));
713
714         memset(&msgh, 0, sizeof(msgh));
715         memset(control, 0, sizeof(control));
716
717         iov.iov_base = &m;
718         iov.iov_len = sizeof(m) - sizeof(msg->fds);
719
720         msgh.msg_name = &dst;
721         msgh.msg_namelen = sizeof(dst);
722         msgh.msg_iov = &iov;
723         msgh.msg_iovlen = 1;
724         msgh.msg_control = control;
725         msgh.msg_controllen = sizeof(control);
726
727         cmsg = CMSG_FIRSTHDR(&msgh);
728         cmsg->cmsg_len = CMSG_LEN(fd_size);
729         cmsg->cmsg_level = SOL_SOCKET;
730         cmsg->cmsg_type = SCM_RIGHTS;
731         memcpy(CMSG_DATA(cmsg), msg->fds, fd_size);
732
733         do {
734                 snd = sendmsg(mp_fd, &msgh, 0);
735         } while (snd < 0 && errno == EINTR);
736
737         if (snd < 0) {
738                 rte_errno = errno;
739                 /* Check if it caused by peer process exits */
740                 if (errno == ECONNREFUSED &&
741                                 rte_eal_process_type() == RTE_PROC_PRIMARY) {
742                         unlink(dst_path);
743                         return 0;
744                 }
745                 if (errno == ENOBUFS) {
746                         RTE_LOG(ERR, EAL, "Peer cannot receive message %s\n",
747                                 dst_path);
748                         return 0;
749                 }
750                 RTE_LOG(ERR, EAL, "failed to send to (%s) due to %s\n",
751                         dst_path, strerror(errno));
752                 return -1;
753         }
754
755         return 1;
756 }
757
758 static int
759 mp_send(struct rte_mp_msg *msg, const char *peer, int type)
760 {
761         int dir_fd, ret = 0;
762         DIR *mp_dir;
763         struct dirent *ent;
764
765         if (!peer && (rte_eal_process_type() == RTE_PROC_SECONDARY))
766                 peer = eal_mp_socket_path();
767
768         if (peer) {
769                 if (send_msg(peer, msg, type) < 0)
770                         return -1;
771                 else
772                         return 0;
773         }
774
775         /* broadcast to all secondary processes */
776         mp_dir = opendir(mp_dir_path);
777         if (!mp_dir) {
778                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n",
779                                 mp_dir_path);
780                 rte_errno = errno;
781                 return -1;
782         }
783
784         dir_fd = dirfd(mp_dir);
785         /* lock the directory to prevent processes spinning up while we send */
786         if (flock(dir_fd, LOCK_EX)) {
787                 RTE_LOG(ERR, EAL, "Unable to lock directory %s\n",
788                         mp_dir_path);
789                 rte_errno = errno;
790                 closedir(mp_dir);
791                 return -1;
792         }
793
794         while ((ent = readdir(mp_dir))) {
795                 char path[PATH_MAX];
796
797                 if (fnmatch(mp_filter, ent->d_name, 0) != 0)
798                         continue;
799
800                 snprintf(path, sizeof(path), "%s/%s", mp_dir_path,
801                          ent->d_name);
802                 if (send_msg(path, msg, type) < 0)
803                         ret = -1;
804         }
805         /* unlock the dir */
806         flock(dir_fd, LOCK_UN);
807
808         /* dir_fd automatically closed on closedir */
809         closedir(mp_dir);
810         return ret;
811 }
812
813 static bool
814 check_input(const struct rte_mp_msg *msg)
815 {
816         if (msg == NULL) {
817                 RTE_LOG(ERR, EAL, "Msg cannot be NULL\n");
818                 rte_errno = EINVAL;
819                 return false;
820         }
821
822         if (validate_action_name(msg->name))
823                 return false;
824
825         if (msg->len_param > RTE_MP_MAX_PARAM_LEN) {
826                 RTE_LOG(ERR, EAL, "Message data is too long\n");
827                 rte_errno = E2BIG;
828                 return false;
829         }
830
831         if (msg->num_fds > RTE_MP_MAX_FD_NUM) {
832                 RTE_LOG(ERR, EAL, "Cannot send more than %d FDs\n",
833                         RTE_MP_MAX_FD_NUM);
834                 rte_errno = E2BIG;
835                 return false;
836         }
837
838         return true;
839 }
840
841 int __rte_experimental
842 rte_mp_sendmsg(struct rte_mp_msg *msg)
843 {
844         if (!check_input(msg))
845                 return -1;
846
847         RTE_LOG(DEBUG, EAL, "sendmsg: %s\n", msg->name);
848         return mp_send(msg, NULL, MP_MSG);
849 }
850
851 static int
852 mp_request_async(const char *dst, struct rte_mp_msg *req,
853                 struct async_request_param *param)
854 {
855         struct rte_mp_msg *reply_msg;
856         struct pending_request *sync_req, *exist;
857         int ret;
858
859         sync_req = malloc(sizeof(*sync_req));
860         reply_msg = malloc(sizeof(*reply_msg));
861         if (sync_req == NULL || reply_msg == NULL) {
862                 RTE_LOG(ERR, EAL, "Could not allocate space for sync request\n");
863                 rte_errno = ENOMEM;
864                 ret = -1;
865                 goto fail;
866         }
867
868         memset(sync_req, 0, sizeof(*sync_req));
869         memset(reply_msg, 0, sizeof(*reply_msg));
870
871         sync_req->type = REQUEST_TYPE_ASYNC;
872         strlcpy(sync_req->dst, dst, sizeof(sync_req->dst));
873         sync_req->request = req;
874         sync_req->reply = reply_msg;
875         sync_req->async.param = param;
876
877         /* queue already locked by caller */
878
879         exist = find_sync_request(dst, req->name);
880         if (exist) {
881                 RTE_LOG(ERR, EAL, "A pending request %s:%s\n", dst, req->name);
882                 rte_errno = EEXIST;
883                 ret = -1;
884                 goto fail;
885         }
886
887         ret = send_msg(dst, req, MP_REQ);
888         if (ret < 0) {
889                 RTE_LOG(ERR, EAL, "Fail to send request %s:%s\n",
890                         dst, req->name);
891                 ret = -1;
892                 goto fail;
893         } else if (ret == 0) {
894                 ret = 0;
895                 goto fail;
896         }
897         TAILQ_INSERT_TAIL(&pending_requests.requests, sync_req, next);
898
899         param->user_reply.nb_sent++;
900
901         return 0;
902 fail:
903         free(sync_req);
904         free(reply_msg);
905         return ret;
906 }
907
908 static int
909 mp_request_sync(const char *dst, struct rte_mp_msg *req,
910                struct rte_mp_reply *reply, const struct timespec *ts)
911 {
912         int ret;
913         struct rte_mp_msg msg, *tmp;
914         struct pending_request sync_req, *exist;
915
916         sync_req.type = REQUEST_TYPE_SYNC;
917         sync_req.reply_received = 0;
918         strlcpy(sync_req.dst, dst, sizeof(sync_req.dst));
919         sync_req.request = req;
920         sync_req.reply = &msg;
921         pthread_cond_init(&sync_req.sync.cond, NULL);
922
923         exist = find_sync_request(dst, req->name);
924         if (exist) {
925                 RTE_LOG(ERR, EAL, "A pending request %s:%s\n", dst, req->name);
926                 rte_errno = EEXIST;
927                 return -1;
928         }
929
930         ret = send_msg(dst, req, MP_REQ);
931         if (ret < 0) {
932                 RTE_LOG(ERR, EAL, "Fail to send request %s:%s\n",
933                         dst, req->name);
934                 return -1;
935         } else if (ret == 0)
936                 return 0;
937
938         TAILQ_INSERT_TAIL(&pending_requests.requests, &sync_req, next);
939
940         reply->nb_sent++;
941
942         do {
943                 ret = pthread_cond_timedwait(&sync_req.sync.cond,
944                                 &pending_requests.lock, ts);
945         } while (ret != 0 && ret != ETIMEDOUT);
946
947         TAILQ_REMOVE(&pending_requests.requests, &sync_req, next);
948
949         if (sync_req.reply_received == 0) {
950                 RTE_LOG(ERR, EAL, "Fail to recv reply for request %s:%s\n",
951                         dst, req->name);
952                 rte_errno = ETIMEDOUT;
953                 return -1;
954         }
955         if (sync_req.reply_received == -1) {
956                 RTE_LOG(DEBUG, EAL, "Asked to ignore response\n");
957                 /* not receiving this message is not an error, so decrement
958                  * number of sent messages
959                  */
960                 reply->nb_sent--;
961                 return 0;
962         }
963
964         tmp = realloc(reply->msgs, sizeof(msg) * (reply->nb_received + 1));
965         if (!tmp) {
966                 RTE_LOG(ERR, EAL, "Fail to alloc reply for request %s:%s\n",
967                         dst, req->name);
968                 rte_errno = ENOMEM;
969                 return -1;
970         }
971         memcpy(&tmp[reply->nb_received], &msg, sizeof(msg));
972         reply->msgs = tmp;
973         reply->nb_received++;
974         return 0;
975 }
976
977 int __rte_experimental
978 rte_mp_request_sync(struct rte_mp_msg *req, struct rte_mp_reply *reply,
979                 const struct timespec *ts)
980 {
981         int dir_fd, ret = 0;
982         DIR *mp_dir;
983         struct dirent *ent;
984         struct timeval now;
985         struct timespec end;
986
987         RTE_LOG(DEBUG, EAL, "request: %s\n", req->name);
988
989         if (check_input(req) == false)
990                 return -1;
991         if (gettimeofday(&now, NULL) < 0) {
992                 RTE_LOG(ERR, EAL, "Faile to get current time\n");
993                 rte_errno = errno;
994                 return -1;
995         }
996
997         end.tv_nsec = (now.tv_usec * 1000 + ts->tv_nsec) % 1000000000;
998         end.tv_sec = now.tv_sec + ts->tv_sec +
999                         (now.tv_usec * 1000 + ts->tv_nsec) / 1000000000;
1000
1001         reply->nb_sent = 0;
1002         reply->nb_received = 0;
1003         reply->msgs = NULL;
1004
1005         /* for secondary process, send request to the primary process only */
1006         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1007                 pthread_mutex_lock(&pending_requests.lock);
1008                 ret = mp_request_sync(eal_mp_socket_path(), req, reply, &end);
1009                 pthread_mutex_unlock(&pending_requests.lock);
1010                 return ret;
1011         }
1012
1013         /* for primary process, broadcast request, and collect reply 1 by 1 */
1014         mp_dir = opendir(mp_dir_path);
1015         if (!mp_dir) {
1016                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n", mp_dir_path);
1017                 rte_errno = errno;
1018                 return -1;
1019         }
1020
1021         dir_fd = dirfd(mp_dir);
1022         /* lock the directory to prevent processes spinning up while we send */
1023         if (flock(dir_fd, LOCK_EX)) {
1024                 RTE_LOG(ERR, EAL, "Unable to lock directory %s\n",
1025                         mp_dir_path);
1026                 closedir(mp_dir);
1027                 rte_errno = errno;
1028                 return -1;
1029         }
1030
1031         pthread_mutex_lock(&pending_requests.lock);
1032         while ((ent = readdir(mp_dir))) {
1033                 char path[PATH_MAX];
1034
1035                 if (fnmatch(mp_filter, ent->d_name, 0) != 0)
1036                         continue;
1037
1038                 snprintf(path, sizeof(path), "%s/%s", mp_dir_path,
1039                          ent->d_name);
1040
1041                 /* unlocks the mutex while waiting for response,
1042                  * locks on receive
1043                  */
1044                 if (mp_request_sync(path, req, reply, &end))
1045                         ret = -1;
1046         }
1047         pthread_mutex_unlock(&pending_requests.lock);
1048         /* unlock the directory */
1049         flock(dir_fd, LOCK_UN);
1050
1051         /* dir_fd automatically closed on closedir */
1052         closedir(mp_dir);
1053         return ret;
1054 }
1055
1056 int __rte_experimental
1057 rte_mp_request_async(struct rte_mp_msg *req, const struct timespec *ts,
1058                 rte_mp_async_reply_t clb)
1059 {
1060         struct rte_mp_msg *copy;
1061         struct pending_request *dummy;
1062         struct async_request_param *param;
1063         struct rte_mp_reply *reply;
1064         int dir_fd, ret = 0;
1065         DIR *mp_dir;
1066         struct dirent *ent;
1067         struct timeval now;
1068         struct timespec *end;
1069         bool dummy_used = false;
1070
1071         RTE_LOG(DEBUG, EAL, "request: %s\n", req->name);
1072
1073         if (check_input(req) == false)
1074                 return -1;
1075         if (gettimeofday(&now, NULL) < 0) {
1076                 RTE_LOG(ERR, EAL, "Faile to get current time\n");
1077                 rte_errno = errno;
1078                 return -1;
1079         }
1080         copy = malloc(sizeof(*copy));
1081         dummy = malloc(sizeof(*dummy));
1082         param = malloc(sizeof(*param));
1083         if (copy == NULL || dummy == NULL || param == NULL) {
1084                 RTE_LOG(ERR, EAL, "Failed to allocate memory for async reply\n");
1085                 rte_errno = ENOMEM;
1086                 goto fail;
1087         }
1088
1089         memset(copy, 0, sizeof(*copy));
1090         memset(dummy, 0, sizeof(*dummy));
1091         memset(param, 0, sizeof(*param));
1092
1093         /* copy message */
1094         memcpy(copy, req, sizeof(*copy));
1095
1096         param->n_responses_processed = 0;
1097         param->clb = clb;
1098         end = &param->end;
1099         reply = &param->user_reply;
1100
1101         end->tv_nsec = (now.tv_usec * 1000 + ts->tv_nsec) % 1000000000;
1102         end->tv_sec = now.tv_sec + ts->tv_sec +
1103                         (now.tv_usec * 1000 + ts->tv_nsec) / 1000000000;
1104         reply->nb_sent = 0;
1105         reply->nb_received = 0;
1106         reply->msgs = NULL;
1107
1108         /* we have to lock the request queue here, as we will be adding a bunch
1109          * of requests to the queue at once, and some of the replies may arrive
1110          * before we add all of the requests to the queue.
1111          */
1112         pthread_mutex_lock(&pending_requests.lock);
1113
1114         /* we have to ensure that callback gets triggered even if we don't send
1115          * anything, therefore earlier we have allocated a dummy request. fill
1116          * it, and put it on the queue if we don't send any requests.
1117          */
1118         dummy->type = REQUEST_TYPE_ASYNC;
1119         dummy->request = copy;
1120         dummy->reply = NULL;
1121         dummy->async.param = param;
1122         dummy->reply_received = 1; /* short-circuit the timeout */
1123
1124         /* for secondary process, send request to the primary process only */
1125         if (rte_eal_process_type() == RTE_PROC_SECONDARY) {
1126                 ret = mp_request_async(eal_mp_socket_path(), copy, param);
1127
1128                 /* if we didn't send anything, put dummy request on the queue */
1129                 if (ret == 0 && reply->nb_sent == 0) {
1130                         TAILQ_INSERT_TAIL(&pending_requests.requests, dummy,
1131                                         next);
1132                         dummy_used = true;
1133                 }
1134
1135                 pthread_mutex_unlock(&pending_requests.lock);
1136
1137                 /* if we couldn't send anything, clean up */
1138                 if (ret != 0)
1139                         goto fail;
1140                 return 0;
1141         }
1142
1143         /* for primary process, broadcast request */
1144         mp_dir = opendir(mp_dir_path);
1145         if (!mp_dir) {
1146                 RTE_LOG(ERR, EAL, "Unable to open directory %s\n", mp_dir_path);
1147                 rte_errno = errno;
1148                 goto unlock_fail;
1149         }
1150         dir_fd = dirfd(mp_dir);
1151
1152         /* lock the directory to prevent processes spinning up while we send */
1153         if (flock(dir_fd, LOCK_EX)) {
1154                 RTE_LOG(ERR, EAL, "Unable to lock directory %s\n",
1155                         mp_dir_path);
1156                 rte_errno = errno;
1157                 goto closedir_fail;
1158         }
1159
1160         while ((ent = readdir(mp_dir))) {
1161                 char path[PATH_MAX];
1162
1163                 if (fnmatch(mp_filter, ent->d_name, 0) != 0)
1164                         continue;
1165
1166                 snprintf(path, sizeof(path), "%s/%s", mp_dir_path,
1167                          ent->d_name);
1168
1169                 if (mp_request_async(path, copy, param))
1170                         ret = -1;
1171         }
1172         /* if we didn't send anything, put dummy request on the queue */
1173         if (ret == 0 && reply->nb_sent == 0) {
1174                 TAILQ_INSERT_HEAD(&pending_requests.requests, dummy, next);
1175                 dummy_used = true;
1176         }
1177
1178         /* trigger async request thread wake up */
1179         pthread_cond_signal(&pending_requests.async_cond);
1180
1181         /* finally, unlock the queue */
1182         pthread_mutex_unlock(&pending_requests.lock);
1183
1184         /* unlock the directory */
1185         flock(dir_fd, LOCK_UN);
1186
1187         /* dir_fd automatically closed on closedir */
1188         closedir(mp_dir);
1189
1190         /* if dummy was unused, free it */
1191         if (!dummy_used)
1192                 free(dummy);
1193
1194         return ret;
1195 closedir_fail:
1196         closedir(mp_dir);
1197 unlock_fail:
1198         pthread_mutex_unlock(&pending_requests.lock);
1199 fail:
1200         free(dummy);
1201         free(param);
1202         free(copy);
1203         return -1;
1204 }
1205
1206 int __rte_experimental
1207 rte_mp_reply(struct rte_mp_msg *msg, const char *peer)
1208 {
1209         RTE_LOG(DEBUG, EAL, "reply: %s\n", msg->name);
1210
1211         if (check_input(msg) == false)
1212                 return -1;
1213
1214         if (peer == NULL) {
1215                 RTE_LOG(ERR, EAL, "peer is not specified\n");
1216                 rte_errno = EINVAL;
1217                 return -1;
1218         }
1219
1220         return mp_send(msg, peer, MP_REP);
1221 }