Build libmemif as part of verify job
[vpp.git] / extras / libmemif / src / main.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2017 Cisco and/or its affiliates.
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at:
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *------------------------------------------------------------------
16  */
17
18 #include <stdint.h>
19 #include <net/if.h>
20 #include <sys/types.h>
21 #include <fcntl.h>
22 #include <sys/ioctl.h>
23 #include <sys/socket.h>
24 #include <sys/un.h>
25 #include <sys/uio.h>
26 #include <sys/mman.h>
27 #include <sys/prctl.h>
28 #include <inttypes.h>
29 #include <string.h>
30 #include <stdio.h>
31 #include <netdb.h>
32 #include <linux/ip.h>
33 #include <linux/icmp.h>
34 #include <arpa/inet.h>
35 #include <stdlib.h>
36 #include <netinet/if_ether.h>
37 #include <net/if_arp.h>
38 #include <asm/byteorder.h>
39 #include <byteswap.h>
40 #include <string.h>
41 #include <errno.h>
42 #include <sys/stat.h>
43 #include <sys/eventfd.h>
44 #include <sys/timerfd.h>
45 #include <sys/epoll.h>
46 #include <signal.h>
47
48 /* memif protocol msg, ring and descriptor definitions */
49 #include <memif.h>
50 /* memif api */
51 #include <libmemif.h>
52 /* socket messaging functions */
53 #include <socket.h>
54 /* private structs and functions */
55 #include <memif_private.h>
56
57 #define ERRLIST_LEN 39
58 #define MAX_ERRBUF_LEN 256
59
60 #if __x86_x64__
61 #define MEMIF_MEMORY_BARRIER() __builtin_ia32_sfence ()
62 #else
63 #define MEMIF_MEMORY_BARRIER() __sync_synchronize ()
64 #endif /* __x86_x64__ */
65
66 libmemif_main_t libmemif_main;
67 int memif_epfd;
68 int poll_cancel_fd = -1;
69
70 static char memif_buf[MAX_ERRBUF_LEN];
71
72 const char *memif_errlist[ERRLIST_LEN] = {      /* MEMIF_ERR_SUCCESS */
73   "Success.",
74   /* MEMIF_ERR_SYSCALL */
75   "Unspecified syscall error (build with -DMEMIF_DBG or make debug).",
76   /* MEMIF_ERR_ACCES */
77   "Permission to resoure denied.",
78   /* MEMIF_ERR_NO_FILE */
79   "Socket file does not exist",
80   /* MEMIF_ERR_FILE_LIMIT */
81   "System limit on total numer of open files reached.",
82   /* MEMIF_ERR_PROC_FILE_LIMIT */
83   "Per-process limit on total number of open files reached.",
84   /* MEMIF_ERR_ALREADY */
85   "Connection already requested.",
86   /* MEMIF_ERR_AGAIN */
87   "File descriptor refers to file other than socket, or operation would block.",
88   /* MEMIF_ERR_BAD_FD */
89   "Bad file descriptor.",
90   /* MEMIF_ERR_NOMEM */
91   "Out of memory.",
92   /* MEMIF_ERR_INVAL_ARG */
93   "Invalid argument.",
94   /* MEMIF_ERR_NOCONN */
95   "Memif connection handle does not point to existing conenction",
96   /* MEMIF_ERR_CONN */
97   "Memif connection handle points to existing connection",
98   /* MEMIF_ERR_CB_FDUPDATE */
99   "Callback memif_control_fd_update_t returned error",
100   /* MEMIF_ERR_FILE_NOT_SOCK */
101   "File specified by socket filename exists and is not socket.",
102   /* MEMIF_ERR_NO_SHMFD */
103   "Missing shared memory file descriptor. (internal error)",
104   /* MEMIF_ERR_COOKIE */
105   "Invalid cookie on ring. (internal error)",
106   /* MEMIF_ERR_NOBUF_RING */
107   "Ring buffer full.",
108   /* MEMIF_ERR_NOBUF */
109   "Not enough memif buffers. There are unreceived data in shared memory.",
110   /* MEMIF_ERR_NOBUF_DET */
111   "Not enough space for memif details in suplied buffer. String data might be malformed.",
112   /* MEMIF_ERR_INT_WRITE */
113   "Send interrupt error.",
114   /* MEMIF_ERR_MFMSG */
115   "Malformed message received on control channel.",
116   /* MEMIF_ERR_QID */
117   "Invalid queue id",
118   /* MEMIF_ERR_PROTO */
119   "Incompatible memory interface protocol version.",
120   /* MEMIF_ERR_ID */
121   "Unmatched interface id.",
122   /* MEMIF_ERR_ACCSLAVE */
123   "Slave cannot accept connection reqest.",
124   /* MEMIF_ERR_ALRCONN */
125   "Interface is already connected.",
126   /* MEMIF_ERR_MODE */
127   "Mode mismatch.",
128   /* MEMIF_ERR_SECRET */
129   "Secret mismatch.",
130   /* MEMIF_ERR_NOSECRET */
131   "Secret required.",
132   /* MEMIF_ERR_MAXREG */
133   "Limit on total number of regions reached.",
134   /* MEMIF_ERR_MAXRING */
135   "Limit on total number of ring reached.",
136   /* MEMIF_ERR_NO_INTFD */
137   "Missing interrupt file descriptor. (internal error)",
138   /* MEMIF_ERR_DISCONNECT */
139   "Interface received disconnect request.",
140   /* MEMIF_ERR_DISCONNECTED */
141   "Interface is disconnected.",
142   /* MEMIF_ERR_UNKNOWN_MSG */
143   "Unknown message type received on control channel. (internal error)",
144   /* MEMIF_ERR_POLL_CANCEL */
145   "Memif event polling was canceled.",
146   /* MEMIF_ERR_MAX_RING */
147   "Maximum log2 ring size is 15.",
148   /* MEMIF_ERR_PRIVHDR */
149   "Private headers not supported."
150 };
151
152 #define MEMIF_ERR_UNDEFINED "undefined error"
153
154 char *
155 memif_strerror (int err_code)
156 {
157   if (err_code >= ERRLIST_LEN)
158     {
159       strncpy (memif_buf, MEMIF_ERR_UNDEFINED, strlen (MEMIF_ERR_UNDEFINED));
160       memif_buf[strlen (MEMIF_ERR_UNDEFINED)] = '\0';
161     }
162   else
163     {
164       strncpy (memif_buf, memif_errlist[err_code],
165                strlen (memif_errlist[err_code]));
166       memif_buf[strlen (memif_errlist[err_code])] = '\0';
167     }
168   return memif_buf;
169 }
170
171 uint16_t
172 memif_get_version ()
173 {
174   return MEMIF_VERSION;
175 }
176
177 #define DBG_TX_BUF (0)
178 #define DBG_RX_BUF (1)
179
180 #ifdef MEMIF_DBG_SHM
181 static void
182 print_bytes (void *data, uint16_t len, uint8_t q)
183 {
184   if (q == DBG_TX_BUF)
185     printf ("\nTX:\n\t");
186   else
187     printf ("\nRX:\n\t");
188   int i;
189   for (i = 0; i < len; i++)
190     {
191       if (i % 8 == 0)
192         printf ("\n%d:\t", i);
193       printf ("%02X ", ((uint8_t *) (data))[i]);
194     }
195   printf ("\n\n");
196 }
197 #endif /* MEMIF_DBG_SHM */
198
199 int
200 memif_syscall_error_handler (int err_code)
201 {
202   DBG ("%s", strerror (err_code));
203
204   if (err_code == 0)
205     return MEMIF_ERR_SUCCESS;
206   if (err_code == EACCES)
207     return MEMIF_ERR_ACCES;
208   if (err_code == ENFILE)
209     return MEMIF_ERR_FILE_LIMIT;
210   if (err_code == EMFILE)
211     return MEMIF_ERR_PROC_FILE_LIMIT;
212   if (err_code == ENOMEM)
213     return MEMIF_ERR_NOMEM;
214 /* connection refused if master does not exist
215     this error would spam the user until master was created */
216   if (err_code == ECONNREFUSED)
217     return MEMIF_ERR_SUCCESS;
218   if (err_code == EALREADY)
219     return MEMIF_ERR_ALREADY;
220   if (err_code == EAGAIN)
221     return MEMIF_ERR_AGAIN;
222   if (err_code == EBADF)
223     return MEMIF_ERR_BAD_FD;
224   if (err_code == ENOENT)
225     return MEMIF_ERR_NO_FILE;
226
227   /* other syscall errors */
228   return MEMIF_ERR_SYSCALL;
229 }
230
231 static int
232 memif_add_epoll_fd (int fd, uint32_t events)
233 {
234   if (fd < 0)
235     {
236       DBG ("invalid fd %d", fd);
237       return -1;
238     }
239   struct epoll_event evt;
240   memset (&evt, 0, sizeof (evt));
241   evt.events = events;
242   evt.data.fd = fd;
243   if (epoll_ctl (memif_epfd, EPOLL_CTL_ADD, fd, &evt) < 0)
244     {
245       DBG ("epoll_ctl: %s fd %d", strerror (errno), fd);
246       return -1;
247     }
248   DBG ("fd %d added to epoll", fd);
249   return 0;
250 }
251
252 static int
253 memif_mod_epoll_fd (int fd, uint32_t events)
254 {
255   if (fd < 0)
256     {
257       DBG ("invalid fd %d", fd);
258       return -1;
259     }
260   struct epoll_event evt;
261   memset (&evt, 0, sizeof (evt));
262   evt.events = events;
263   evt.data.fd = fd;
264   if (epoll_ctl (memif_epfd, EPOLL_CTL_MOD, fd, &evt) < 0)
265     {
266       DBG ("epoll_ctl: %s fd %d", strerror (errno), fd);
267       return -1;
268     }
269   DBG ("fd %d moddified on epoll", fd);
270   return 0;
271 }
272
273 static int
274 memif_del_epoll_fd (int fd)
275 {
276   if (fd < 0)
277     {
278       DBG ("invalid fd %d", fd);
279       return -1;
280     }
281   struct epoll_event evt;
282   memset (&evt, 0, sizeof (evt));
283   if (epoll_ctl (memif_epfd, EPOLL_CTL_DEL, fd, &evt) < 0)
284     {
285       DBG ("epoll_ctl: %s fd %d", strerror (errno), fd);
286       return -1;
287     }
288   DBG ("fd %d removed from epoll", fd);
289   return 0;
290 }
291
292 int
293 memif_control_fd_update (int fd, uint8_t events)
294 {
295   if (events & MEMIF_FD_EVENT_DEL)
296     return memif_del_epoll_fd (fd);
297
298   uint32_t evt = 0;
299   if (events & MEMIF_FD_EVENT_READ)
300     evt |= EPOLLIN;
301   if (events & MEMIF_FD_EVENT_WRITE)
302     evt |= EPOLLOUT;
303
304   if (events & MEMIF_FD_EVENT_MOD)
305     return memif_mod_epoll_fd (fd, evt);
306
307   return memif_add_epoll_fd (fd, evt);
308 }
309
310 int
311 add_list_elt (memif_list_elt_t * e, memif_list_elt_t ** list, uint16_t * len)
312 {
313   libmemif_main_t *lm = &libmemif_main;
314
315   int i;
316   for (i = 0; i < *len; i++)
317     {
318       if ((*list)[i].data_struct == NULL)
319         {
320           (*list)[i].key = e->key;
321           (*list)[i].data_struct = e->data_struct;
322           return i;
323         }
324     }
325   memif_list_elt_t *tmp;
326   tmp = realloc (*list, sizeof (memif_list_elt_t) * *len * 2);
327   if (tmp == NULL)
328     return -1;
329
330   for (i = *len; i < *len * 2; i++)
331     {
332       tmp[i].key = -1;
333       tmp[i].data_struct = NULL;
334     }
335
336   tmp[*len].key = e->key;
337   tmp[*len].data_struct = e->data_struct;
338   i = *len;
339   *len = *len * 2;
340   *list = tmp;
341
342   return i;
343 }
344
345 int
346 get_list_elt (memif_list_elt_t ** e, memif_list_elt_t * list, uint16_t len,
347               int key)
348 {
349   if (key == -1)
350     {
351       *e = NULL;
352       return -1;
353     }
354   int i;
355   for (i = 0; i < len; i++)
356     {
357       if (list[i].key == key)
358         {
359           *e = &list[i];
360           return 0;
361         }
362     }
363   *e = NULL;
364   return -1;
365 }
366
367 /* does not free memory, only marks element as free */
368 int
369 free_list_elt (memif_list_elt_t * list, uint16_t len, int key)
370 {
371   int i;
372   for (i = 0; i < len; i++)
373     {
374       if (list[i].key == key)
375         {
376           list[i].key = -1;
377           list[i].data_struct = NULL;
378           return 0;
379         }
380     }
381
382   return -1;
383 }
384
385 int
386 free_list_elt_ctx (memif_list_elt_t * list, uint16_t len,
387                    memif_connection_t * ctx)
388 {
389   int i;
390   for (i = 0; i < len; i++)
391     {
392       if (list[i].key == -1)
393         {
394           if (list[i].data_struct == ctx)
395             {
396               list[i].data_struct = NULL;
397               return 0;
398             }
399         }
400     }
401
402   return -1;
403 }
404
405 static void
406 memif_control_fd_update_register (memif_control_fd_update_t * cb)
407 {
408   libmemif_main_t *lm = &libmemif_main;
409   lm->control_fd_update = cb;
410 }
411
412 static void
413 memif_alloc_register (memif_alloc_t * ma)
414 {
415   libmemif_main_t *lm = &libmemif_main;
416   lm->alloc = ma;
417 }
418
419 static void
420 memif_free_register (memif_free_t * mf)
421 {
422   libmemif_main_t *lm = &libmemif_main;
423   lm->free = mf;
424 }
425
426 int
427 memif_init (memif_control_fd_update_t * on_control_fd_update, char *app_name,
428             memif_alloc_t * memif_alloc, memif_free_t * memif_free)
429 {
430   int err = MEMIF_ERR_SUCCESS;  /* 0 */
431   libmemif_main_t *lm = &libmemif_main;
432   memset (lm, 0, sizeof (libmemif_main_t));
433
434   if (memif_alloc != NULL)
435     {
436       memif_alloc_register (memif_alloc);
437     }
438   else
439     memif_alloc_register (malloc);
440
441   if (memif_free != NULL)
442     memif_free_register (memif_free);
443   else
444     memif_free_register (free);
445
446   if (app_name != NULL)
447     {
448       uint8_t len = (strlen (app_name) > MEMIF_NAME_LEN)
449         ? strlen (app_name) : MEMIF_NAME_LEN;
450       strncpy ((char *) lm->app_name, app_name, len);
451     }
452   else
453     {
454       strncpy ((char *) lm->app_name, MEMIF_DEFAULT_APP_NAME,
455                strlen (MEMIF_DEFAULT_APP_NAME));
456     }
457
458   /* register control fd update callback */
459   if (on_control_fd_update != NULL)
460     memif_control_fd_update_register (on_control_fd_update);
461   else
462     {
463       memif_epfd = epoll_create (1);
464       memif_control_fd_update_register (memif_control_fd_update);
465       if ((poll_cancel_fd = eventfd (0, EFD_NONBLOCK)) < 0)
466         {
467           err = errno;
468           DBG ("eventfd: %s", strerror (err));
469           return memif_syscall_error_handler (err);
470         }
471       lm->control_fd_update (poll_cancel_fd, MEMIF_FD_EVENT_READ);
472       DBG ("libmemif event polling initialized");
473     }
474
475   lm->control_list_len = 2;
476   lm->interrupt_list_len = 2;
477   lm->listener_list_len = 1;
478   lm->pending_list_len = 1;
479
480   lm->control_list =
481     lm->alloc (sizeof (memif_list_elt_t) * lm->control_list_len);
482   if (lm->control_list == NULL)
483     {
484       err = MEMIF_ERR_NOMEM;
485       goto error;
486     }
487   lm->interrupt_list =
488     lm->alloc (sizeof (memif_list_elt_t) * lm->interrupt_list_len);
489   if (lm->interrupt_list == NULL)
490     {
491       err = MEMIF_ERR_NOMEM;
492       goto error;
493     }
494   lm->listener_list =
495     lm->alloc (sizeof (memif_list_elt_t) * lm->listener_list_len);
496   if (lm->listener_list == NULL)
497     {
498       err = MEMIF_ERR_NOMEM;
499       goto error;
500     }
501   lm->pending_list =
502     lm->alloc (sizeof (memif_list_elt_t) * lm->pending_list_len);
503   if (lm->pending_list == NULL)
504     {
505       err = MEMIF_ERR_NOMEM;
506       goto error;
507     }
508
509   int i;
510   for (i = 0; i < lm->control_list_len; i++)
511     {
512       lm->control_list[i].key = -1;
513       lm->control_list[i].data_struct = NULL;
514     }
515   for (i = 0; i < lm->interrupt_list_len; i++)
516     {
517       lm->interrupt_list[i].key = -1;
518       lm->interrupt_list[i].data_struct = NULL;
519     }
520   for (i = 0; i < lm->listener_list_len; i++)
521     {
522       lm->listener_list[i].key = -1;
523       lm->listener_list[i].data_struct = NULL;
524     }
525   for (i = 0; i < lm->pending_list_len; i++)
526     {
527       lm->pending_list[i].key = -1;
528       lm->pending_list[i].data_struct = NULL;
529     }
530
531   lm->disconn_slaves = 0;
532
533   lm->timerfd = timerfd_create (CLOCK_REALTIME, TFD_NONBLOCK);
534   if (lm->timerfd < 0)
535     {
536       err = memif_syscall_error_handler (errno);
537       goto error;
538     }
539
540   lm->arm.it_value.tv_sec = 2;
541   lm->arm.it_value.tv_nsec = 0;
542   lm->arm.it_interval.tv_sec = 2;
543   lm->arm.it_interval.tv_nsec = 0;
544
545   if (lm->control_fd_update (lm->timerfd, MEMIF_FD_EVENT_READ) < 0)
546     {
547       DBG ("callback type memif_control_fd_update_t error!");
548       err = MEMIF_ERR_CB_FDUPDATE;
549       goto error;
550     }
551
552   return err;
553
554 error:
555   memif_cleanup ();
556   return err;
557 }
558
559 static inline memif_ring_t *
560 memif_get_ring (memif_connection_t * conn, memif_ring_type_t type,
561                 uint16_t ring_num)
562 {
563   if (&conn->regions[0] == NULL)
564     return NULL;
565   void *p = conn->regions[0].shm;
566   int ring_size =
567     sizeof (memif_ring_t) +
568     sizeof (memif_desc_t) * (1 << conn->run_args.log2_ring_size);
569   p += (ring_num + type * conn->run_args.num_s2m_rings) * ring_size;
570
571   return (memif_ring_t *) p;
572 }
573
574 int
575 memif_set_rx_mode (memif_conn_handle_t c, memif_rx_mode_t rx_mode,
576                    uint16_t qid)
577 {
578   memif_connection_t *conn = (memif_connection_t *) c;
579   if (conn == NULL)
580     return MEMIF_ERR_NOCONN;
581   uint8_t num =
582     (conn->args.is_master) ? conn->run_args.num_s2m_rings : conn->run_args.
583     num_m2s_rings;
584   if (qid >= num)
585     return MEMIF_ERR_QID;
586
587   conn->rx_queues[qid].ring->flags = rx_mode;
588   DBG ("rx_mode flag: %u", conn->rx_queues[qid].ring->flags);
589   return MEMIF_ERR_SUCCESS;
590 }
591
592 int
593 memif_create (memif_conn_handle_t * c, memif_conn_args_t * args,
594               memif_connection_update_t * on_connect,
595               memif_connection_update_t * on_disconnect,
596               memif_interrupt_t * on_interrupt, void *private_ctx)
597 {
598   libmemif_main_t *lm = &libmemif_main;
599   int err, i, index, sockfd = -1;
600   memif_list_elt_t list_elt;
601   memif_connection_t *conn = (memif_connection_t *) * c;
602   if (conn != NULL)
603     {
604       DBG ("This handle already points to existing memif.");
605       return MEMIF_ERR_CONN;
606     }
607   conn = (memif_connection_t *) lm->alloc (sizeof (memif_connection_t));
608   if (conn == NULL)
609     {
610       err = MEMIF_ERR_NOMEM;
611       goto error;
612     }
613   memset (conn, 0, sizeof (memif_connection_t));
614
615   conn->args.interface_id = args->interface_id;
616
617   if (args->log2_ring_size == 0)
618     args->log2_ring_size = MEMIF_DEFAULT_LOG2_RING_SIZE;
619   else if (args->log2_ring_size > MEMIF_MAX_LOG2_RING_SIZE)
620     {
621       err = MEMIF_ERR_MAX_RING;
622       goto error;
623     }
624   if (args->buffer_size == 0)
625     args->buffer_size = MEMIF_DEFAULT_BUFFER_SIZE;
626   if (args->num_s2m_rings == 0)
627     args->num_s2m_rings = MEMIF_DEFAULT_TX_QUEUES;
628   if (args->num_m2s_rings == 0)
629     args->num_m2s_rings = MEMIF_DEFAULT_RX_QUEUES;
630
631   conn->args.num_s2m_rings = args->num_s2m_rings;
632   conn->args.num_m2s_rings = args->num_m2s_rings;
633   conn->args.buffer_size = args->buffer_size;
634   conn->args.log2_ring_size = args->log2_ring_size;
635   conn->args.is_master = args->is_master;
636   conn->args.mode = args->mode;
637   conn->msg_queue = NULL;
638   conn->regions = NULL;
639   conn->tx_queues = NULL;
640   conn->rx_queues = NULL;
641   conn->fd = -1;
642   conn->on_connect = on_connect;
643   conn->on_disconnect = on_disconnect;
644   conn->on_interrupt = on_interrupt;
645   conn->private_ctx = private_ctx;
646   memset (&conn->run_args, 0, sizeof (memif_conn_run_args_t));
647
648   uint8_t l = strlen ((char *) args->interface_name);
649   strncpy ((char *) conn->args.interface_name, (char *) args->interface_name,
650            l);
651
652   /* allocate and initialize socket_filename so it can be copyed to sun_path
653      without memory leaks */
654   conn->args.socket_filename = lm->alloc (sizeof (char *) * 108);
655   if (conn->args.socket_filename == NULL)
656     {
657       err = MEMIF_ERR_NOMEM;
658       goto error;
659     }
660   memset (conn->args.socket_filename, 0, 108 * sizeof (char *));
661
662   if (args->socket_filename)
663     {
664       if (conn->args.socket_filename == NULL)
665         {
666           err = memif_syscall_error_handler (errno);
667           goto error;
668         }
669       strncpy ((char *) conn->args.socket_filename,
670                (char *) args->socket_filename,
671                strlen ((char *) args->socket_filename));
672     }
673   else
674     {
675       uint16_t sdl = strlen (MEMIF_DEFAULT_SOCKET_DIR);
676       uint16_t sfl = strlen (MEMIF_DEFAULT_SOCKET_FILENAME);
677       if (conn->args.socket_filename == NULL)
678         {
679           err = memif_syscall_error_handler (errno);
680           goto error;
681         }
682       strncpy ((char *) conn->args.socket_filename,
683                MEMIF_DEFAULT_SOCKET_DIR, sdl);
684       conn->args.socket_filename[sdl] = '/';
685       strncpy ((char *) (conn->args.socket_filename + 1 + sdl),
686                MEMIF_DEFAULT_SOCKET_FILENAME, sfl);
687     }
688
689   if (args->secret)
690     {
691       l = strlen ((char *) args->secret);
692       strncpy ((char *) conn->args.secret, (char *) args->secret, l);
693     }
694
695   if (conn->args.is_master)
696     {
697       conn->run_args.buffer_size = conn->args.buffer_size;
698       memif_socket_t *ms;
699       memif_list_elt_t elt;
700       for (i = 0; i < lm->listener_list_len; i++)
701         {
702           if ((ms =
703                (memif_socket_t *) lm->listener_list[i].data_struct) != NULL)
704             {
705               if (strncmp
706                   ((char *) ms->filename, (char *) conn->args.socket_filename,
707                    strlen ((char *) ms->filename)) == 0)
708                 {
709                   /* add interface to listener socket */
710                   elt.key = conn->args.interface_id;
711                   *c = elt.data_struct = conn;
712                   add_list_elt (&elt, &ms->interface_list,
713                                 &ms->interface_list_len);
714                   ms->use_count++;
715                   conn->listener_fd = ms->fd;
716                   break;
717                 }
718             }
719           else
720             {
721               struct stat file_stat;
722               if (stat ((char *) conn->args.socket_filename, &file_stat) == 0)
723                 {
724                   if (S_ISSOCK (file_stat.st_mode))
725                     unlink ((char *) conn->args.socket_filename);
726                   else
727                     return memif_syscall_error_handler (errno);
728                 }
729               DBG ("creating socket file");
730               ms = lm->alloc (sizeof (memif_socket_t));
731               if (ms == NULL)
732                 {
733                   err = MEMIF_ERR_NOMEM;
734                   goto error;
735                 }
736               ms->filename =
737                 lm->alloc (strlen ((char *) conn->args.socket_filename) +
738                            sizeof (char));
739               if (ms->filename == NULL)
740                 {
741                   err = MEMIF_ERR_NOMEM;
742                   goto error;
743                 }
744               memset (ms->filename, 0,
745                       strlen ((char *) conn->args.socket_filename) +
746                       sizeof (char));
747               strncpy ((char *) ms->filename,
748                        (char *) conn->args.socket_filename,
749                        strlen ((char *) conn->args.socket_filename));
750               ms->interface_list_len = 1;
751               ms->interface_list =
752                 lm->alloc (sizeof (memif_list_elt_t) *
753                            ms->interface_list_len);
754               if (ms->interface_list == NULL)
755                 {
756                   err = MEMIF_ERR_NOMEM;
757                   goto error;
758                 }
759               ms->interface_list[0].key = -1;
760               ms->interface_list[0].data_struct = NULL;
761               struct sockaddr_un un = { 0 };
762               int on = 1;
763
764               ms->fd = socket (AF_UNIX, SOCK_SEQPACKET, 0);
765               if (ms->fd < 0)
766                 {
767                   err = memif_syscall_error_handler (errno);
768                   goto error;
769                 }
770               DBG ("socket %d created", ms->fd);
771               un.sun_family = AF_UNIX;
772               strncpy ((char *) un.sun_path, (char *) ms->filename,
773                        sizeof (un.sun_path) - 1);
774               DBG ("sockopt");
775               if (setsockopt
776                   (ms->fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof (on)) < 0)
777                 {
778                   err = memif_syscall_error_handler (errno);
779                   goto error;
780                 }
781               DBG ("bind");
782               if (bind (ms->fd, (struct sockaddr *) &un, sizeof (un)) < 0)
783                 {
784                   err = memif_syscall_error_handler (errno);
785                   goto error;
786                 }
787               DBG ("listen");
788               if (listen (ms->fd, 1) < 0)
789                 {
790                   err = memif_syscall_error_handler (errno);
791                   goto error;
792                 }
793               DBG ("stat");
794               if (stat ((char *) ms->filename, &file_stat) < 0)
795                 {
796                   err = memif_syscall_error_handler (errno);
797                   goto error;
798                 }
799
800               /* add interface to listener socket */
801               elt.key = conn->args.interface_id;
802               *c = elt.data_struct = conn;
803               add_list_elt (&elt, &ms->interface_list,
804                             &ms->interface_list_len);
805               ms->use_count = 1;
806               conn->listener_fd = ms->fd;
807
808               /* add listener socket to libmemif main */
809               elt.key = ms->fd;
810               elt.data_struct = ms;
811               add_list_elt (&elt, &lm->listener_list, &lm->listener_list_len);
812               lm->control_fd_update (ms->fd, MEMIF_FD_EVENT_READ);
813               break;
814             }
815         }
816     }
817   else
818     {
819       if (lm->disconn_slaves == 0)
820         {
821           if (timerfd_settime (lm->timerfd, 0, &lm->arm, NULL) < 0)
822             {
823               err = memif_syscall_error_handler (errno);
824               goto error;
825             }
826         }
827
828       lm->disconn_slaves++;
829
830       list_elt.key = -1;
831       *c = list_elt.data_struct = conn;
832       if ((index =
833            add_list_elt (&list_elt, &lm->control_list,
834                          &lm->control_list_len)) < 0)
835         {
836           err = MEMIF_ERR_NOMEM;
837           goto error;
838         }
839     }
840
841   conn->index = index;
842
843   return 0;
844
845 error:
846   if (sockfd > 0)
847     close (sockfd);
848   sockfd = -1;
849   if (conn->args.socket_filename)
850     lm->free (conn->args.socket_filename);
851   if (conn != NULL)
852     lm->free (conn);
853   *c = conn = NULL;
854   return err;
855 }
856
857 int
858 memif_control_fd_handler (int fd, uint8_t events)
859 {
860   int i, rv, sockfd = -1, err = MEMIF_ERR_SUCCESS;      /* 0 */
861   uint16_t num;
862   memif_list_elt_t *e = NULL;
863   memif_connection_t *conn;
864   libmemif_main_t *lm = &libmemif_main;
865   if (fd == lm->timerfd)
866     {
867       uint64_t b;
868       ssize_t size;
869       size = read (fd, &b, sizeof (b));
870       for (i = 0; i < lm->control_list_len; i++)
871         {
872           if ((lm->control_list[i].key < 0)
873               && (lm->control_list[i].data_struct != NULL))
874             {
875               conn = lm->control_list[i].data_struct;
876               if (conn->args.is_master)
877                 continue;
878
879               struct sockaddr_un sun;
880               sockfd = socket (AF_UNIX, SOCK_SEQPACKET, 0);
881               if (sockfd < 0)
882                 {
883                   err = memif_syscall_error_handler (errno);
884                   goto error;
885                 }
886
887               sun.sun_family = AF_UNIX;
888
889               strncpy (sun.sun_path, conn->args.socket_filename,
890                        sizeof (sun.sun_path) - 1);
891
892               if (connect (sockfd, (struct sockaddr *) &sun,
893                            sizeof (struct sockaddr_un)) == 0)
894                 {
895                   conn->fd = sockfd;
896                   conn->read_fn = memif_conn_fd_read_ready;
897                   conn->write_fn = memif_conn_fd_write_ready;
898                   conn->error_fn = memif_conn_fd_error;
899
900                   lm->control_list[conn->index].key = conn->fd;
901
902                   lm->control_fd_update (sockfd,
903                                          MEMIF_FD_EVENT_READ |
904                                          MEMIF_FD_EVENT_WRITE);
905
906                   lm->disconn_slaves--;
907                   if (lm->disconn_slaves == 0)
908                     {
909                       if (timerfd_settime (lm->timerfd, 0, &lm->disarm, NULL)
910                           < 0)
911                         {
912                           err = memif_syscall_error_handler (errno);
913                           goto error;
914                         }
915                     }
916                 }
917               else
918                 {
919                   err = memif_syscall_error_handler (errno);
920                   goto error;
921                 }
922             }
923         }
924     }
925   else
926     {
927       get_list_elt (&e, lm->interrupt_list, lm->interrupt_list_len, fd);
928       if (e != NULL)
929         {
930           if (((memif_connection_t *) e->data_struct)->on_interrupt != NULL)
931             {
932               num =
933                 (((memif_connection_t *) e->data_struct)->args.
934                  is_master) ? ((memif_connection_t *) e->data_struct)->
935                 run_args.num_s2m_rings : ((memif_connection_t *) e->
936                                           data_struct)->run_args.
937                 num_m2s_rings;
938               for (i = 0; i < num; i++)
939                 {
940                   if (((memif_connection_t *) e->data_struct)->rx_queues[i].
941                       int_fd == fd)
942                     {
943                       ((memif_connection_t *) e->
944                        data_struct)->on_interrupt ((void *) e->data_struct,
945                                                    ((memif_connection_t *)
946                                                     e->data_struct)->
947                                                    private_ctx, i);
948                       return MEMIF_ERR_SUCCESS;
949                     }
950                 }
951             }
952           return MEMIF_ERR_SUCCESS;
953         }
954       get_list_elt (&e, lm->listener_list, lm->listener_list_len, fd);
955       if (e != NULL)
956         {
957           memif_conn_fd_accept_ready ((memif_socket_t *) e->data_struct);
958           return MEMIF_ERR_SUCCESS;
959         }
960
961       get_list_elt (&e, lm->pending_list, lm->pending_list_len, fd);
962       if (e != NULL)
963         {
964           memif_read_ready (fd);
965           return MEMIF_ERR_SUCCESS;
966         }
967
968       get_list_elt (&e, lm->control_list, lm->control_list_len, fd);
969       if (e != NULL)
970         {
971           if (events & MEMIF_FD_EVENT_READ)
972             {
973               err =
974                 ((memif_connection_t *) e->data_struct)->read_fn (e->
975                                                                   data_struct);
976               if (err != MEMIF_ERR_SUCCESS)
977                 return err;
978             }
979           if (events & MEMIF_FD_EVENT_WRITE)
980             {
981               err =
982                 ((memif_connection_t *) e->data_struct)->write_fn (e->
983                                                                    data_struct);
984               if (err != MEMIF_ERR_SUCCESS)
985                 return err;
986             }
987           if (events & MEMIF_FD_EVENT_ERROR)
988             {
989               err =
990                 ((memif_connection_t *) e->data_struct)->error_fn (e->
991                                                                    data_struct);
992               if (err != MEMIF_ERR_SUCCESS)
993                 return err;
994             }
995         }
996     }
997
998   return MEMIF_ERR_SUCCESS;     /* 0 */
999
1000 error:
1001   if (sockfd > 0)
1002     close (sockfd);
1003   sockfd = -1;
1004   return err;
1005 }
1006
1007 int
1008 memif_poll_event (int timeout)
1009 {
1010   libmemif_main_t *lm = &libmemif_main;
1011   memif_list_elt_t *elt;
1012   struct epoll_event evt, *e;
1013   int en = 0, err = MEMIF_ERR_SUCCESS, i = 0;   /* 0 */
1014   uint16_t num;
1015   uint32_t events = 0;
1016   uint64_t counter = 0;
1017   ssize_t r = 0;
1018   memset (&evt, 0, sizeof (evt));
1019   evt.events = EPOLLIN | EPOLLOUT;
1020   sigset_t sigset;
1021   sigemptyset (&sigset);
1022   en = epoll_pwait (memif_epfd, &evt, 1, timeout, &sigset);
1023   if (en < 0)
1024     {
1025       err = errno;
1026       DBG ("epoll_pwait: %s", strerror (err));
1027       return memif_syscall_error_handler (err);
1028     }
1029   if (en > 0)
1030     {
1031       if (evt.data.fd == poll_cancel_fd)
1032         {
1033           r = read (evt.data.fd, &counter, sizeof (counter));
1034           return MEMIF_ERR_POLL_CANCEL;
1035         }
1036       if (evt.events & EPOLLIN)
1037         events |= MEMIF_FD_EVENT_READ;
1038       if (evt.events & EPOLLOUT)
1039         events |= MEMIF_FD_EVENT_WRITE;
1040       if (evt.events & EPOLLERR)
1041         events |= MEMIF_FD_EVENT_ERROR;
1042       err = memif_control_fd_handler (evt.data.fd, events);
1043       return err;
1044     }
1045   return 0;
1046 }
1047
1048 int
1049 memif_cancel_poll_event ()
1050 {
1051   uint64_t counter = 1;
1052   ssize_t w = 0;
1053
1054   if (poll_cancel_fd == -1)
1055     return 0;
1056   w = write (poll_cancel_fd, &counter, sizeof (counter));
1057   if (w < sizeof (counter))
1058     return MEMIF_ERR_INT_WRITE;
1059
1060   return 0;
1061 }
1062
1063 static void
1064 memif_msg_queue_free (libmemif_main_t * lm, memif_msg_queue_elt_t ** e)
1065 {
1066   if (*e == NULL)
1067     return;
1068   memif_msg_queue_free (lm, &(*e)->next);
1069   lm->free (*e);
1070   *e = NULL;
1071   return;
1072 }
1073
1074 /* send disconnect msg and close interface */
1075 int
1076 memif_disconnect_internal (memif_connection_t * c)
1077 {
1078   if (c == NULL)
1079     {
1080       DBG ("no connection");
1081       return MEMIF_ERR_NOCONN;
1082     }
1083   uint16_t num;
1084   int err = MEMIF_ERR_SUCCESS, i;       /* 0 */
1085   memif_queue_t *mq;
1086   libmemif_main_t *lm = &libmemif_main;
1087   memif_list_elt_t *e;
1088
1089   c->on_disconnect ((void *) c, c->private_ctx);
1090
1091   if (c->fd > 0)
1092     {
1093       memif_msg_send_disconnect (c->fd, "interface deleted", 0);
1094       lm->control_fd_update (c->fd, MEMIF_FD_EVENT_DEL);
1095       close (c->fd);
1096     }
1097   get_list_elt (&e, lm->control_list, lm->control_list_len, c->fd);
1098   if (e != NULL)
1099     {
1100       if (c->args.is_master)
1101         free_list_elt (lm->control_list, lm->control_list_len, c->fd);
1102       e->key = c->fd = -1;
1103     }
1104
1105   if (c->tx_queues != NULL)
1106     {
1107       num =
1108         (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1109         num_s2m_rings;
1110       for (i = 0; i < num; i++)
1111         {
1112           mq = &c->tx_queues[i];
1113           if (mq != NULL)
1114             {
1115               if (mq->int_fd > 0)
1116                 close (mq->int_fd);
1117               free_list_elt (lm->interrupt_list, lm->interrupt_list_len,
1118                              mq->int_fd);
1119               mq->int_fd = -1;
1120             }
1121         }
1122       lm->free (c->tx_queues);
1123       c->tx_queues = NULL;
1124     }
1125
1126   if (c->rx_queues != NULL)
1127     {
1128       num =
1129         (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1130         num_m2s_rings;
1131       for (i = 0; i < num; i++)
1132         {
1133           mq = &c->rx_queues[i];
1134           if (mq != NULL)
1135             {
1136               if (mq->int_fd > 0)
1137                 {
1138                   if (c->on_interrupt != NULL)
1139                     lm->control_fd_update (mq->int_fd, MEMIF_FD_EVENT_DEL);
1140                   close (mq->int_fd);
1141                 }
1142               free_list_elt (lm->interrupt_list, lm->interrupt_list_len,
1143                              mq->int_fd);
1144               mq->int_fd = -1;
1145             }
1146         }
1147       lm->free (c->rx_queues);
1148       c->rx_queues = NULL;
1149     }
1150
1151   if (c->regions != NULL)
1152     {
1153       if (munmap (c->regions[0].shm, c->regions[0].region_size) < 0)
1154         return memif_syscall_error_handler (errno);
1155       if (c->regions[0].fd > 0)
1156         close (c->regions[0].fd);
1157       c->regions[0].fd = -1;
1158       lm->free (c->regions);
1159       c->regions = NULL;
1160     }
1161
1162   memset (&c->run_args, 0, sizeof (memif_conn_run_args_t));
1163
1164   memif_msg_queue_free (lm, &c->msg_queue);
1165
1166   if (!(c->args.is_master))
1167     {
1168       if (lm->disconn_slaves == 0)
1169         {
1170           if (timerfd_settime (lm->timerfd, 0, &lm->arm, NULL) < 0)
1171             {
1172               err = memif_syscall_error_handler (errno);
1173               DBG ("timerfd_settime: arm");
1174             }
1175         }
1176       lm->disconn_slaves++;
1177     }
1178
1179   return err;
1180 }
1181
1182 int
1183 memif_delete (memif_conn_handle_t * conn)
1184 {
1185   memif_connection_t *c = (memif_connection_t *) * conn;
1186   if (c == NULL)
1187     {
1188       DBG ("no connection");
1189       return MEMIF_ERR_NOCONN;
1190     }
1191   libmemif_main_t *lm = &libmemif_main;
1192   memif_list_elt_t *e = NULL;
1193   memif_socket_t *ms = NULL;
1194
1195   int err = MEMIF_ERR_SUCCESS;
1196
1197   if (c->fd > 0)
1198     {
1199       DBG ("DISCONNECTING");
1200       err = memif_disconnect_internal (c);
1201       if (err == MEMIF_ERR_NOCONN)
1202         return err;
1203     }
1204
1205   free_list_elt_ctx (lm->control_list, lm->control_list_len, c);
1206
1207   if (c->args.is_master)
1208     {
1209       get_list_elt (&e, lm->listener_list, lm->listener_list_len,
1210                     c->listener_fd);
1211       if (e != NULL)
1212         {
1213           ms = (memif_socket_t *) e->data_struct;
1214           ms->use_count--;
1215           free_list_elt (ms->interface_list, ms->interface_list_len,
1216                          c->args.interface_id);
1217           if (ms->use_count <= 0)
1218             {
1219               lm->control_fd_update (c->listener_fd, MEMIF_FD_EVENT_DEL);
1220               free_list_elt (lm->listener_list, lm->listener_list_len,
1221                              c->listener_fd);
1222               close (c->listener_fd);
1223               c->listener_fd = ms->fd = -1;
1224               lm->free (ms->interface_list);
1225               ms->interface_list = NULL;
1226               lm->free (ms->filename);
1227               ms->filename = NULL;
1228               lm->free (ms);
1229               ms = NULL;
1230             }
1231         }
1232     }
1233   else
1234     {
1235       lm->disconn_slaves--;
1236       if (lm->disconn_slaves <= 0)
1237         {
1238           if (timerfd_settime (lm->timerfd, 0, &lm->disarm, NULL) < 0)
1239             {
1240               err = memif_syscall_error_handler (errno);
1241               DBG ("timerfd_settime: disarm");
1242             }
1243         }
1244     }
1245
1246   if (c->args.socket_filename)
1247     lm->free (c->args.socket_filename);
1248   c->args.socket_filename = NULL;
1249
1250   lm->free (c);
1251   c = NULL;
1252
1253   *conn = c;
1254   return err;
1255 }
1256
1257 int
1258 memif_connect1 (memif_connection_t * c)
1259 {
1260   libmemif_main_t *lm = &libmemif_main;
1261   memif_region_t *mr = c->regions;
1262   memif_queue_t *mq;
1263   int i;
1264   uint16_t num;
1265
1266   if (mr != NULL)
1267     {
1268       if (!mr->shm)
1269         {
1270           if (mr->fd < 0)
1271             return MEMIF_ERR_NO_SHMFD;
1272
1273           if ((mr->shm = mmap (NULL, mr->region_size, PROT_READ | PROT_WRITE,
1274                                MAP_SHARED, mr->fd, 0)) == MAP_FAILED)
1275             {
1276               return memif_syscall_error_handler (errno);
1277             }
1278         }
1279     }
1280
1281   num =
1282     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1283     num_s2m_rings;
1284   for (i = 0; i < num; i++)
1285     {
1286       mq = &c->tx_queues[i];
1287       if (mq != NULL)
1288         {
1289           mq->ring = c->regions[mq->region].shm + mq->offset;
1290           if (mq->ring->cookie != MEMIF_COOKIE)
1291             {
1292               DBG ("wrong cookie on tx ring %u", i);
1293               return MEMIF_ERR_COOKIE;
1294             }
1295           mq->ring->head = mq->ring->tail = mq->last_head = mq->alloc_bufs =
1296             0;
1297         }
1298     }
1299   num =
1300     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1301     num_m2s_rings;
1302   for (i = 0; i < num; i++)
1303     {
1304       mq = &c->rx_queues[i];
1305       if (mq != NULL)
1306         {
1307           mq->ring = c->regions[mq->region].shm + mq->offset;
1308           if (mq->ring->cookie != MEMIF_COOKIE)
1309             {
1310               DBG ("wrong cookie on rx ring %u", i);
1311               return MEMIF_ERR_COOKIE;
1312             }
1313           mq->ring->head = mq->ring->tail = mq->last_head = mq->alloc_bufs =
1314             0;
1315         }
1316     }
1317
1318   lm->control_fd_update (c->fd, MEMIF_FD_EVENT_READ | MEMIF_FD_EVENT_MOD);
1319
1320   return 0;
1321 }
1322
1323 int
1324 memif_init_regions_and_queues (memif_connection_t * conn)
1325 {
1326   memif_ring_t *ring = NULL;
1327   uint64_t buffer_offset;
1328   memif_region_t *r;
1329   int i, j;
1330   libmemif_main_t *lm = &libmemif_main;
1331   memif_list_elt_t e;
1332
1333   conn->regions = (memif_region_t *) lm->alloc (sizeof (memif_region_t));
1334   if (conn->regions == NULL)
1335     return MEMIF_ERR_NOMEM;
1336   r = conn->regions;
1337
1338   buffer_offset =
1339     (conn->run_args.num_s2m_rings +
1340      conn->run_args.num_m2s_rings) * (sizeof (memif_ring_t) +
1341                                       sizeof (memif_desc_t) *
1342                                       (1 << conn->run_args.log2_ring_size));
1343
1344   r->region_size = buffer_offset +
1345     conn->run_args.buffer_size * (1 << conn->run_args.log2_ring_size) *
1346     (conn->run_args.num_s2m_rings + conn->run_args.num_m2s_rings);
1347
1348   if ((r->fd =
1349        memfd_create ("memif region 0", MFD_ALLOW_SEALING)) == -1)
1350     return memif_syscall_error_handler (errno);
1351
1352   if ((fcntl (r->fd, F_ADD_SEALS, F_SEAL_SHRINK)) == -1)
1353     return memif_syscall_error_handler (errno);
1354
1355   if ((ftruncate (r->fd, r->region_size)) == -1)
1356     return memif_syscall_error_handler (errno);
1357
1358   if ((r->shm = mmap (NULL, r->region_size, PROT_READ | PROT_WRITE,
1359                       MAP_SHARED, r->fd, 0)) == MAP_FAILED)
1360     return memif_syscall_error_handler (errno);
1361
1362   for (i = 0; i < conn->run_args.num_s2m_rings; i++)
1363     {
1364       ring = memif_get_ring (conn, MEMIF_RING_S2M, i);
1365       DBG ("RING: %p I: %d", ring, i);
1366       ring->head = ring->tail = 0;
1367       ring->cookie = MEMIF_COOKIE;
1368       ring->flags = 0;
1369       for (j = 0; j < (1 << conn->run_args.log2_ring_size); j++)
1370         {
1371           uint16_t slot = i * (1 << conn->run_args.log2_ring_size) + j;
1372           ring->desc[j].region = 0;
1373           ring->desc[j].offset = buffer_offset +
1374             (uint32_t) (slot * conn->run_args.buffer_size);
1375           ring->desc[j].length = conn->run_args.buffer_size;
1376         }
1377     }
1378   for (i = 0; i < conn->run_args.num_m2s_rings; i++)
1379     {
1380       ring = memif_get_ring (conn, MEMIF_RING_M2S, i);
1381       DBG ("RING: %p I: %d", ring, i);
1382       ring->head = ring->tail = 0;
1383       ring->cookie = MEMIF_COOKIE;
1384       ring->flags = 0;
1385       for (j = 0; j < (1 << conn->run_args.log2_ring_size); j++)
1386         {
1387           uint16_t slot =
1388             (i +
1389              conn->run_args.num_s2m_rings) *
1390             (1 << conn->run_args.log2_ring_size) + j;
1391           ring->desc[j].region = 0;
1392           ring->desc[j].offset = buffer_offset +
1393             (uint32_t) (slot * conn->run_args.buffer_size);
1394           ring->desc[j].length = conn->run_args.buffer_size;
1395         }
1396     }
1397   memif_queue_t *mq;
1398   mq =
1399     (memif_queue_t *) lm->alloc (sizeof (memif_queue_t) *
1400                                  conn->run_args.num_s2m_rings);
1401   if (mq == NULL)
1402     return MEMIF_ERR_NOMEM;
1403   int x;
1404   for (x = 0; x < conn->run_args.num_s2m_rings; x++)
1405     {
1406       if ((mq[x].int_fd = eventfd (0, EFD_NONBLOCK)) < 0)
1407         return memif_syscall_error_handler (errno);
1408       /* add int fd to interrupt fd list */
1409       e.key = mq[x].int_fd;
1410       e.data_struct = conn;
1411       add_list_elt (&e, &lm->interrupt_list, &lm->interrupt_list_len);
1412
1413       mq[x].ring = memif_get_ring (conn, MEMIF_RING_S2M, x);
1414       DBG ("RING: %p I: %d", mq[x].ring, x);
1415       mq[x].log2_ring_size = conn->run_args.log2_ring_size;
1416       mq[x].region = 0;
1417       mq[x].offset =
1418         (void *) mq[x].ring - (void *) conn->regions[mq->region].shm;
1419       mq[x].last_head = 0;
1420       mq[x].last_tail = 0;
1421       mq[x].alloc_bufs = 0;
1422     }
1423   conn->tx_queues = mq;
1424
1425   mq =
1426     (memif_queue_t *) lm->alloc (sizeof (memif_queue_t) *
1427                                  conn->run_args.num_m2s_rings);
1428   if (mq == NULL)
1429     return MEMIF_ERR_NOMEM;
1430   for (x = 0; x < conn->run_args.num_m2s_rings; x++)
1431     {
1432       if ((mq[x].int_fd = eventfd (0, EFD_NONBLOCK)) < 0)
1433         return memif_syscall_error_handler (errno);
1434       /* add int fd to interrupt fd list */
1435       e.key = mq[x].int_fd;
1436       e.data_struct = conn;
1437       add_list_elt (&e, &lm->interrupt_list, &lm->interrupt_list_len);
1438
1439       mq[x].ring = memif_get_ring (conn, MEMIF_RING_M2S, x);
1440       DBG ("RING: %p I: %d", mq[x].ring, x);
1441       mq[x].log2_ring_size = conn->run_args.log2_ring_size;
1442       mq[x].region = 0;
1443       mq[x].offset =
1444         (void *) mq[x].ring - (void *) conn->regions[mq->region].shm;
1445       mq[x].last_head = 0;
1446       mq[x].last_tail = 0;
1447       mq[x].alloc_bufs = 0;
1448     }
1449   conn->rx_queues = mq;
1450
1451   return 0;
1452 }
1453
1454 int
1455 memif_buffer_alloc (memif_conn_handle_t conn, uint16_t qid,
1456                     memif_buffer_t * bufs, uint16_t count,
1457                     uint16_t * count_out, uint16_t size)
1458 {
1459   memif_connection_t *c = (memif_connection_t *) conn;
1460   if (EXPECT_FALSE (c == NULL))
1461     return MEMIF_ERR_NOCONN;
1462   if (EXPECT_FALSE (c->fd < 0))
1463     return MEMIF_ERR_DISCONNECTED;
1464   uint8_t num =
1465     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1466     num_s2m_rings;
1467   if (EXPECT_FALSE (qid >= num))
1468     return MEMIF_ERR_QID;
1469   if (EXPECT_FALSE (!count_out))
1470     return MEMIF_ERR_INVAL_ARG;
1471
1472   memif_queue_t *mq = &c->tx_queues[qid];
1473   memif_ring_t *ring = mq->ring;
1474   memif_buffer_t *b0, *b1;
1475   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1476   uint16_t ring_size;
1477   uint16_t slot, ns;
1478   int i, err = MEMIF_ERR_SUCCESS;       /* 0 */
1479   uint16_t dst_left, src_left;
1480   uint16_t saved_count;
1481   memif_buffer_t *saved_b;
1482   *count_out = 0;
1483
1484   ring_size = (1 << mq->log2_ring_size);
1485   ns = ring->tail - mq->last_tail;
1486   mq->last_tail += ns;
1487   slot = (c->args.is_master) ? ring->tail : ring->head;
1488   slot += mq->alloc_bufs;
1489
1490   if (c->args.is_master)
1491     ns = ring->head + mq->alloc_bufs - ring->tail;
1492   else
1493     ns = ring_size - ring->head + mq->alloc_bufs + mq->last_tail;
1494
1495   while (count && ns)
1496     {
1497       b0 = (bufs + *count_out);
1498
1499       saved_b = b0;
1500       saved_count = count;
1501
1502       b0->desc_index = slot;
1503       ring->desc[slot & mask].flags = 0;
1504
1505       /* slave can produce buffer with original length */
1506       dst_left = (c->args.is_master) ? ring->desc[slot & mask].length : c->run_args.buffer_size;        /* - headroom */
1507       src_left = size;
1508
1509       while (src_left)
1510         {
1511           if (dst_left == 0)
1512             {
1513               if (count && ns)
1514                 {
1515                   slot++;
1516                   *count_out += 1;
1517                   mq->alloc_bufs++;
1518                   ns--;
1519                   count--;
1520
1521                   ring->desc[b0->desc_index & mask].flags |=
1522                     MEMIF_DESC_FLAG_NEXT;
1523                   b0->flags |= MEMIF_BUFFER_FLAG_NEXT;
1524
1525                   b0 = (bufs + *count_out);
1526                   b0->desc_index = slot;
1527                   dst_left = (c->args.is_master) ? ring->desc[slot & mask].length : c->run_args.buffer_size;    /* - headroom */
1528                   ring->desc[slot & mask].flags = 0;
1529                 }
1530               else
1531                 {
1532                   /* rollback allocated chain buffers */
1533                   memset (saved_b, 0, sizeof (memif_buffer_t)
1534                           * (saved_count - count + 1));
1535                   *count_out -= saved_count - count;
1536                   mq->alloc_bufs = saved_count - count;
1537                   goto no_ns;
1538                 }
1539             }
1540           b0->len = memif_min (dst_left, src_left);
1541           b0->data = memif_get_buffer (c, ring, slot & mask);
1542
1543           src_left -= b0->len;
1544           dst_left -= b0->len;
1545         }
1546
1547       slot++;
1548       *count_out += 1;
1549       mq->alloc_bufs++;
1550       ns--;
1551       count--;
1552     }
1553
1554 no_ns:
1555
1556   DBG ("allocated: %u/%u bufs. Total %u allocated bufs", *count_out, count,
1557        mq->alloc_bufs);
1558
1559   if (count)
1560     {
1561       DBG ("ring buffer full! qid: %u", qid);
1562       err = MEMIF_ERR_NOBUF_RING;
1563     }
1564
1565   return err;
1566 }
1567
1568 int
1569 memif_refill_queue (memif_conn_handle_t conn, uint16_t qid, uint16_t count)
1570 {
1571   memif_connection_t *c = (memif_connection_t *) conn;
1572   if (EXPECT_FALSE (c == NULL))
1573     return MEMIF_ERR_NOCONN;
1574   if (EXPECT_FALSE (c->fd < 0))
1575     return MEMIF_ERR_DISCONNECTED;
1576   uint8_t num =
1577     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1578     num_m2s_rings;
1579   if (EXPECT_FALSE (qid >= num))
1580     return MEMIF_ERR_QID;
1581   libmemif_main_t *lm = &libmemif_main;
1582   memif_queue_t *mq = &c->rx_queues[qid];
1583   memif_ring_t *ring = mq->ring;
1584
1585   if (c->args.is_master)
1586     {
1587       MEMIF_MEMORY_BARRIER ();
1588       ring->tail =
1589         (ring->tail + count <=
1590          mq->last_head) ? ring->tail + count : mq->last_head;
1591     }
1592   else
1593     {
1594       uint16_t head = ring->head;
1595       uint16_t ns = (1 << mq->log2_ring_size) - head + mq->last_tail;
1596       head += ns;
1597       MEMIF_MEMORY_BARRIER ();
1598       ring->head = (ring->head + count <= head) ? ring->head + count : head;
1599     }
1600
1601   return MEMIF_ERR_SUCCESS;     /* 0 */
1602 }
1603
1604 int
1605 memif_tx_burst (memif_conn_handle_t conn, uint16_t qid,
1606                 memif_buffer_t * bufs, uint16_t count, uint16_t * tx)
1607 {
1608   memif_connection_t *c = (memif_connection_t *) conn;
1609   if (EXPECT_FALSE (c == NULL))
1610     return MEMIF_ERR_NOCONN;
1611   if (EXPECT_FALSE (c->fd < 0))
1612     return MEMIF_ERR_DISCONNECTED;
1613   uint8_t num =
1614     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1615     num_s2m_rings;
1616   if (EXPECT_FALSE (qid >= num))
1617     return MEMIF_ERR_QID;
1618   if (EXPECT_FALSE (!tx))
1619     return MEMIF_ERR_INVAL_ARG;
1620
1621   memif_queue_t *mq = &c->tx_queues[qid];
1622   memif_ring_t *ring = mq->ring;
1623   uint16_t slot;
1624
1625   slot = (c->args.is_master) ? ring->tail : ring->head;
1626   *tx = (count <= mq->alloc_bufs) ? count : mq->alloc_bufs;
1627
1628 #ifdef MEMIF_DBG_SHM
1629   uint16_t curr_buf = 0;
1630   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1631   memif_buffer_t *b0;
1632   for (curr_buf = 0; curr_buf < count; curr_buf++)
1633     {
1634       b0 = (bufs + curr_buf);
1635       print_bytes (memif_get_buffer (c, ring, b0->desc_index & mask),
1636                    ring->desc[b0->desc_index & mask].length, DBG_TX_BUF);
1637
1638     }
1639 #endif /* MEMIF_DBG_SHM */
1640
1641   MEMIF_MEMORY_BARRIER ();
1642   if (c->args.is_master)
1643     ring->tail = slot + *tx;
1644   else
1645     ring->head = slot + *tx;
1646
1647   /* zero out buffer fields so the client cant modify transmitted data */
1648   memset (bufs, 0, sizeof (memif_buffer_t) * *tx);
1649
1650   mq->alloc_bufs -= *tx;
1651
1652   if ((ring->flags & MEMIF_RING_FLAG_MASK_INT) == 0)
1653     {
1654       uint64_t a = 1;
1655       int r = write (mq->int_fd, &a, sizeof (a));
1656       if (r < 0)
1657         return MEMIF_ERR_INT_WRITE;
1658     }
1659
1660   return MEMIF_ERR_SUCCESS;     /* 0 */
1661 }
1662
1663 int
1664 memif_rx_burst (memif_conn_handle_t conn, uint16_t qid,
1665                 memif_buffer_t * bufs, uint16_t count, uint16_t * rx)
1666 {
1667   memif_connection_t *c = (memif_connection_t *) conn;
1668   if (EXPECT_FALSE (c == NULL))
1669     return MEMIF_ERR_NOCONN;
1670   if (EXPECT_FALSE (c->fd < 0))
1671     return MEMIF_ERR_DISCONNECTED;
1672   uint8_t num =
1673     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1674     num_m2s_rings;
1675   if (EXPECT_FALSE (qid >= num))
1676     return MEMIF_ERR_QID;
1677   if (EXPECT_FALSE (!rx))
1678     return MEMIF_ERR_INVAL_ARG;
1679
1680   memif_queue_t *mq = &c->rx_queues[qid];
1681   memif_ring_t *ring = mq->ring;
1682   uint16_t cur_slot, last_slot;
1683   uint16_t ns;
1684   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1685   memif_buffer_t *b0, *b1;
1686   *rx = 0;
1687
1688   uint64_t b;
1689   ssize_t r = read (mq->int_fd, &b, sizeof (b));
1690   if ((r == -1) && (errno != EAGAIN))
1691     return memif_syscall_error_handler (errno);
1692
1693   cur_slot = (c->args.is_master) ? mq->last_head : mq->last_tail;
1694   last_slot = (c->args.is_master) ? ring->head : ring->tail;
1695   if (cur_slot == last_slot)
1696     return MEMIF_ERR_SUCCESS;
1697
1698   ns = last_slot - cur_slot;
1699
1700   while (ns && count)
1701     {
1702       b0 = (bufs + *rx);
1703
1704       b0->desc_index = cur_slot;
1705       b0->data = memif_get_buffer (c, ring, cur_slot & mask);
1706       b0->len = ring->desc[cur_slot & mask].length;
1707       /* slave resets buffer length */
1708       if (c->args.is_master == 0)
1709         {
1710           ring->desc[cur_slot & mask].length = c->run_args.buffer_size;
1711         }
1712       if (ring->desc[cur_slot & mask].flags & MEMIF_DESC_FLAG_NEXT)
1713         {
1714           b0->flags = MEMIF_BUFFER_FLAG_NEXT;
1715           ring->desc[cur_slot & mask].flags &= ~MEMIF_DESC_FLAG_NEXT;
1716         }
1717
1718 #ifdef MEMIF_DBG_SHM
1719       print_bytes (b0->data, b0->len, DBG_RX_BUF);
1720 #endif /* MEMIF_DBG_SHM */
1721       ns--;
1722       *rx += 1;
1723
1724       count--;
1725       cur_slot++;
1726     }
1727
1728   if (c->args.is_master)
1729     mq->last_head = cur_slot;
1730   else
1731     mq->last_tail = cur_slot;
1732
1733   if (ns)
1734     {
1735       DBG ("not enough buffers!");
1736       return MEMIF_ERR_NOBUF;
1737     }
1738
1739   return MEMIF_ERR_SUCCESS;     /* 0 */
1740 }
1741
1742 int
1743 memif_get_details (memif_conn_handle_t conn, memif_details_t * md,
1744                    char *buf, ssize_t buflen)
1745 {
1746   libmemif_main_t *lm = &libmemif_main;
1747   memif_connection_t *c = (memif_connection_t *) conn;
1748   if (c == NULL)
1749     return MEMIF_ERR_NOCONN;
1750
1751   int err = MEMIF_ERR_SUCCESS, i;
1752   ssize_t l0, l1, total_l;
1753   l0 = 0;
1754
1755   l1 = strlen ((char *) c->args.interface_name);
1756   if (l0 + l1 < buflen)
1757     {
1758       md->if_name = strcpy (buf + l0, (char *) c->args.interface_name);
1759       l0 += l1 + 1;
1760     }
1761   else
1762     err = MEMIF_ERR_NOBUF_DET;
1763
1764   l1 = strlen ((char *) lm->app_name);
1765   if (l0 + l1 < buflen)
1766     {
1767       md->inst_name = strcpy (buf + l0, (char *) lm->app_name);
1768       l0 += l1 + 1;
1769     }
1770   else
1771     err = MEMIF_ERR_NOBUF_DET;
1772
1773   l1 = strlen ((char *) c->remote_if_name);
1774   if (l0 + l1 < buflen)
1775     {
1776       md->remote_if_name = strcpy (buf + l0, (char *) c->remote_if_name);
1777       l0 += l1 + 1;
1778     }
1779   else
1780     err = MEMIF_ERR_NOBUF_DET;
1781
1782   l1 = strlen ((char *) c->remote_name);
1783   if (l0 + l1 < buflen)
1784     {
1785       md->remote_inst_name = strcpy (buf + l0, (char *) c->remote_name);
1786       l0 += l1 + 1;
1787     }
1788   else
1789     err = MEMIF_ERR_NOBUF_DET;
1790
1791   md->id = c->args.interface_id;
1792
1793   if (c->args.secret)
1794     {
1795       l1 = strlen ((char *) c->args.secret);
1796       if (l0 + l1 < buflen)
1797         {
1798           md->secret = strcpy (buf + l0, (char *) c->args.secret);
1799           l0 += l1 + 1;
1800         }
1801       else
1802         err = MEMIF_ERR_NOBUF_DET;
1803     }
1804
1805   md->role = (c->args.is_master) ? 0 : 1;
1806   md->mode = c->args.mode;
1807
1808   l1 = strlen ((char *) c->args.socket_filename);
1809   if (l0 + l1 < buflen)
1810     {
1811       md->socket_filename =
1812         strcpy (buf + l0, (char *) c->args.socket_filename);
1813       l0 += l1 + 1;
1814     }
1815   else
1816     err = MEMIF_ERR_NOBUF_DET;
1817
1818   md->rx_queues_num =
1819     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1820     num_m2s_rings;
1821
1822   l1 = sizeof (memif_queue_details_t) * md->rx_queues_num;
1823   if (l0 + l1 <= buflen)
1824     {
1825       md->rx_queues = (memif_queue_details_t *) buf + l0;
1826       l0 += l1;
1827     }
1828   else
1829     err = MEMIF_ERR_NOBUF_DET;
1830
1831   for (i = 0; i < md->rx_queues_num; i++)
1832     {
1833       md->rx_queues[i].qid = i;
1834       md->rx_queues[i].ring_size = (1 << c->rx_queues[i].log2_ring_size);
1835       md->rx_queues[i].flags = c->rx_queues[i].ring->flags;
1836       md->rx_queues[i].head = c->rx_queues[i].ring->head;
1837       md->rx_queues[i].tail = c->rx_queues[i].ring->tail;
1838       md->rx_queues[i].buffer_size = c->run_args.buffer_size;
1839     }
1840
1841   md->tx_queues_num =
1842     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1843     num_s2m_rings;
1844
1845   l1 = sizeof (memif_queue_details_t) * md->tx_queues_num;
1846   if (l0 + l1 <= buflen)
1847     {
1848       md->tx_queues = (memif_queue_details_t *) buf + l0;
1849       l0 += l1;
1850     }
1851   else
1852     err = MEMIF_ERR_NOBUF_DET;
1853
1854   for (i = 0; i < md->tx_queues_num; i++)
1855     {
1856       md->tx_queues[i].qid = i;
1857       md->tx_queues[i].ring_size = (1 << c->tx_queues[i].log2_ring_size);
1858       md->tx_queues[i].flags = c->tx_queues[i].ring->flags;
1859       md->tx_queues[i].head = c->tx_queues[i].ring->head;
1860       md->tx_queues[i].tail = c->tx_queues[i].ring->tail;
1861       md->tx_queues[i].buffer_size = c->run_args.buffer_size;
1862     }
1863
1864   md->link_up_down = (c->fd > 0) ? 1 : 0;
1865
1866   return err;                   /* 0 */
1867 }
1868
1869 int
1870 memif_get_queue_efd (memif_conn_handle_t conn, uint16_t qid, int *efd)
1871 {
1872   memif_connection_t *c = (memif_connection_t *) conn;
1873   *efd = -1;
1874   if (c == NULL)
1875     return MEMIF_ERR_NOCONN;
1876   if (c->fd < 0)
1877     return MEMIF_ERR_DISCONNECTED;
1878   uint8_t num =
1879     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1880     num_m2s_rings;
1881   if (qid >= num)
1882     return MEMIF_ERR_QID;
1883
1884   *efd = c->rx_queues[qid].int_fd;
1885
1886   return MEMIF_ERR_SUCCESS;
1887 }
1888
1889 int
1890 memif_cleanup ()
1891 {
1892   libmemif_main_t *lm = &libmemif_main;
1893   if (lm->control_list)
1894     lm->free (lm->control_list);
1895   lm->control_list = NULL;
1896   if (lm->interrupt_list)
1897     lm->free (lm->interrupt_list);
1898   lm->interrupt_list = NULL;
1899   if (lm->listener_list)
1900     lm->free (lm->listener_list);
1901   lm->listener_list = NULL;
1902   if (lm->pending_list)
1903     lm->free (lm->pending_list);
1904   lm->pending_list = NULL;
1905   if (poll_cancel_fd != -1)
1906     close (poll_cancel_fd);
1907
1908   return MEMIF_ERR_SUCCESS;     /* 0 */
1909 }