Add memif - packet memory interface for intra-host communication
[vpp.git] / src / plugins / memif / memif.c
1 /*
2  *------------------------------------------------------------------
3  * Copyright (c) 2016 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 #define _GNU_SOURCE
19 #include <stdint.h>
20 #include <net/if.h>
21 #include <sys/types.h>
22 #include <fcntl.h>
23 #include <sys/ioctl.h>
24 #include <sys/socket.h>
25 #include <sys/un.h>
26 #include <sys/uio.h>
27 #include <sys/mman.h>
28 #include <sys/prctl.h>
29 #include <inttypes.h>
30
31 #include <vlib/vlib.h>
32 #include <vlib/unix/unix.h>
33 #include <vnet/plugin/plugin.h>
34 #include <vnet/ethernet/ethernet.h>
35 #include <vpp/app/version.h>
36 #include <memif/memif.h>
37
38 #define MEMIF_DEBUG 1
39
40 #if MEMIF_DEBUG == 1
41 #define DEBUG_LOG(...) clib_warning(__VA_ARGS__)
42 #define DEBUG_UNIX_LOG(...) clib_unix_warning(__VA_ARGS__)
43 #else
44 #define DEBUG_LOG(...)
45 #endif
46
47 memif_main_t memif_main;
48
49 static clib_error_t *memif_conn_fd_read_ready (unix_file_t * uf);
50 static clib_error_t *memif_int_fd_read_ready (unix_file_t * uf);
51
52 static u32
53 memif_eth_flag_change (vnet_main_t * vnm, vnet_hw_interface_t * hi, u32 flags)
54 {
55   /* nothing for now */
56   return 0;
57 }
58
59 static void
60 memif_remove_pending_conn (memif_pending_conn_t * pending_conn)
61 {
62   memif_main_t *mm = &memif_main;
63
64   unix_file_del (&unix_main,
65                  unix_main.file_pool + pending_conn->connection.index);
66   pool_put (mm->pending_conns, pending_conn);
67 }
68
69 static void
70 memif_connect (vlib_main_t * vm, memif_if_t * mif)
71 {
72   vnet_main_t *vnm = vnet_get_main ();
73   int num_rings = mif->num_s2m_rings + mif->num_m2s_rings;
74   memif_ring_data_t *rd = NULL;
75
76   vec_validate_aligned (mif->ring_data, num_rings - 1, CLIB_CACHE_LINE_BYTES);
77   vec_foreach (rd, mif->ring_data)
78   {
79     rd->last_head = 0;
80   }
81
82   mif->flags &= ~MEMIF_IF_FLAG_CONNECTING;
83   mif->flags |= MEMIF_IF_FLAG_CONNECTED;
84   vnet_hw_interface_set_flags (vnm, mif->hw_if_index,
85                                VNET_HW_INTERFACE_FLAG_LINK_UP);
86 }
87
88 static void
89 memif_disconnect (vlib_main_t * vm, memif_if_t * mif)
90 {
91   vnet_main_t *vnm = vnet_get_main ();
92
93   mif->flags &= ~(MEMIF_IF_FLAG_CONNECTED | MEMIF_IF_FLAG_CONNECTING);
94   if (mif->hw_if_index != ~0)
95     vnet_hw_interface_set_flags (vnm, mif->hw_if_index, 0);
96
97   if (mif->interrupt_line.index != ~0)
98     {
99       unix_file_del (&unix_main,
100                      unix_main.file_pool + mif->interrupt_line.index);
101       mif->interrupt_line.index = ~0;
102       mif->interrupt_line.fd = -1;      /* closed in unix_file_del */
103     }
104   if (mif->connection.index != ~0)
105     {
106       unix_file_del (&unix_main, unix_main.file_pool + mif->connection.index);
107       mif->connection.index = ~0;
108       mif->connection.fd = -1;  /* closed in unix_file_del */
109     }
110
111   // TODO: properly munmap + close memif-owned shared memory segments
112   vec_free (mif->regions);
113 }
114
115 static clib_error_t *
116 memif_process_connect_req (memif_pending_conn_t * pending_conn,
117                            memif_msg_t * req, struct ucred *slave_cr,
118                            int shm_fd, int int_fd)
119 {
120   memif_main_t *mm = &memif_main;
121   vlib_main_t *vm = vlib_get_main ();
122   int fd = pending_conn->connection.fd;
123   unix_file_t *uf = 0;
124   memif_if_t *mif = 0;
125   memif_msg_t resp = { 0 };
126   unix_file_t template = { 0 };
127   void *shm;
128   uword *p;
129   u8 retval = 0;
130   static clib_error_t *error = 0;
131
132   if (shm_fd == -1)
133     {
134       DEBUG_LOG
135         ("Connection request is missing shared memory file descriptor");
136       retval = 1;
137       goto response;
138     }
139
140   if (int_fd == -1)
141     {
142       DEBUG_LOG
143         ("Connection request is missing interrupt line file descriptor");
144       retval = 2;
145       goto response;
146     }
147
148   if (slave_cr == NULL)
149     {
150       DEBUG_LOG ("Connection request is missing slave credentials");
151       retval = 3;
152       goto response;
153     }
154
155   p = mhash_get (&mm->if_index_by_key, &req->key);
156   if (!p)
157     {
158       DEBUG_LOG
159         ("Connection request with unmatched key (0x%" PRIx64 ")", req->key);
160       retval = 4;
161       goto response;
162     }
163
164   mif = vec_elt_at_index (mm->interfaces, *p);
165   if (mif->listener_index != pending_conn->listener_index)
166     {
167       DEBUG_LOG
168         ("Connection request with non-matching listener (%d vs. %d)",
169          pending_conn->listener_index, mif->listener_index);
170       retval = 5;
171       goto response;
172     }
173
174   if (mif->flags & MEMIF_IF_FLAG_IS_SLAVE)
175     {
176       DEBUG_LOG ("Memif slave does not accept connection requests");
177       retval = 6;
178       goto response;
179     }
180
181   if (mif->connection.fd != -1)
182     {
183       DEBUG_LOG
184         ("Memif with key 0x%" PRIx64 " is already connected", mif->key);
185       retval = 7;
186       goto response;
187     }
188
189   if ((mif->flags & MEMIF_IF_FLAG_ADMIN_UP) == 0)
190     {
191       /* just silently decline the request */
192       retval = 8;
193       goto response;
194     }
195
196   if (req->shared_mem_size < sizeof (memif_shm_t))
197     {
198       DEBUG_LOG
199         ("Unexpectedly small shared memory segment received from slave.");
200       retval = 9;
201       goto response;
202     }
203
204   if ((shm =
205        mmap (NULL, req->shared_mem_size, PROT_READ | PROT_WRITE, MAP_SHARED,
206              shm_fd, 0)) == MAP_FAILED)
207     {
208       DEBUG_UNIX_LOG
209         ("Failed to map shared memory segment received from slave memif");
210       error = clib_error_return_unix (0, "mmap fd %d", shm_fd);
211       retval = 10;
212       goto response;
213     }
214
215   if (((memif_shm_t *) shm)->cookie != 0xdeadbeef)
216     {
217       DEBUG_LOG
218         ("Possibly corrupted shared memory segment received from slave memif");
219       munmap (shm, req->shared_mem_size);
220       retval = 11;
221       goto response;
222     }
223
224   mif->log2_ring_size = req->log2_ring_size;
225   mif->num_s2m_rings = req->num_s2m_rings;
226   mif->num_m2s_rings = req->num_m2s_rings;
227   mif->buffer_size = req->buffer_size;
228   mif->remote_pid = slave_cr->pid;
229   mif->remote_uid = slave_cr->uid;
230   vec_add1 (mif->regions, shm);
231
232   /* register interrupt line */
233   mif->interrupt_line.fd = int_fd;
234   template.read_function = memif_int_fd_read_ready;
235   template.file_descriptor = int_fd;
236   template.private_data = mif->if_index;
237   mif->interrupt_line.index = unix_file_add (&unix_main, &template);
238
239   /* change context for future messages */
240   uf = vec_elt_at_index (unix_main.file_pool, pending_conn->connection.index);
241   uf->private_data = mif->if_index << 1;
242   mif->connection = pending_conn->connection;
243   pool_put (mm->pending_conns, pending_conn);
244
245   memif_connect (vm, mif);
246
247 response:
248   resp.version = MEMIF_VERSION;
249   resp.type = MEMIF_MSG_TYPE_CONNECT_RESP;
250   resp.retval = retval;
251   send (fd, &resp, sizeof (resp), 0);
252   return error;
253 }
254
255 static clib_error_t *
256 memif_process_connect_resp (memif_if_t * mif, memif_msg_t * resp)
257 {
258   vlib_main_t *vm = vlib_get_main ();
259
260   if ((mif->flags & MEMIF_IF_FLAG_IS_SLAVE) == 0)
261     {
262       DEBUG_LOG ("Memif master does not accept connection responses");
263       return 0;
264     }
265
266   if ((mif->flags & MEMIF_IF_FLAG_CONNECTING) == 0)
267     {
268       DEBUG_LOG ("Unexpected connection response");
269       return 0;
270     }
271
272   if (resp->retval == 0)
273     memif_connect (vm, mif);
274   else
275     memif_disconnect (vm, mif);
276
277   return 0;
278 }
279
280 static clib_error_t *
281 memif_conn_fd_read_ready (unix_file_t * uf)
282 {
283   memif_main_t *mm = &memif_main;
284   vlib_main_t *vm = vlib_get_main ();
285   memif_if_t *mif = 0;
286   memif_pending_conn_t *pending_conn = 0;
287   int fd_array[2] = { -1, -1 };
288   char ctl[CMSG_SPACE (sizeof (fd_array)) +
289            CMSG_SPACE (sizeof (struct ucred))] = { 0 };
290   struct msghdr mh = { 0 };
291   struct iovec iov[1];
292   struct ucred *cr = 0;
293   memif_msg_t msg = { 0 };
294   struct cmsghdr *cmsg;
295   ssize_t size;
296   static clib_error_t *error = 0;
297
298   iov[0].iov_base = (void *) &msg;
299   iov[0].iov_len = sizeof (memif_msg_t);
300   mh.msg_iov = iov;
301   mh.msg_iovlen = 1;
302   mh.msg_control = ctl;
303   mh.msg_controllen = sizeof (ctl);
304
305   /* grab the appropriate context */
306   if (uf->private_data & 1)
307     pending_conn = vec_elt_at_index (mm->pending_conns,
308                                      uf->private_data >> 1);
309   else
310     mif = vec_elt_at_index (mm->interfaces, uf->private_data >> 1);
311
312   /* receive the incoming message */
313   size = recvmsg (uf->file_descriptor, &mh, 0);
314   if (size != sizeof (memif_msg_t))
315     {
316       if (size != 0)
317         {
318           DEBUG_UNIX_LOG ("Malformed message received on fd %d",
319                           uf->file_descriptor);
320           error = clib_error_return_unix (0, "recvmsg fd %d",
321                                           uf->file_descriptor);
322         }
323       goto disconnect;
324     }
325
326   /* check version of the sender's memif plugin */
327   if (msg.version != MEMIF_VERSION)
328     {
329       DEBUG_LOG ("Memif version mismatch");
330       goto disconnect;
331     }
332
333   /* process the message based on its type */
334   switch (msg.type)
335     {
336     case MEMIF_MSG_TYPE_CONNECT_REQ:
337       if (pending_conn == 0)
338         {
339           DEBUG_LOG ("Received unexpected connection request");
340           return 0;
341         }
342
343       /* Read anciliary data */
344       cmsg = CMSG_FIRSTHDR (&mh);
345       while (cmsg)
346         {
347           if (cmsg->cmsg_level == SOL_SOCKET
348               && cmsg->cmsg_type == SCM_CREDENTIALS)
349             {
350               cr = (struct ucred *) CMSG_DATA (cmsg);
351             }
352           else if (cmsg->cmsg_level == SOL_SOCKET
353                    && cmsg->cmsg_type == SCM_RIGHTS)
354             {
355               clib_memcpy (fd_array, CMSG_DATA (cmsg), sizeof (fd_array));
356             }
357           cmsg = CMSG_NXTHDR (&mh, cmsg);
358         }
359
360       return memif_process_connect_req (pending_conn, &msg, cr,
361                                         fd_array[0], fd_array[1]);
362
363     case MEMIF_MSG_TYPE_CONNECT_RESP:
364       if (mif == 0)
365         {
366           DEBUG_LOG ("Received unexpected connection response");
367           return 0;
368         }
369       return memif_process_connect_resp (mif, &msg);
370
371     case MEMIF_MSG_TYPE_DISCONNECT:
372       goto disconnect;
373
374     default:
375       DEBUG_LOG ("Received unknown message type");
376       goto disconnect;
377     }
378
379   return 0;
380
381 disconnect:
382   if (pending_conn)
383     memif_remove_pending_conn (pending_conn);
384   else
385     memif_disconnect (vm, mif);
386   return error;
387 }
388
389 static clib_error_t *
390 memif_int_fd_read_ready (unix_file_t * uf)
391 {
392   memif_main_t *mm = &memif_main;
393   vlib_main_t *vm = vlib_get_main ();
394   memif_if_t *mif = vec_elt_at_index (mm->interfaces, uf->private_data);
395   u8 b;
396   ssize_t size;
397
398   size = read (uf->file_descriptor, &b, sizeof (b));
399   if (0 == size)
400     {
401       /* interrupt line was disconnected */
402       unix_file_del (&unix_main,
403                      unix_main.file_pool + mif->interrupt_line.index);
404       mif->interrupt_line.index = ~0;
405       mif->interrupt_line.fd = -1;
406     }
407   vlib_node_set_interrupt_pending (vm, memif_input_node.index);
408   return 0;
409 }
410
411 static clib_error_t *
412 memif_conn_fd_accept_ready (unix_file_t * uf)
413 {
414   memif_main_t *mm = &memif_main;
415   memif_listener_t *listener = 0;
416   memif_pending_conn_t *pending_conn = 0;
417   int addr_len;
418   struct sockaddr_un client;
419   int conn_fd;
420   unix_file_t template = { 0 };
421
422   listener = pool_elt_at_index (mm->listeners, uf->private_data);
423
424   addr_len = sizeof (client);
425   conn_fd = accept (uf->file_descriptor,
426                     (struct sockaddr *) &client, (socklen_t *) & addr_len);
427
428   if (conn_fd < 0)
429     return clib_error_return_unix (0, "accept fd %d", uf->file_descriptor);
430
431   pool_get (mm->pending_conns, pending_conn);
432   pending_conn->index = pending_conn - mm->pending_conns;
433   pending_conn->listener_index = listener->index;
434   pending_conn->connection.fd = conn_fd;
435
436   template.read_function = memif_conn_fd_read_ready;
437   template.file_descriptor = conn_fd;
438   template.private_data = (pending_conn->index << 1) | 1;
439   pending_conn->connection.index = unix_file_add (&unix_main, &template);
440
441   return 0;
442 }
443
444 static void
445 memif_connect_master (vlib_main_t * vm, memif_if_t * mif)
446 {
447   memif_msg_t msg;
448   struct msghdr mh = { 0 };
449   struct iovec iov[1];
450   struct cmsghdr *cmsg;
451   int mfd = -1;
452   int rv;
453   int fd_array[2] = { -1, -1 };
454   char ctl[CMSG_SPACE (sizeof (fd_array))];
455   memif_ring_t *ring = NULL;
456   int i, j;
457   void *shm = 0;
458   u64 buffer_offset;
459   unix_file_t template = { 0 };
460
461   msg.version = MEMIF_VERSION;
462   msg.type = MEMIF_MSG_TYPE_CONNECT_REQ;
463   msg.key = mif->key;
464   msg.log2_ring_size = mif->log2_ring_size;
465   msg.num_s2m_rings = mif->num_s2m_rings;
466   msg.num_m2s_rings = mif->num_m2s_rings;
467   msg.buffer_size = mif->buffer_size;
468
469   buffer_offset = sizeof (memif_shm_t) +
470     (mif->num_s2m_rings + mif->num_m2s_rings) *
471     (sizeof (memif_ring_t) +
472      sizeof (memif_desc_t) * (1 << mif->log2_ring_size));
473
474   msg.shared_mem_size = buffer_offset +
475     mif->buffer_size * (1 << mif->log2_ring_size) * (mif->num_s2m_rings +
476                                                      mif->num_m2s_rings);
477
478   if ((mfd = memfd_create ("shared mem", MFD_ALLOW_SEALING)) == -1)
479     {
480       DEBUG_LOG ("Failed to create anonymous file");
481       goto error;
482     }
483
484   if ((fcntl (mfd, F_ADD_SEALS, F_SEAL_SHRINK)) == -1)
485     {
486       DEBUG_UNIX_LOG ("Failed to seal an anonymous file off from truncating");
487       goto error;
488     }
489
490   if ((ftruncate (mfd, msg.shared_mem_size)) == -1)
491     {
492       DEBUG_UNIX_LOG ("Failed to extend the size of an anonymous file");
493       goto error;
494     }
495
496   if ((shm = mmap (NULL, msg.shared_mem_size, PROT_READ | PROT_WRITE,
497                    MAP_SHARED, mfd, 0)) == MAP_FAILED)
498     {
499       DEBUG_UNIX_LOG ("Failed to map anonymous file into memory");
500       goto error;
501     }
502
503   vec_add1 (mif->regions, shm);
504   ((memif_shm_t *) mif->regions[0])->cookie = 0xdeadbeef;
505
506   for (i = 0; i < mif->num_s2m_rings; i++)
507     {
508       ring = memif_get_ring (mif, MEMIF_RING_S2M, i);
509       ring->head = ring->tail = 0;
510       for (j = 0; j < (1 << mif->log2_ring_size); j++)
511         {
512           u16 slot = i * (1 << mif->log2_ring_size) + j;
513           ring->desc[j].region = 0;
514           ring->desc[j].offset = buffer_offset + (slot * mif->buffer_size);
515           ring->desc[j].buffer_length = mif->buffer_size;
516         }
517     }
518   for (i = 0; i < mif->num_m2s_rings; i++)
519     {
520       ring = memif_get_ring (mif, MEMIF_RING_M2S, i);
521       ring->head = ring->tail = 0;
522       for (j = 0; j < (1 << mif->log2_ring_size); j++)
523         {
524           u16 slot =
525             (i + mif->num_s2m_rings) * (1 << mif->log2_ring_size) + j;
526           ring->desc[j].region = 0;
527           ring->desc[j].offset = buffer_offset + (slot * mif->buffer_size);
528           ring->desc[j].buffer_length = mif->buffer_size;
529         }
530     }
531
532   iov[0].iov_base = (void *) &msg;
533   iov[0].iov_len = sizeof (memif_msg_t);
534   mh.msg_iov = iov;
535   mh.msg_iovlen = 1;
536
537   /* create interrupt socket */
538   if (socketpair (AF_UNIX, SOCK_STREAM, 0, fd_array) < 0)
539     {
540       DEBUG_UNIX_LOG ("Failed to create a pair of connected sockets");
541       goto error;
542     }
543
544   mif->interrupt_line.fd = fd_array[0];
545   template.read_function = memif_int_fd_read_ready;
546   template.file_descriptor = mif->interrupt_line.fd;
547   template.private_data = mif->if_index;
548   mif->interrupt_line.index = unix_file_add (&unix_main, &template);
549
550   memset (&ctl, 0, sizeof (ctl));
551   mh.msg_control = ctl;
552   mh.msg_controllen = sizeof (ctl);
553   cmsg = CMSG_FIRSTHDR (&mh);
554   cmsg->cmsg_len = CMSG_LEN (sizeof (fd_array));
555   cmsg->cmsg_level = SOL_SOCKET;
556   cmsg->cmsg_type = SCM_RIGHTS;
557   fd_array[0] = mfd;
558   clib_memcpy (CMSG_DATA (cmsg), fd_array, sizeof (fd_array));
559
560   mif->flags |= MEMIF_IF_FLAG_CONNECTING;
561   rv = sendmsg (mif->connection.fd, &mh, 0);
562   if (rv < 0)
563     {
564       DEBUG_UNIX_LOG ("Failed to send memif connection request");
565       goto error;
566     }
567
568   /* No need to keep the descriptor open,
569    * mmap creates an extra reference to the underlying file */
570   close (mfd);
571   mfd = -1;
572   /* This FD is given to peer, so we can close it */
573   close (fd_array[1]);
574   fd_array[1] = -1;
575   return;
576
577 error:
578   if (mfd > -1)
579     close (mfd);
580   if (fd_array[1] > -1)
581     close (fd_array[1]);
582   memif_disconnect (vm, mif);
583 }
584
585 static uword
586 memif_process (vlib_main_t * vm, vlib_node_runtime_t * rt, vlib_frame_t * f)
587 {
588   memif_main_t *mm = &memif_main;
589   memif_if_t *mif;
590   struct sockaddr_un sun;
591   int sockfd;
592   uword *event_data = 0, event_type;
593   unix_file_t template = { 0 };
594   u8 enabled = 0;
595   f64 start_time, last_run_duration = 0, now;
596
597   sockfd = socket (AF_UNIX, SOCK_STREAM, 0);
598   sun.sun_family = AF_UNIX;
599   template.read_function = memif_conn_fd_read_ready;
600
601   while (1)
602     {
603       if (enabled)
604         vlib_process_wait_for_event_or_clock (vm,
605                                               (f64) 3 - last_run_duration);
606       else
607         vlib_process_wait_for_event (vm);
608
609       event_type = vlib_process_get_events (vm, &event_data);
610       vec_reset_length (event_data);
611
612       switch (event_type)
613         {
614         case ~0:
615           break;
616         case MEMIF_PROCESS_EVENT_START:
617           enabled = 1;
618           break;
619         case MEMIF_PROCESS_EVENT_STOP:
620           enabled = 0;
621           continue;
622         default:
623           ASSERT (0);
624         }
625
626       last_run_duration = start_time = vlib_time_now (vm);
627       /* *INDENT-OFF* */
628       pool_foreach (mif, mm->interfaces,
629         ({
630           /* Allow no more than 10us without a pause */
631           now = vlib_time_now (vm);
632           if (now > start_time + 10e-6)
633             {
634               vlib_process_suspend (vm, 100e-6);        /* suspend for 100 us */
635               start_time = vlib_time_now (vm);
636             }
637
638           if ((mif->flags & MEMIF_IF_FLAG_ADMIN_UP) == 0)
639             continue;
640
641           if (mif->flags & MEMIF_IF_FLAG_CONNECTING)
642             continue;
643
644           if (mif->flags & MEMIF_IF_FLAG_CONNECTED)
645             continue;
646
647           if (mif->flags & MEMIF_IF_FLAG_IS_SLAVE)
648             {
649               strncpy (sun.sun_path, (char *) mif->socket_filename,
650                        sizeof (sun.sun_path) - 1);
651
652               if (connect
653                   (sockfd, (struct sockaddr *) &sun,
654                    sizeof (struct sockaddr_un)) == 0)
655                 {
656                   mif->connection.fd = sockfd;
657                   template.file_descriptor = sockfd;
658                   template.private_data = mif->if_index << 1;
659                   mif->connection.index = unix_file_add (&unix_main, &template);
660                   memif_connect_master (vm, mif);
661
662                   /* grab another fd */
663                   sockfd = socket (AF_UNIX, SOCK_STREAM, 0);
664                   if (sockfd < 0)
665                     {
666                       DEBUG_UNIX_LOG ("socket AF_UNIX");
667                       return 0;
668                     }
669                 }
670             }
671         }));
672       /* *INDENT-ON* */
673       last_run_duration = vlib_time_now (vm) - last_run_duration;
674     }
675   return 0;
676 }
677
678 /* *INDENT-OFF* */
679 VLIB_REGISTER_NODE (memif_process_node,static) = {
680   .function = memif_process,
681   .type = VLIB_NODE_TYPE_PROCESS,
682   .name = "memif-process",
683 };
684 /* *INDENT-ON* */
685
686 static void
687 memif_close_if (memif_main_t * mm, memif_if_t * mif)
688 {
689   vlib_main_t *vm = vlib_get_main ();
690   memif_listener_t *listener = 0;
691   memif_pending_conn_t *pending_conn = 0;
692
693   memif_disconnect (vm, mif);
694
695   if (mif->listener_index != (uword) ~ 0)
696     {
697       listener = pool_elt_at_index (mm->listeners, mif->listener_index);
698       if (--listener->usage_counter == 0)
699         {
700           /* not used anymore -> remove the socket and pending connections */
701
702           /* *INDENT-OFF* */
703           pool_foreach (pending_conn, mm->pending_conns,
704             ({
705                if (pending_conn->listener_index == mif->listener_index)
706                  {
707                    memif_remove_pending_conn (pending_conn);
708                  }
709              }));
710           /* *INDENT-ON* */
711
712           unix_file_del (&unix_main,
713                          unix_main.file_pool + listener->socket.index);
714           pool_put (mm->listeners, listener);
715           unlink ((char *) mif->socket_filename);
716         }
717     }
718
719   if (mif->lockp != 0)
720     {
721       clib_mem_free ((void *) mif->lockp);
722       mif->lockp = 0;
723     }
724
725   mhash_unset (&mm->if_index_by_key, &mif->key, &mif->if_index);
726   vec_free (mif->socket_filename);
727   vec_free (mif->ring_data);
728
729   memset (mif, 0, sizeof (*mif));
730   pool_put (mm->interfaces, mif);
731 }
732
733 int
734 memif_worker_thread_enable ()
735 {
736   /* if worker threads are enabled, switch to polling mode */
737   foreach_vlib_main ((
738                        {
739                        vlib_node_set_state (this_vlib_main,
740                                             memif_input_node.index,
741                                             VLIB_NODE_STATE_POLLING);
742                        }));
743
744   return 0;
745 }
746
747 int
748 memif_worker_thread_disable ()
749 {
750   foreach_vlib_main ((
751                        {
752                        vlib_node_set_state (this_vlib_main,
753                                             memif_input_node.index,
754                                             VLIB_NODE_STATE_INTERRUPT);
755                        }));
756
757   return 0;
758 }
759
760 int
761 memif_create_if (vlib_main_t * vm, memif_create_if_args_t * args)
762 {
763   memif_main_t *mm = &memif_main;
764   vlib_thread_main_t *tm = vlib_get_thread_main ();
765   vnet_main_t *vnm = vnet_get_main ();
766   memif_if_t *mif = 0;
767   vnet_sw_interface_t *sw;
768   clib_error_t *error = 0;
769   int ret = 0;
770   uword *p;
771
772   p = mhash_get (&mm->if_index_by_key, &args->key);
773   if (p)
774     return VNET_API_ERROR_SUBIF_ALREADY_EXISTS;
775
776   pool_get (mm->interfaces, mif);
777   memset (mif, 0, sizeof (*mif));
778   mif->key = args->key;
779   mif->if_index = mif - mm->interfaces;
780   mif->sw_if_index = mif->hw_if_index = mif->per_interface_next_index = ~0;
781   mif->listener_index = ~0;
782   mif->connection.index = mif->interrupt_line.index = ~0;
783   mif->connection.fd = mif->interrupt_line.fd = -1;
784
785   if (tm->n_vlib_mains > 1)
786     {
787       mif->lockp = clib_mem_alloc_aligned (CLIB_CACHE_LINE_BYTES,
788                                            CLIB_CACHE_LINE_BYTES);
789       memset ((void *) mif->lockp, 0, CLIB_CACHE_LINE_BYTES);
790     }
791
792   if (!args->hw_addr_set)
793     {
794       f64 now = vlib_time_now (vm);
795       u32 rnd;
796       rnd = (u32) (now * 1e6);
797       rnd = random_u32 (&rnd);
798
799       memcpy (args->hw_addr + 2, &rnd, sizeof (rnd));
800       args->hw_addr[0] = 2;
801       args->hw_addr[1] = 0xfe;
802     }
803
804   error = ethernet_register_interface (vnm, memif_device_class.index,
805                                        mif->if_index, args->hw_addr,
806                                        &mif->hw_if_index,
807                                        memif_eth_flag_change);
808
809   if (error)
810     {
811       clib_error_report (error);
812       ret = VNET_API_ERROR_SYSCALL_ERROR_1;
813       goto error;
814     }
815
816   sw = vnet_get_hw_sw_interface (vnm, mif->hw_if_index);
817   mif->sw_if_index = sw->sw_if_index;
818
819   mif->log2_ring_size = args->log2_ring_size;
820   mif->buffer_size = args->buffer_size;
821
822   /* TODO: make configurable */
823   mif->num_s2m_rings = 1;
824   mif->num_m2s_rings = 1;
825
826   mhash_set_mem (&mm->if_index_by_key, &args->key, &mif->if_index, 0);
827
828   if (args->socket_filename != 0)
829     mif->socket_filename = args->socket_filename;
830   else
831     mif->socket_filename = vec_dup (mm->default_socket_filename);
832
833   args->sw_if_index = mif->sw_if_index;
834
835   if (args->is_master)
836     {
837       struct sockaddr_un un = { 0 };
838       struct stat file_stat;
839       int on = 1;
840       memif_listener_t *listener = 0;
841
842       if (stat ((char *) mif->socket_filename, &file_stat) == 0)
843         {
844           if (!S_ISSOCK (file_stat.st_mode))
845             {
846               errno = ENOTSOCK;
847               ret = VNET_API_ERROR_SYSCALL_ERROR_2;
848               goto error;
849             }
850           /* *INDENT-OFF* */
851           pool_foreach (listener, mm->listeners,
852             ({
853                if (listener->sock_dev == file_stat.st_dev &&
854                    listener->sock_ino == file_stat.st_ino)
855                  {
856                    /* attach memif to the existing listener */
857                    mif->listener_index = listener->index;
858                    ++listener->usage_counter;
859                    goto signal;
860                  }
861              }));
862           /* *INDENT-ON* */
863           unlink ((char *) mif->socket_filename);
864         }
865
866       pool_get (mm->listeners, listener);
867       memset (listener, 0, sizeof (*listener));
868       listener->socket.fd = -1;
869       listener->socket.index = ~0;
870       listener->index = listener - mm->listeners;
871       listener->usage_counter = 1;
872
873       if ((listener->socket.fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
874         {
875           ret = VNET_API_ERROR_SYSCALL_ERROR_3;
876           goto error;
877         }
878
879       un.sun_family = AF_UNIX;
880       strncpy ((char *) un.sun_path, (char *) mif->socket_filename,
881                sizeof (un.sun_path) - 1);
882
883       if (setsockopt (listener->socket.fd, SOL_SOCKET, SO_PASSCRED,
884                       &on, sizeof (on)) < 0)
885         {
886           ret = VNET_API_ERROR_SYSCALL_ERROR_4;
887           goto error;
888         }
889       if (bind (listener->socket.fd, (struct sockaddr *) &un,
890                 sizeof (un)) == -1)
891         {
892           ret = VNET_API_ERROR_SYSCALL_ERROR_5;
893           goto error;
894         }
895       if (listen (listener->socket.fd, 1) == -1)
896         {
897           ret = VNET_API_ERROR_SYSCALL_ERROR_6;
898           goto error;
899         }
900
901       if (stat ((char *) mif->socket_filename, &file_stat) == -1)
902         {
903           ret = VNET_API_ERROR_SYSCALL_ERROR_7;
904           goto error;
905         }
906
907       listener->sock_dev = file_stat.st_dev;
908       listener->sock_ino = file_stat.st_ino;
909
910       unix_file_t template = { 0 };
911       template.read_function = memif_conn_fd_accept_ready;
912       template.file_descriptor = listener->socket.fd;
913       template.private_data = listener->index;
914       listener->socket.index = unix_file_add (&unix_main, &template);
915
916       mif->listener_index = listener->index;
917     }
918   else
919     {
920       mif->flags |= MEMIF_IF_FLAG_IS_SLAVE;
921     }
922
923 #if 0
924   /* use configured or generate random MAC address */
925   if (!args->hw_addr_set &&
926       tm->n_vlib_mains > 1 && pool_elts (mm->interfaces) == 1)
927     memif_worker_thread_enable ();
928 #endif
929
930 signal:
931   if (pool_elts (mm->interfaces) == 1)
932     {
933       vlib_process_signal_event (vm, memif_process_node.index,
934                                  MEMIF_PROCESS_EVENT_START, 0);
935     }
936   return 0;
937
938 error:
939   if (mif->hw_if_index != ~0)
940     {
941       ethernet_delete_interface (vnm, mif->hw_if_index);
942       mif->hw_if_index = ~0;
943     }
944   memif_close_if (mm, mif);
945   return ret;
946 }
947
948 int
949 memif_delete_if (vlib_main_t * vm, u64 key)
950 {
951   vnet_main_t *vnm = vnet_get_main ();
952   memif_main_t *mm = &memif_main;
953   memif_if_t *mif;
954   uword *p;
955
956   p = mhash_get (&mm->if_index_by_key, &key);
957   if (p == NULL)
958     {
959       clib_warning ("Memory interface with key 0x%" PRIx64 " does not exist",
960                     key);
961       return VNET_API_ERROR_SYSCALL_ERROR_1;
962     }
963   mif = pool_elt_at_index (mm->interfaces, p[0]);
964   mif->flags |= MEMIF_IF_FLAG_DELETING;
965
966   /* bring down the interface */
967   vnet_hw_interface_set_flags (vnm, mif->hw_if_index, 0);
968   vnet_sw_interface_set_flags (vnm, mif->sw_if_index, 0);
969
970   /* remove the interface */
971   ethernet_delete_interface (vnm, mif->hw_if_index);
972   mif->hw_if_index = ~0;
973   memif_close_if (mm, mif);
974
975   if (pool_elts (mm->interfaces) == 0)
976     {
977       vlib_process_signal_event (vm, memif_process_node.index,
978                                  MEMIF_PROCESS_EVENT_STOP, 0);
979     }
980
981 #if 0
982   if (tm->n_vlib_mains > 1 && pool_elts (mm->interfaces) == 0)
983     memif_worker_thread_disable ();
984 #endif
985
986   return 0;
987 }
988
989 static clib_error_t *
990 memif_init (vlib_main_t * vm)
991 {
992   memif_main_t *mm = &memif_main;
993   vlib_thread_main_t *tm = vlib_get_thread_main ();
994   vlib_thread_registration_t *tr;
995   uword *p;
996
997   memset (mm, 0, sizeof (memif_main_t));
998
999   mm->input_cpu_first_index = 0;
1000   mm->input_cpu_count = 1;
1001
1002   /* initialize binary API */
1003   memif_plugin_api_hookup (vm);
1004
1005   /* find out which cpus will be used for input */
1006   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
1007   tr = p ? (vlib_thread_registration_t *) p[0] : 0;
1008
1009   if (tr && tr->count > 0)
1010     {
1011       mm->input_cpu_first_index = tr->first_index;
1012       mm->input_cpu_count = tr->count;
1013     }
1014
1015   mhash_init (&mm->if_index_by_key, sizeof (uword), sizeof (u64));
1016
1017   vec_validate_aligned (mm->rx_buffers, tm->n_vlib_mains - 1,
1018                         CLIB_CACHE_LINE_BYTES);
1019
1020   /* set default socket filename */
1021   vec_validate (mm->default_socket_filename,
1022                 strlen (MEMIF_DEFAULT_SOCKET_FILENAME));
1023   strncpy ((char *) mm->default_socket_filename,
1024            MEMIF_DEFAULT_SOCKET_FILENAME,
1025            vec_len (mm->default_socket_filename) - 1);
1026
1027   return 0;
1028 }
1029
1030 VLIB_INIT_FUNCTION (memif_init);
1031
1032 /* *INDENT-OFF* */
1033 VLIB_PLUGIN_REGISTER () = {
1034     .version = VPP_BUILD_VER,
1035     .description = "Packet Memory Interface (experimetal)",
1036 };
1037 /* *INDENT-ON* */
1038
1039 /*
1040  * fd.io coding-style-patch-verification: ON
1041  *
1042  * Local Variables:
1043  * eval: (c-set-style "gnu")
1044  * End:
1045  */