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