libmemif: fix clang compilation errors/warnings
[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 ((l = strlen ((char *) args->secret)) > 0)
690     {
691       strncpy ((char *) conn->args.secret, (char *) args->secret, l);
692     }
693
694   if (conn->args.is_master)
695     {
696       conn->run_args.buffer_size = conn->args.buffer_size;
697       memif_socket_t *ms;
698       memif_list_elt_t elt;
699       for (i = 0; i < lm->listener_list_len; i++)
700         {
701           if ((ms =
702                (memif_socket_t *) lm->listener_list[i].data_struct) != NULL)
703             {
704               if (strncmp
705                   ((char *) ms->filename, (char *) conn->args.socket_filename,
706                    strlen ((char *) ms->filename)) == 0)
707                 {
708                   /* add interface to listener socket */
709                   elt.key = conn->args.interface_id;
710                   *c = elt.data_struct = conn;
711                   add_list_elt (&elt, &ms->interface_list,
712                                 &ms->interface_list_len);
713                   ms->use_count++;
714                   conn->listener_fd = ms->fd;
715                   break;
716                 }
717             }
718           else
719             {
720               struct stat file_stat;
721               if (stat ((char *) conn->args.socket_filename, &file_stat) == 0)
722                 {
723                   if (S_ISSOCK (file_stat.st_mode))
724                     unlink ((char *) conn->args.socket_filename);
725                   else
726                     return memif_syscall_error_handler (errno);
727                 }
728               DBG ("creating socket file");
729               ms = lm->alloc (sizeof (memif_socket_t));
730               if (ms == NULL)
731                 {
732                   err = MEMIF_ERR_NOMEM;
733                   goto error;
734                 }
735               ms->filename =
736                 lm->alloc (strlen ((char *) conn->args.socket_filename) +
737                            sizeof (char));
738               if (ms->filename == NULL)
739                 {
740                   err = MEMIF_ERR_NOMEM;
741                   goto error;
742                 }
743               memset (ms->filename, 0,
744                       strlen ((char *) conn->args.socket_filename) +
745                       sizeof (char));
746               strncpy ((char *) ms->filename,
747                        (char *) conn->args.socket_filename,
748                        strlen ((char *) conn->args.socket_filename));
749               ms->interface_list_len = 1;
750               ms->interface_list =
751                 lm->alloc (sizeof (memif_list_elt_t) *
752                            ms->interface_list_len);
753               if (ms->interface_list == NULL)
754                 {
755                   err = MEMIF_ERR_NOMEM;
756                   goto error;
757                 }
758               ms->interface_list[0].key = -1;
759               ms->interface_list[0].data_struct = NULL;
760               struct sockaddr_un un = { 0 };
761               int on = 1;
762
763               ms->fd = socket (AF_UNIX, SOCK_SEQPACKET, 0);
764               if (ms->fd < 0)
765                 {
766                   err = memif_syscall_error_handler (errno);
767                   goto error;
768                 }
769               DBG ("socket %d created", ms->fd);
770               un.sun_family = AF_UNIX;
771               strncpy ((char *) un.sun_path, (char *) ms->filename,
772                        sizeof (un.sun_path) - 1);
773               DBG ("sockopt");
774               if (setsockopt
775                   (ms->fd, SOL_SOCKET, SO_PASSCRED, &on, sizeof (on)) < 0)
776                 {
777                   err = memif_syscall_error_handler (errno);
778                   goto error;
779                 }
780               DBG ("bind");
781               if (bind (ms->fd, (struct sockaddr *) &un, sizeof (un)) < 0)
782                 {
783                   err = memif_syscall_error_handler (errno);
784                   goto error;
785                 }
786               DBG ("listen");
787               if (listen (ms->fd, 1) < 0)
788                 {
789                   err = memif_syscall_error_handler (errno);
790                   goto error;
791                 }
792               DBG ("stat");
793               if (stat ((char *) ms->filename, &file_stat) < 0)
794                 {
795                   err = memif_syscall_error_handler (errno);
796                   goto error;
797                 }
798
799               /* add interface to listener socket */
800               elt.key = conn->args.interface_id;
801               *c = elt.data_struct = conn;
802               add_list_elt (&elt, &ms->interface_list,
803                             &ms->interface_list_len);
804               ms->use_count = 1;
805               conn->listener_fd = ms->fd;
806
807               /* add listener socket to libmemif main */
808               elt.key = ms->fd;
809               elt.data_struct = ms;
810               add_list_elt (&elt, &lm->listener_list, &lm->listener_list_len);
811               lm->control_fd_update (ms->fd, MEMIF_FD_EVENT_READ);
812               break;
813             }
814         }
815     }
816   else
817     {
818       if (lm->disconn_slaves == 0)
819         {
820           if (timerfd_settime (lm->timerfd, 0, &lm->arm, NULL) < 0)
821             {
822               err = memif_syscall_error_handler (errno);
823               goto error;
824             }
825         }
826
827       lm->disconn_slaves++;
828
829       list_elt.key = -1;
830       *c = list_elt.data_struct = conn;
831       if ((index =
832            add_list_elt (&list_elt, &lm->control_list,
833                          &lm->control_list_len)) < 0)
834         {
835           err = MEMIF_ERR_NOMEM;
836           goto error;
837         }
838     }
839
840   conn->index = index;
841
842   return 0;
843
844 error:
845   if (sockfd > 0)
846     close (sockfd);
847   sockfd = -1;
848   if (conn->args.socket_filename)
849     lm->free (conn->args.socket_filename);
850   if (conn != NULL)
851     lm->free (conn);
852   *c = conn = NULL;
853   return err;
854 }
855
856 int
857 memif_control_fd_handler (int fd, uint8_t events)
858 {
859   int i, rv, sockfd = -1, err = MEMIF_ERR_SUCCESS;      /* 0 */
860   uint16_t num;
861   memif_list_elt_t *e = NULL;
862   memif_connection_t *conn;
863   libmemif_main_t *lm = &libmemif_main;
864   if (fd == lm->timerfd)
865     {
866       uint64_t b;
867       ssize_t size;
868       size = read (fd, &b, sizeof (b));
869       for (i = 0; i < lm->control_list_len; i++)
870         {
871           if ((lm->control_list[i].key < 0)
872               && (lm->control_list[i].data_struct != NULL))
873             {
874               conn = lm->control_list[i].data_struct;
875               if (conn->args.is_master)
876                 continue;
877
878               struct sockaddr_un sun;
879               sockfd = socket (AF_UNIX, SOCK_SEQPACKET, 0);
880               if (sockfd < 0)
881                 {
882                   err = memif_syscall_error_handler (errno);
883                   goto error;
884                 }
885
886               sun.sun_family = AF_UNIX;
887
888               strncpy (sun.sun_path, (char*) conn->args.socket_filename,
889                        sizeof (sun.sun_path) - 1);
890
891               if (connect (sockfd, (struct sockaddr *) &sun,
892                            sizeof (struct sockaddr_un)) == 0)
893                 {
894                   conn->fd = sockfd;
895                   conn->read_fn = memif_conn_fd_read_ready;
896                   conn->write_fn = memif_conn_fd_write_ready;
897                   conn->error_fn = memif_conn_fd_error;
898
899                   lm->control_list[conn->index].key = conn->fd;
900
901                   lm->control_fd_update (sockfd,
902                                          MEMIF_FD_EVENT_READ |
903                                          MEMIF_FD_EVENT_WRITE);
904
905                   lm->disconn_slaves--;
906                   if (lm->disconn_slaves == 0)
907                     {
908                       if (timerfd_settime (lm->timerfd, 0, &lm->disarm, NULL)
909                           < 0)
910                         {
911                           err = memif_syscall_error_handler (errno);
912                           goto error;
913                         }
914                     }
915                 }
916               else
917                 {
918                   err = memif_syscall_error_handler (errno);
919                   goto error;
920                 }
921             }
922         }
923     }
924   else
925     {
926       get_list_elt (&e, lm->interrupt_list, lm->interrupt_list_len, fd);
927       if (e != NULL)
928         {
929           if (((memif_connection_t *) e->data_struct)->on_interrupt != NULL)
930             {
931               num =
932                 (((memif_connection_t *) e->data_struct)->args.
933                  is_master) ? ((memif_connection_t *) e->data_struct)->
934                 run_args.num_s2m_rings : ((memif_connection_t *) e->
935                                           data_struct)->run_args.
936                 num_m2s_rings;
937               for (i = 0; i < num; i++)
938                 {
939                   if (((memif_connection_t *) e->data_struct)->rx_queues[i].
940                       int_fd == fd)
941                     {
942                       ((memif_connection_t *) e->
943                        data_struct)->on_interrupt ((void *) e->data_struct,
944                                                    ((memif_connection_t *)
945                                                     e->data_struct)->
946                                                    private_ctx, i);
947                       return MEMIF_ERR_SUCCESS;
948                     }
949                 }
950             }
951           return MEMIF_ERR_SUCCESS;
952         }
953       get_list_elt (&e, lm->listener_list, lm->listener_list_len, fd);
954       if (e != NULL)
955         {
956           memif_conn_fd_accept_ready ((memif_socket_t *) e->data_struct);
957           return MEMIF_ERR_SUCCESS;
958         }
959
960       get_list_elt (&e, lm->pending_list, lm->pending_list_len, fd);
961       if (e != NULL)
962         {
963           memif_read_ready (fd);
964           return MEMIF_ERR_SUCCESS;
965         }
966
967       get_list_elt (&e, lm->control_list, lm->control_list_len, fd);
968       if (e != NULL)
969         {
970           if (events & MEMIF_FD_EVENT_READ)
971             {
972               err =
973                 ((memif_connection_t *) e->data_struct)->read_fn (e->
974                                                                   data_struct);
975               if (err != MEMIF_ERR_SUCCESS)
976                 return err;
977             }
978           if (events & MEMIF_FD_EVENT_WRITE)
979             {
980               err =
981                 ((memif_connection_t *) e->data_struct)->write_fn (e->
982                                                                    data_struct);
983               if (err != MEMIF_ERR_SUCCESS)
984                 return err;
985             }
986           if (events & MEMIF_FD_EVENT_ERROR)
987             {
988               err =
989                 ((memif_connection_t *) e->data_struct)->error_fn (e->
990                                                                    data_struct);
991               if (err != MEMIF_ERR_SUCCESS)
992                 return err;
993             }
994         }
995     }
996
997   return MEMIF_ERR_SUCCESS;     /* 0 */
998
999 error:
1000   if (sockfd > 0)
1001     close (sockfd);
1002   sockfd = -1;
1003   return err;
1004 }
1005
1006 int
1007 memif_poll_event (int timeout)
1008 {
1009   libmemif_main_t *lm = &libmemif_main;
1010   memif_list_elt_t *elt;
1011   struct epoll_event evt, *e;
1012   int en = 0, err = MEMIF_ERR_SUCCESS, i = 0;   /* 0 */
1013   uint16_t num;
1014   uint32_t events = 0;
1015   uint64_t counter = 0;
1016   ssize_t r = 0;
1017   memset (&evt, 0, sizeof (evt));
1018   evt.events = EPOLLIN | EPOLLOUT;
1019   sigset_t sigset;
1020   sigemptyset (&sigset);
1021   en = epoll_pwait (memif_epfd, &evt, 1, timeout, &sigset);
1022   if (en < 0)
1023     {
1024       err = errno;
1025       DBG ("epoll_pwait: %s", strerror (err));
1026       return memif_syscall_error_handler (err);
1027     }
1028   if (en > 0)
1029     {
1030       if (evt.data.fd == poll_cancel_fd)
1031         {
1032           r = read (evt.data.fd, &counter, sizeof (counter));
1033           return MEMIF_ERR_POLL_CANCEL;
1034         }
1035       if (evt.events & EPOLLIN)
1036         events |= MEMIF_FD_EVENT_READ;
1037       if (evt.events & EPOLLOUT)
1038         events |= MEMIF_FD_EVENT_WRITE;
1039       if (evt.events & EPOLLERR)
1040         events |= MEMIF_FD_EVENT_ERROR;
1041       err = memif_control_fd_handler (evt.data.fd, events);
1042       return err;
1043     }
1044   return 0;
1045 }
1046
1047 int
1048 memif_cancel_poll_event ()
1049 {
1050   uint64_t counter = 1;
1051   ssize_t w = 0;
1052
1053   if (poll_cancel_fd == -1)
1054     return 0;
1055   w = write (poll_cancel_fd, &counter, sizeof (counter));
1056   if (w < sizeof (counter))
1057     return MEMIF_ERR_INT_WRITE;
1058
1059   return 0;
1060 }
1061
1062 static void
1063 memif_msg_queue_free (libmemif_main_t * lm, memif_msg_queue_elt_t ** e)
1064 {
1065   if (*e == NULL)
1066     return;
1067   memif_msg_queue_free (lm, &(*e)->next);
1068   lm->free (*e);
1069   *e = NULL;
1070   return;
1071 }
1072
1073 /* send disconnect msg and close interface */
1074 int
1075 memif_disconnect_internal (memif_connection_t * c)
1076 {
1077   if (c == NULL)
1078     {
1079       DBG ("no connection");
1080       return MEMIF_ERR_NOCONN;
1081     }
1082   uint16_t num;
1083   int err = MEMIF_ERR_SUCCESS, i;       /* 0 */
1084   memif_queue_t *mq;
1085   libmemif_main_t *lm = &libmemif_main;
1086   memif_list_elt_t *e;
1087
1088   c->on_disconnect ((void *) c, c->private_ctx);
1089
1090   if (c->fd > 0)
1091     {
1092       memif_msg_send_disconnect (c->fd, (uint8_t *) "interface deleted", 0);
1093       lm->control_fd_update (c->fd, MEMIF_FD_EVENT_DEL);
1094       close (c->fd);
1095     }
1096   get_list_elt (&e, lm->control_list, lm->control_list_len, c->fd);
1097   if (e != NULL)
1098     {
1099       if (c->args.is_master)
1100         free_list_elt (lm->control_list, lm->control_list_len, c->fd);
1101       e->key = c->fd = -1;
1102     }
1103
1104   if (c->tx_queues != NULL)
1105     {
1106       num =
1107         (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1108         num_s2m_rings;
1109       for (i = 0; i < num; i++)
1110         {
1111           mq = &c->tx_queues[i];
1112           if (mq != NULL)
1113             {
1114               if (mq->int_fd > 0)
1115                 close (mq->int_fd);
1116               free_list_elt (lm->interrupt_list, lm->interrupt_list_len,
1117                              mq->int_fd);
1118               mq->int_fd = -1;
1119             }
1120         }
1121       lm->free (c->tx_queues);
1122       c->tx_queues = NULL;
1123     }
1124
1125   if (c->rx_queues != NULL)
1126     {
1127       num =
1128         (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1129         num_m2s_rings;
1130       for (i = 0; i < num; i++)
1131         {
1132           mq = &c->rx_queues[i];
1133           if (mq != NULL)
1134             {
1135               if (mq->int_fd > 0)
1136                 {
1137                   if (c->on_interrupt != NULL)
1138                     lm->control_fd_update (mq->int_fd, MEMIF_FD_EVENT_DEL);
1139                   close (mq->int_fd);
1140                 }
1141               free_list_elt (lm->interrupt_list, lm->interrupt_list_len,
1142                              mq->int_fd);
1143               mq->int_fd = -1;
1144             }
1145         }
1146       lm->free (c->rx_queues);
1147       c->rx_queues = NULL;
1148     }
1149
1150   if (c->regions != NULL)
1151     {
1152       if (munmap (c->regions[0].shm, c->regions[0].region_size) < 0)
1153         return memif_syscall_error_handler (errno);
1154       if (c->regions[0].fd > 0)
1155         close (c->regions[0].fd);
1156       c->regions[0].fd = -1;
1157       lm->free (c->regions);
1158       c->regions = NULL;
1159     }
1160
1161   memset (&c->run_args, 0, sizeof (memif_conn_run_args_t));
1162
1163   memif_msg_queue_free (lm, &c->msg_queue);
1164
1165   if (!(c->args.is_master))
1166     {
1167       if (lm->disconn_slaves == 0)
1168         {
1169           if (timerfd_settime (lm->timerfd, 0, &lm->arm, NULL) < 0)
1170             {
1171               err = memif_syscall_error_handler (errno);
1172               DBG ("timerfd_settime: arm");
1173             }
1174         }
1175       lm->disconn_slaves++;
1176     }
1177
1178   return err;
1179 }
1180
1181 int
1182 memif_delete (memif_conn_handle_t * conn)
1183 {
1184   memif_connection_t *c = (memif_connection_t *) * conn;
1185   if (c == NULL)
1186     {
1187       DBG ("no connection");
1188       return MEMIF_ERR_NOCONN;
1189     }
1190   libmemif_main_t *lm = &libmemif_main;
1191   memif_list_elt_t *e = NULL;
1192   memif_socket_t *ms = NULL;
1193
1194   int err = MEMIF_ERR_SUCCESS;
1195
1196   if (c->fd > 0)
1197     {
1198       DBG ("DISCONNECTING");
1199       err = memif_disconnect_internal (c);
1200       if (err == MEMIF_ERR_NOCONN)
1201         return err;
1202     }
1203
1204   free_list_elt_ctx (lm->control_list, lm->control_list_len, c);
1205
1206   if (c->args.is_master)
1207     {
1208       get_list_elt (&e, lm->listener_list, lm->listener_list_len,
1209                     c->listener_fd);
1210       if (e != NULL)
1211         {
1212           ms = (memif_socket_t *) e->data_struct;
1213           ms->use_count--;
1214           free_list_elt (ms->interface_list, ms->interface_list_len,
1215                          c->args.interface_id);
1216           if (ms->use_count <= 0)
1217             {
1218               lm->control_fd_update (c->listener_fd, MEMIF_FD_EVENT_DEL);
1219               free_list_elt (lm->listener_list, lm->listener_list_len,
1220                              c->listener_fd);
1221               close (c->listener_fd);
1222               c->listener_fd = ms->fd = -1;
1223               lm->free (ms->interface_list);
1224               ms->interface_list = NULL;
1225               lm->free (ms->filename);
1226               ms->filename = NULL;
1227               lm->free (ms);
1228               ms = NULL;
1229             }
1230         }
1231     }
1232   else
1233     {
1234       lm->disconn_slaves--;
1235       if (lm->disconn_slaves <= 0)
1236         {
1237           if (timerfd_settime (lm->timerfd, 0, &lm->disarm, NULL) < 0)
1238             {
1239               err = memif_syscall_error_handler (errno);
1240               DBG ("timerfd_settime: disarm");
1241             }
1242         }
1243     }
1244
1245   if (c->args.socket_filename)
1246     lm->free (c->args.socket_filename);
1247   c->args.socket_filename = NULL;
1248
1249   lm->free (c);
1250   c = NULL;
1251
1252   *conn = c;
1253   return err;
1254 }
1255
1256 int
1257 memif_connect1 (memif_connection_t * c)
1258 {
1259   libmemif_main_t *lm = &libmemif_main;
1260   memif_region_t *mr = c->regions;
1261   memif_queue_t *mq;
1262   int i;
1263   uint16_t num;
1264
1265   if (mr != NULL)
1266     {
1267       if (!mr->shm)
1268         {
1269           if (mr->fd < 0)
1270             return MEMIF_ERR_NO_SHMFD;
1271
1272           if ((mr->shm = mmap (NULL, mr->region_size, PROT_READ | PROT_WRITE,
1273                                MAP_SHARED, mr->fd, 0)) == MAP_FAILED)
1274             {
1275               return memif_syscall_error_handler (errno);
1276             }
1277         }
1278     }
1279
1280   num =
1281     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1282     num_s2m_rings;
1283   for (i = 0; i < num; i++)
1284     {
1285       mq = &c->tx_queues[i];
1286       if (mq != NULL)
1287         {
1288           mq->ring = c->regions[mq->region].shm + mq->offset;
1289           if (mq->ring->cookie != MEMIF_COOKIE)
1290             {
1291               DBG ("wrong cookie on tx ring %u", i);
1292               return MEMIF_ERR_COOKIE;
1293             }
1294           mq->ring->head = mq->ring->tail = mq->last_head = mq->alloc_bufs =
1295             0;
1296         }
1297     }
1298   num =
1299     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1300     num_m2s_rings;
1301   for (i = 0; i < num; i++)
1302     {
1303       mq = &c->rx_queues[i];
1304       if (mq != NULL)
1305         {
1306           mq->ring = c->regions[mq->region].shm + mq->offset;
1307           if (mq->ring->cookie != MEMIF_COOKIE)
1308             {
1309               DBG ("wrong cookie on rx ring %u", i);
1310               return MEMIF_ERR_COOKIE;
1311             }
1312           mq->ring->head = mq->ring->tail = mq->last_head = mq->alloc_bufs =
1313             0;
1314         }
1315     }
1316
1317   lm->control_fd_update (c->fd, MEMIF_FD_EVENT_READ | MEMIF_FD_EVENT_MOD);
1318
1319   return 0;
1320 }
1321
1322 int
1323 memif_init_regions_and_queues (memif_connection_t * conn)
1324 {
1325   memif_ring_t *ring = NULL;
1326   memif_region_t *r;
1327   int i, j;
1328   libmemif_main_t *lm = &libmemif_main;
1329   memif_list_elt_t e;
1330
1331   conn->regions = (memif_region_t *) lm->alloc (sizeof (memif_region_t));
1332   if (conn->regions == NULL)
1333     return MEMIF_ERR_NOMEM;
1334   r = conn->regions;
1335
1336   r->buffer_offset =
1337     (conn->run_args.num_s2m_rings +
1338      conn->run_args.num_m2s_rings) * (sizeof (memif_ring_t) +
1339                                       sizeof (memif_desc_t) *
1340                                       (1 << conn->run_args.log2_ring_size));
1341
1342   r->region_size = r->buffer_offset +
1343     conn->run_args.buffer_size * (1 << conn->run_args.log2_ring_size) *
1344     (conn->run_args.num_s2m_rings + conn->run_args.num_m2s_rings);
1345
1346   if ((r->fd =
1347        memfd_create ("memif region 0", MFD_ALLOW_SEALING)) == -1)
1348   if ((r->fd = memfd_create ("memif region 0", MFD_ALLOW_SEALING)) == -1)
1349     return memif_syscall_error_handler (errno);
1350
1351   if ((fcntl (r->fd, F_ADD_SEALS, F_SEAL_SHRINK)) == -1)
1352     return memif_syscall_error_handler (errno);
1353
1354   if ((ftruncate (r->fd, r->region_size)) == -1)
1355     return memif_syscall_error_handler (errno);
1356
1357   if ((r->shm = mmap (NULL, r->region_size, PROT_READ | PROT_WRITE,
1358                       MAP_SHARED, r->fd, 0)) == MAP_FAILED)
1359     return memif_syscall_error_handler (errno);
1360
1361   for (i = 0; i < conn->run_args.num_s2m_rings; i++)
1362     {
1363       ring = memif_get_ring (conn, MEMIF_RING_S2M, i);
1364       DBG ("RING: %p I: %d", ring, i);
1365       ring->head = ring->tail = 0;
1366       ring->cookie = MEMIF_COOKIE;
1367       ring->flags = 0;
1368       for (j = 0; j < (1 << conn->run_args.log2_ring_size); j++)
1369         {
1370           uint16_t slot = i * (1 << conn->run_args.log2_ring_size) + j;
1371           ring->desc[j].region = 0;
1372           ring->desc[j].offset = r->buffer_offset +
1373             (uint32_t) (slot * conn->run_args.buffer_size);
1374           ring->desc[j].length = conn->run_args.buffer_size;
1375         }
1376     }
1377   for (i = 0; i < conn->run_args.num_m2s_rings; i++)
1378     {
1379       ring = memif_get_ring (conn, MEMIF_RING_M2S, i);
1380       DBG ("RING: %p I: %d", ring, i);
1381       ring->head = ring->tail = 0;
1382       ring->cookie = MEMIF_COOKIE;
1383       ring->flags = 0;
1384       for (j = 0; j < (1 << conn->run_args.log2_ring_size); j++)
1385         {
1386           uint16_t slot =
1387             (i +
1388              conn->run_args.num_s2m_rings) *
1389             (1 << conn->run_args.log2_ring_size) + j;
1390           ring->desc[j].region = 0;
1391           ring->desc[j].offset = r->buffer_offset +
1392             (uint32_t) (slot * conn->run_args.buffer_size);
1393           ring->desc[j].length = conn->run_args.buffer_size;
1394         }
1395     }
1396   memif_queue_t *mq;
1397   mq =
1398     (memif_queue_t *) lm->alloc (sizeof (memif_queue_t) *
1399                                  conn->run_args.num_s2m_rings);
1400   if (mq == NULL)
1401     return MEMIF_ERR_NOMEM;
1402   int x;
1403   for (x = 0; x < conn->run_args.num_s2m_rings; x++)
1404     {
1405       if ((mq[x].int_fd = eventfd (0, EFD_NONBLOCK)) < 0)
1406         return memif_syscall_error_handler (errno);
1407       /* add int fd to interrupt fd list */
1408       e.key = mq[x].int_fd;
1409       e.data_struct = conn;
1410       add_list_elt (&e, &lm->interrupt_list, &lm->interrupt_list_len);
1411
1412       mq[x].ring = memif_get_ring (conn, MEMIF_RING_S2M, x);
1413       DBG ("RING: %p I: %d", mq[x].ring, x);
1414       mq[x].log2_ring_size = conn->run_args.log2_ring_size;
1415       mq[x].region = 0;
1416       mq[x].offset =
1417         (void *) mq[x].ring - (void *) conn->regions[mq->region].shm;
1418       mq[x].last_head = 0;
1419       mq[x].alloc_bufs = 0;
1420     }
1421   conn->tx_queues = mq;
1422
1423   mq =
1424     (memif_queue_t *) lm->alloc (sizeof (memif_queue_t) *
1425                                  conn->run_args.num_m2s_rings);
1426   if (mq == NULL)
1427     return MEMIF_ERR_NOMEM;
1428   for (x = 0; x < conn->run_args.num_m2s_rings; x++)
1429     {
1430       if ((mq[x].int_fd = eventfd (0, EFD_NONBLOCK)) < 0)
1431         return memif_syscall_error_handler (errno);
1432       /* add int fd to interrupt fd list */
1433       e.key = mq[x].int_fd;
1434       e.data_struct = conn;
1435       add_list_elt (&e, &lm->interrupt_list, &lm->interrupt_list_len);
1436
1437       mq[x].ring = memif_get_ring (conn, MEMIF_RING_M2S, x);
1438       DBG ("RING: %p I: %d", mq[x].ring, x);
1439       mq[x].log2_ring_size = conn->run_args.log2_ring_size;
1440       mq[x].region = 0;
1441       mq[x].offset =
1442         (void *) mq[x].ring - (void *) conn->regions[mq->region].shm;
1443       mq[x].last_head = 0;
1444       mq[x].alloc_bufs = 0;
1445     }
1446   conn->rx_queues = mq;
1447
1448   return 0;
1449 }
1450
1451 int
1452 memif_buffer_enq_tx (memif_conn_handle_t conn, uint16_t qid,
1453                      memif_buffer_t * bufs, uint16_t count,
1454                      uint16_t * count_out)
1455 {
1456   memif_connection_t *c = (memif_connection_t *) conn;
1457   if (EXPECT_FALSE (c == NULL))
1458     return MEMIF_ERR_NOCONN;
1459   if (EXPECT_FALSE (c->fd < 0))
1460     return MEMIF_ERR_DISCONNECTED;
1461   uint8_t num =
1462     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1463     num_s2m_rings;
1464   if (EXPECT_FALSE (qid >= num))
1465     return MEMIF_ERR_QID;
1466   if (EXPECT_FALSE (!count_out))
1467     return MEMIF_ERR_INVAL_ARG;
1468   if (EXPECT_FALSE (c->args.is_master))
1469     return MEMIF_ERR_INVAL_ARG;
1470
1471   memif_queue_t *mq = &c->tx_queues[qid];
1472   memif_ring_t *ring = mq->ring;
1473   memif_buffer_t *b0;
1474   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1475   uint16_t ring_size;
1476   uint16_t slot, ns;
1477   int i, err = MEMIF_ERR_SUCCESS;       /* 0 */
1478   *count_out = 0;
1479
1480   ring_size = (1 << mq->log2_ring_size);
1481   ns = ring->tail - mq->last_tail;
1482   mq->last_tail += ns;
1483   slot = (c->args.is_master) ? ring->tail : ring->head;
1484   slot += mq->alloc_bufs;
1485
1486   /* can only be called by slave */
1487   ns = ring_size - ring->head + mq->alloc_bufs + mq->last_tail;
1488
1489   b0 = bufs;
1490
1491   while (count && ns)
1492     {
1493       if (EXPECT_FALSE ((b0->flags & MEMIF_BUFFER_FLAG_RX) == 0))
1494         {
1495           /* not a valid buffer */
1496           count--;
1497           continue;
1498         }
1499       b0->flags &= ~MEMIF_BUFFER_FLAG_RX;
1500
1501       ((memif_ring_t *) b0->ring)->desc[b0->desc_index & mask].offset = ring->desc[slot & mask].offset; /* put free buffer on rx ring */
1502
1503       ring->desc[slot & mask].offset =
1504         (uint32_t) (b0->data - c->regions->shm);
1505       ring->desc[slot & mask].flags |=
1506         (b0->flags & MEMIF_BUFFER_FLAG_NEXT) ? MEMIF_DESC_FLAG_NEXT : 0;
1507
1508       b0->desc_index = slot;
1509
1510       mq->alloc_bufs++;
1511       slot++;
1512
1513       count--;
1514       ns--;
1515       b0++;
1516       *count_out += 1;
1517     }
1518
1519   DBG ("allocated: %u/%u bufs. Total %u allocated bufs", *count_out, count,
1520        mq->alloc_bufs);
1521
1522   if (count)
1523     {
1524       DBG ("ring buffer full! qid: %u", qid);
1525       err = MEMIF_ERR_NOBUF_RING;
1526     }
1527
1528 error:
1529   return err;
1530 }
1531
1532 int
1533 memif_buffer_alloc (memif_conn_handle_t conn, uint16_t qid,
1534                     memif_buffer_t * bufs, uint16_t count,
1535                     uint16_t * count_out, uint16_t size)
1536 {
1537   memif_connection_t *c = (memif_connection_t *) conn;
1538   if (EXPECT_FALSE (c == NULL))
1539     return MEMIF_ERR_NOCONN;
1540   if (EXPECT_FALSE (c->fd < 0))
1541     return MEMIF_ERR_DISCONNECTED;
1542   uint8_t num =
1543     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1544     num_s2m_rings;
1545   if (EXPECT_FALSE (qid >= num))
1546     return MEMIF_ERR_QID;
1547   if (EXPECT_FALSE (!count_out))
1548     return MEMIF_ERR_INVAL_ARG;
1549
1550   memif_queue_t *mq = &c->tx_queues[qid];
1551   memif_ring_t *ring = mq->ring;
1552   memif_buffer_t *b0, *b1;
1553   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1554   uint16_t ring_size;
1555   uint16_t slot, ns;
1556   int i, err = MEMIF_ERR_SUCCESS;       /* 0 */
1557   uint16_t dst_left, src_left;
1558   uint16_t saved_count;
1559   memif_buffer_t *saved_b;
1560   *count_out = 0;
1561
1562   ring_size = (1 << mq->log2_ring_size);
1563   ns = ring->tail - mq->last_tail;
1564   mq->last_tail += ns;
1565   slot = (c->args.is_master) ? ring->tail : ring->head;
1566   slot += mq->alloc_bufs;
1567
1568   if (c->args.is_master)
1569     ns = ring->head + mq->alloc_bufs - ring->tail;
1570   else
1571     ns = ring_size - ring->head + mq->alloc_bufs + mq->last_tail;
1572
1573   while (count && ns)
1574     {
1575       b0 = (bufs + *count_out);
1576
1577       saved_b = b0;
1578       saved_count = count;
1579
1580       b0->desc_index = slot;
1581       ring->desc[slot & mask].flags = 0;
1582
1583       /* slave can produce buffer with original length */
1584       dst_left = (c->args.is_master) ? ring->desc[slot & mask].length :
1585         c->run_args.buffer_size;
1586       src_left = size;
1587
1588       while (src_left)
1589         {
1590           if (EXPECT_FALSE (dst_left == 0))
1591             {
1592               if (count && ns)
1593                 {
1594                   slot++;
1595                   *count_out += 1;
1596                   mq->alloc_bufs++;
1597                   ns--;
1598                   count--;
1599
1600                   ring->desc[b0->desc_index & mask].flags |=
1601                     MEMIF_DESC_FLAG_NEXT;
1602                   b0->flags |= MEMIF_BUFFER_FLAG_NEXT;
1603
1604                   b0 = (bufs + *count_out);
1605                   b0->desc_index = slot;
1606                   dst_left =
1607                     (c->args.is_master) ? ring->desc[slot & mask].length : c->
1608                     run_args.buffer_size;
1609                   ring->desc[slot & mask].flags = 0;
1610                 }
1611               else
1612                 {
1613                   /* rollback allocated chain buffers */
1614                   memset (saved_b, 0, sizeof (memif_buffer_t)
1615                           * (saved_count - count + 1));
1616                   *count_out -= saved_count - count;
1617                   mq->alloc_bufs = saved_count - count;
1618                   goto no_ns;
1619                 }
1620             }
1621           b0->len = memif_min (dst_left, src_left);
1622
1623           /* slave resets buffer offset */
1624           if (c->args.is_master == 0)
1625             {
1626               uint16_t x =
1627                 (ring->desc[slot & mask].offset -
1628                  c->regions->buffer_offset) / c->run_args.buffer_size;
1629               ring->desc[slot & mask].offset =
1630                 c->regions->buffer_offset + (x * c->run_args.buffer_size);
1631             }
1632
1633           b0->data = c->regions->shm + ring->desc[slot & mask].offset;
1634
1635           src_left -= b0->len;
1636           dst_left -= b0->len;
1637         }
1638
1639       slot++;
1640       *count_out += 1;
1641       mq->alloc_bufs++;
1642       ns--;
1643       count--;
1644     }
1645
1646 no_ns:
1647
1648   DBG ("allocated: %u/%u bufs. Total %u allocated bufs", *count_out, count,
1649        mq->alloc_bufs);
1650
1651   if (count)
1652     {
1653       DBG ("ring buffer full! qid: %u", qid);
1654       err = MEMIF_ERR_NOBUF_RING;
1655     }
1656
1657 error:
1658   return err;
1659 }
1660
1661 int
1662 memif_refill_queue (memif_conn_handle_t conn, uint16_t qid, uint16_t count,
1663                     uint16_t headroom)
1664 {
1665   memif_connection_t *c = (memif_connection_t *) conn;
1666   if (EXPECT_FALSE (c == NULL))
1667     return MEMIF_ERR_NOCONN;
1668   if (EXPECT_FALSE (c->fd < 0))
1669     return MEMIF_ERR_DISCONNECTED;
1670   uint8_t num =
1671     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1672     num_m2s_rings;
1673   if (EXPECT_FALSE (qid >= num))
1674     return MEMIF_ERR_QID;
1675   libmemif_main_t *lm = &libmemif_main;
1676   memif_queue_t *mq = &c->rx_queues[qid];
1677   memif_ring_t *ring = mq->ring;
1678   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1679   uint16_t slot;
1680
1681   if (c->args.is_master)
1682     {
1683       MEMIF_MEMORY_BARRIER ();
1684       ring->tail =
1685         (ring->tail + count <=
1686          mq->last_head) ? ring->tail + count : mq->last_head;
1687       return MEMIF_ERR_SUCCESS;
1688     }
1689
1690   uint16_t head = ring->head;
1691   uint16_t ns = (1 << mq->log2_ring_size) - head + mq->last_tail;
1692   head += (count < ns) ? count : ns;
1693
1694   if (headroom)
1695     {
1696       slot = (c->args.is_master) ? ring->head : ring->tail;
1697       while (slot < head)
1698         {
1699           uint16_t x =
1700             (ring->desc[slot & mask].offset -
1701              c->regions->buffer_offset) / c->run_args.buffer_size;
1702           ring->desc[slot & mask].offset =
1703             c->regions->buffer_offset + (x * c->run_args.buffer_size) +
1704             headroom;
1705
1706           slot++;
1707         }
1708     }
1709
1710   MEMIF_MEMORY_BARRIER ();
1711   ring->head = head;
1712
1713   return MEMIF_ERR_SUCCESS;     /* 0 */
1714 }
1715
1716 int
1717 memif_tx_burst (memif_conn_handle_t conn, uint16_t qid,
1718                 memif_buffer_t * bufs, uint16_t count, uint16_t * tx)
1719 {
1720   memif_connection_t *c = (memif_connection_t *) conn;
1721   if (EXPECT_FALSE (c == NULL))
1722     return MEMIF_ERR_NOCONN;
1723   if (EXPECT_FALSE (c->fd < 0))
1724     return MEMIF_ERR_DISCONNECTED;
1725   uint8_t num =
1726     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1727     num_s2m_rings;
1728   if (EXPECT_FALSE (qid >= num))
1729     return MEMIF_ERR_QID;
1730   if (EXPECT_FALSE (!tx))
1731     return MEMIF_ERR_INVAL_ARG;
1732
1733   memif_queue_t *mq = &c->tx_queues[qid];
1734   memif_ring_t *ring = mq->ring;
1735   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1736   memif_buffer_t *b0;
1737   *tx = 0;
1738
1739   if (count > mq->alloc_bufs)
1740     count = mq->alloc_bufs;
1741
1742   if (EXPECT_FALSE (count == 0))
1743     return MEMIF_ERR_SUCCESS;
1744
1745   while (count)
1746     {
1747       b0 = (bufs + *tx);
1748       ring->desc[b0->desc_index & mask].length = b0->len;
1749
1750 #ifdef MEMIF_DBG_SHM
1751       printf ("offset: %-6d\n", ring->desc[b0->desc_index & mask].offset);
1752       printf ("data: %p\n",
1753               memif_get_buffer (c, ring, b0->desc_index & mask));
1754       printf ("index: %u\n", b0->desc_index);
1755       print_bytes (memif_get_buffer (c, ring, b0->desc_index & mask),
1756                    ring->desc[b0->desc_index & mask].length, DBG_TX_BUF);
1757 #endif /* MEMIF_DBG_SHM */
1758
1759       *tx += 1;
1760       count--;
1761     }
1762
1763
1764   MEMIF_MEMORY_BARRIER ();
1765   if (c->args.is_master)
1766     ring->tail = b0->desc_index + 1;
1767   else
1768     ring->head = b0->desc_index + 1;
1769
1770   mq->alloc_bufs -= *tx;
1771
1772   if ((ring->flags & MEMIF_RING_FLAG_MASK_INT) == 0)
1773     {
1774       uint64_t a = 1;
1775       int r = write (mq->int_fd, &a, sizeof (a));
1776       if (r < 0)
1777         return MEMIF_ERR_INT_WRITE;
1778     }
1779
1780   return MEMIF_ERR_SUCCESS;     /* 0 */
1781 }
1782
1783 int
1784 memif_rx_burst (memif_conn_handle_t conn, uint16_t qid,
1785                 memif_buffer_t * bufs, uint16_t count, uint16_t * rx)
1786 {
1787   memif_connection_t *c = (memif_connection_t *) conn;
1788   if (EXPECT_FALSE (c == NULL))
1789     return MEMIF_ERR_NOCONN;
1790   if (EXPECT_FALSE (c->fd < 0))
1791     return MEMIF_ERR_DISCONNECTED;
1792   uint8_t num =
1793     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1794     num_m2s_rings;
1795   if (EXPECT_FALSE (qid >= num))
1796     return MEMIF_ERR_QID;
1797   if (EXPECT_FALSE (!rx))
1798     return MEMIF_ERR_INVAL_ARG;
1799
1800   memif_queue_t *mq = &c->rx_queues[qid];
1801   memif_ring_t *ring = mq->ring;
1802   uint16_t cur_slot, last_slot;
1803   uint16_t ns;
1804   uint16_t mask = (1 << mq->log2_ring_size) - 1;
1805   memif_buffer_t *b0, *b1;
1806   *rx = 0;
1807
1808   uint64_t b;
1809   ssize_t r = read (mq->int_fd, &b, sizeof (b));
1810   if (EXPECT_FALSE ((r == -1) && (errno != EAGAIN)))
1811     return memif_syscall_error_handler (errno);
1812
1813   cur_slot = (c->args.is_master) ? mq->last_head : mq->last_tail;
1814   last_slot = (c->args.is_master) ? ring->head : ring->tail;
1815   if (cur_slot == last_slot)
1816     return MEMIF_ERR_SUCCESS;
1817
1818   ns = last_slot - cur_slot;
1819
1820   while (ns && count)
1821     {
1822       b0 = (bufs + *rx);
1823
1824       b0->desc_index = cur_slot;
1825       b0->data = memif_get_buffer (c, ring, cur_slot & mask);
1826       b0->len = ring->desc[cur_slot & mask].length;
1827       /* slave resets buffer length */
1828       if (c->args.is_master == 0)
1829         {
1830           ring->desc[cur_slot & mask].length = c->run_args.buffer_size;
1831         }
1832
1833       b0->flags = MEMIF_BUFFER_FLAG_RX;
1834       if (ring->desc[cur_slot & mask].flags & MEMIF_DESC_FLAG_NEXT)
1835         {
1836           b0->flags |= MEMIF_BUFFER_FLAG_NEXT;
1837           ring->desc[cur_slot & mask].flags &= ~MEMIF_DESC_FLAG_NEXT;
1838         }
1839 /*      b0->offset = ring->desc[cur_slot & mask].offset;*/
1840       b0->ring = ring;
1841 #ifdef MEMIF_DBG_SHM
1842       printf ("data: %p\n", b0->data);
1843       printf ("index: %u\n", b0->desc_index);
1844       printf ("ring: %p\n", b0->ring);
1845       print_bytes (b0->data, b0->len, DBG_RX_BUF);
1846 #endif /* MEMIF_DBG_SHM */
1847       ns--;
1848       *rx += 1;
1849
1850       count--;
1851       cur_slot++;
1852     }
1853
1854   if (c->args.is_master)
1855     mq->last_head = cur_slot;
1856   else
1857     mq->last_tail = cur_slot;
1858
1859   if (ns)
1860     {
1861       DBG ("not enough buffers!");
1862       return MEMIF_ERR_NOBUF;
1863     }
1864
1865   return MEMIF_ERR_SUCCESS;     /* 0 */
1866 }
1867
1868 int
1869 memif_get_details (memif_conn_handle_t conn, memif_details_t * md,
1870                    char *buf, ssize_t buflen)
1871 {
1872   libmemif_main_t *lm = &libmemif_main;
1873   memif_connection_t *c = (memif_connection_t *) conn;
1874   if (c == NULL)
1875     return MEMIF_ERR_NOCONN;
1876
1877   int err = MEMIF_ERR_SUCCESS, i;
1878   ssize_t l0, l1, total_l;
1879   l0 = 0;
1880
1881   l1 = strlen ((char *) c->args.interface_name);
1882   if (l0 + l1 < buflen)
1883     {
1884       md->if_name = (uint8_t *) strcpy (buf + l0, (char *) c->args.interface_name);
1885       l0 += l1 + 1;
1886     }
1887   else
1888     err = MEMIF_ERR_NOBUF_DET;
1889
1890   l1 = strlen ((char *) lm->app_name);
1891   if (l0 + l1 < buflen)
1892     {
1893       md->inst_name = (uint8_t *) strcpy (buf + l0, (char *) lm->app_name);
1894       l0 += l1 + 1;
1895     }
1896   else
1897     err = MEMIF_ERR_NOBUF_DET;
1898
1899   l1 = strlen ((char *) c->remote_if_name);
1900   if (l0 + l1 < buflen)
1901     {
1902       md->remote_if_name = (uint8_t *) strcpy (buf + l0, (char *) c->remote_if_name);
1903       l0 += l1 + 1;
1904     }
1905   else
1906     err = MEMIF_ERR_NOBUF_DET;
1907
1908   l1 = strlen ((char *) c->remote_name);
1909   if (l0 + l1 < buflen)
1910     {
1911       md->remote_inst_name = (uint8_t *) strcpy (buf + l0, (char *) c->remote_name);
1912       l0 += l1 + 1;
1913     }
1914   else
1915     err = MEMIF_ERR_NOBUF_DET;
1916
1917   md->id = c->args.interface_id;
1918
1919   if (strlen((char *) c->args.secret) > 0)
1920     {
1921       l1 = strlen ((char *) c->args.secret);
1922       if (l0 + l1 < buflen)
1923         {
1924           md->secret = (uint8_t *) strcpy (buf + l0, (char *) c->args.secret);
1925           l0 += l1 + 1;
1926         }
1927       else
1928         err = MEMIF_ERR_NOBUF_DET;
1929     }
1930
1931   md->role = (c->args.is_master) ? 0 : 1;
1932   md->mode = c->args.mode;
1933
1934   l1 = strlen ((char *) c->args.socket_filename);
1935   if (l0 + l1 < buflen)
1936     {
1937       md->socket_filename =
1938         (uint8_t *) strcpy (buf + l0, (char *) c->args.socket_filename);
1939       l0 += l1 + 1;
1940     }
1941   else
1942     err = MEMIF_ERR_NOBUF_DET;
1943
1944   md->rx_queues_num =
1945     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
1946     num_m2s_rings;
1947
1948   l1 = sizeof (memif_queue_details_t) * md->rx_queues_num;
1949   if (l0 + l1 <= buflen)
1950     {
1951       md->rx_queues = (memif_queue_details_t *) buf + l0;
1952       l0 += l1;
1953     }
1954   else
1955     err = MEMIF_ERR_NOBUF_DET;
1956
1957   for (i = 0; i < md->rx_queues_num; i++)
1958     {
1959       md->rx_queues[i].qid = i;
1960       md->rx_queues[i].ring_size = (1 << c->rx_queues[i].log2_ring_size);
1961       md->rx_queues[i].flags = c->rx_queues[i].ring->flags;
1962       md->rx_queues[i].head = c->rx_queues[i].ring->head;
1963       md->rx_queues[i].tail = c->rx_queues[i].ring->tail;
1964       md->rx_queues[i].buffer_size = c->run_args.buffer_size;
1965     }
1966
1967   md->tx_queues_num =
1968     (c->args.is_master) ? c->run_args.num_m2s_rings : c->run_args.
1969     num_s2m_rings;
1970
1971   l1 = sizeof (memif_queue_details_t) * md->tx_queues_num;
1972   if (l0 + l1 <= buflen)
1973     {
1974       md->tx_queues = (memif_queue_details_t *) buf + l0;
1975       l0 += l1;
1976     }
1977   else
1978     err = MEMIF_ERR_NOBUF_DET;
1979
1980   for (i = 0; i < md->tx_queues_num; i++)
1981     {
1982       md->tx_queues[i].qid = i;
1983       md->tx_queues[i].ring_size = (1 << c->tx_queues[i].log2_ring_size);
1984       md->tx_queues[i].flags = c->tx_queues[i].ring->flags;
1985       md->tx_queues[i].head = c->tx_queues[i].ring->head;
1986       md->tx_queues[i].tail = c->tx_queues[i].ring->tail;
1987       md->tx_queues[i].buffer_size = c->run_args.buffer_size;
1988     }
1989
1990   md->link_up_down = (c->fd > 0) ? 1 : 0;
1991
1992   return err;                   /* 0 */
1993 }
1994
1995 int
1996 memif_get_queue_efd (memif_conn_handle_t conn, uint16_t qid, int *efd)
1997 {
1998   memif_connection_t *c = (memif_connection_t *) conn;
1999   *efd = -1;
2000   if (c == NULL)
2001     return MEMIF_ERR_NOCONN;
2002   if (c->fd < 0)
2003     return MEMIF_ERR_DISCONNECTED;
2004   uint8_t num =
2005     (c->args.is_master) ? c->run_args.num_s2m_rings : c->run_args.
2006     num_m2s_rings;
2007   if (qid >= num)
2008     return MEMIF_ERR_QID;
2009
2010   *efd = c->rx_queues[qid].int_fd;
2011
2012   return MEMIF_ERR_SUCCESS;
2013 }
2014
2015 int
2016 memif_cleanup ()
2017 {
2018   libmemif_main_t *lm = &libmemif_main;
2019   if (lm->control_list)
2020     lm->free (lm->control_list);
2021   lm->control_list = NULL;
2022   if (lm->interrupt_list)
2023     lm->free (lm->interrupt_list);
2024   lm->interrupt_list = NULL;
2025   if (lm->listener_list)
2026     lm->free (lm->listener_list);
2027   lm->listener_list = NULL;
2028   if (lm->pending_list)
2029     lm->free (lm->pending_list);
2030   lm->pending_list = NULL;
2031   if (poll_cancel_fd != -1)
2032     close (poll_cancel_fd);
2033
2034   return MEMIF_ERR_SUCCESS;     /* 0 */
2035 }