vppinfra: add spinlock inline functions
[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   clib_spinlock_free (&mif->lockp);
720
721   mhash_unset (&mm->if_index_by_key, &mif->key, &mif->if_index);
722   vec_free (mif->socket_filename);
723   vec_free (mif->ring_data);
724
725   memset (mif, 0, sizeof (*mif));
726   pool_put (mm->interfaces, mif);
727 }
728
729 int
730 memif_worker_thread_enable ()
731 {
732   /* if worker threads are enabled, switch to polling mode */
733   foreach_vlib_main ((
734                        {
735                        vlib_node_set_state (this_vlib_main,
736                                             memif_input_node.index,
737                                             VLIB_NODE_STATE_POLLING);
738                        }));
739
740   return 0;
741 }
742
743 int
744 memif_worker_thread_disable ()
745 {
746   foreach_vlib_main ((
747                        {
748                        vlib_node_set_state (this_vlib_main,
749                                             memif_input_node.index,
750                                             VLIB_NODE_STATE_INTERRUPT);
751                        }));
752
753   return 0;
754 }
755
756 int
757 memif_create_if (vlib_main_t * vm, memif_create_if_args_t * args)
758 {
759   memif_main_t *mm = &memif_main;
760   vlib_thread_main_t *tm = vlib_get_thread_main ();
761   vnet_main_t *vnm = vnet_get_main ();
762   memif_if_t *mif = 0;
763   vnet_sw_interface_t *sw;
764   clib_error_t *error = 0;
765   int ret = 0;
766   uword *p;
767
768   p = mhash_get (&mm->if_index_by_key, &args->key);
769   if (p)
770     return VNET_API_ERROR_SUBIF_ALREADY_EXISTS;
771
772   pool_get (mm->interfaces, mif);
773   memset (mif, 0, sizeof (*mif));
774   mif->key = args->key;
775   mif->if_index = mif - mm->interfaces;
776   mif->sw_if_index = mif->hw_if_index = mif->per_interface_next_index = ~0;
777   mif->listener_index = ~0;
778   mif->connection.index = mif->interrupt_line.index = ~0;
779   mif->connection.fd = mif->interrupt_line.fd = -1;
780
781   if (tm->n_vlib_mains > 1)
782     clib_spinlock_init (&mif->lockp);
783
784   if (!args->hw_addr_set)
785     {
786       f64 now = vlib_time_now (vm);
787       u32 rnd;
788       rnd = (u32) (now * 1e6);
789       rnd = random_u32 (&rnd);
790
791       memcpy (args->hw_addr + 2, &rnd, sizeof (rnd));
792       args->hw_addr[0] = 2;
793       args->hw_addr[1] = 0xfe;
794     }
795
796   error = ethernet_register_interface (vnm, memif_device_class.index,
797                                        mif->if_index, args->hw_addr,
798                                        &mif->hw_if_index,
799                                        memif_eth_flag_change);
800
801   if (error)
802     {
803       clib_error_report (error);
804       ret = VNET_API_ERROR_SYSCALL_ERROR_1;
805       goto error;
806     }
807
808   sw = vnet_get_hw_sw_interface (vnm, mif->hw_if_index);
809   mif->sw_if_index = sw->sw_if_index;
810
811   mif->log2_ring_size = args->log2_ring_size;
812   mif->buffer_size = args->buffer_size;
813
814   /* TODO: make configurable */
815   mif->num_s2m_rings = 1;
816   mif->num_m2s_rings = 1;
817
818   mhash_set_mem (&mm->if_index_by_key, &args->key, &mif->if_index, 0);
819
820   if (args->socket_filename != 0)
821     mif->socket_filename = args->socket_filename;
822   else
823     mif->socket_filename = vec_dup (mm->default_socket_filename);
824
825   args->sw_if_index = mif->sw_if_index;
826
827   if (args->is_master)
828     {
829       struct sockaddr_un un = { 0 };
830       struct stat file_stat;
831       int on = 1;
832       memif_listener_t *listener = 0;
833
834       if (stat ((char *) mif->socket_filename, &file_stat) == 0)
835         {
836           if (!S_ISSOCK (file_stat.st_mode))
837             {
838               errno = ENOTSOCK;
839               ret = VNET_API_ERROR_SYSCALL_ERROR_2;
840               goto error;
841             }
842           /* *INDENT-OFF* */
843           pool_foreach (listener, mm->listeners,
844             ({
845                if (listener->sock_dev == file_stat.st_dev &&
846                    listener->sock_ino == file_stat.st_ino)
847                  {
848                    /* attach memif to the existing listener */
849                    mif->listener_index = listener->index;
850                    ++listener->usage_counter;
851                    goto signal;
852                  }
853              }));
854           /* *INDENT-ON* */
855           unlink ((char *) mif->socket_filename);
856         }
857
858       pool_get (mm->listeners, listener);
859       memset (listener, 0, sizeof (*listener));
860       listener->socket.fd = -1;
861       listener->socket.index = ~0;
862       listener->index = listener - mm->listeners;
863       listener->usage_counter = 1;
864
865       if ((listener->socket.fd = socket (AF_UNIX, SOCK_STREAM, 0)) < 0)
866         {
867           ret = VNET_API_ERROR_SYSCALL_ERROR_3;
868           goto error;
869         }
870
871       un.sun_family = AF_UNIX;
872       strncpy ((char *) un.sun_path, (char *) mif->socket_filename,
873                sizeof (un.sun_path) - 1);
874
875       if (setsockopt (listener->socket.fd, SOL_SOCKET, SO_PASSCRED,
876                       &on, sizeof (on)) < 0)
877         {
878           ret = VNET_API_ERROR_SYSCALL_ERROR_4;
879           goto error;
880         }
881       if (bind (listener->socket.fd, (struct sockaddr *) &un,
882                 sizeof (un)) == -1)
883         {
884           ret = VNET_API_ERROR_SYSCALL_ERROR_5;
885           goto error;
886         }
887       if (listen (listener->socket.fd, 1) == -1)
888         {
889           ret = VNET_API_ERROR_SYSCALL_ERROR_6;
890           goto error;
891         }
892
893       if (stat ((char *) mif->socket_filename, &file_stat) == -1)
894         {
895           ret = VNET_API_ERROR_SYSCALL_ERROR_7;
896           goto error;
897         }
898
899       listener->sock_dev = file_stat.st_dev;
900       listener->sock_ino = file_stat.st_ino;
901
902       unix_file_t template = { 0 };
903       template.read_function = memif_conn_fd_accept_ready;
904       template.file_descriptor = listener->socket.fd;
905       template.private_data = listener->index;
906       listener->socket.index = unix_file_add (&unix_main, &template);
907
908       mif->listener_index = listener->index;
909     }
910   else
911     {
912       mif->flags |= MEMIF_IF_FLAG_IS_SLAVE;
913     }
914
915 #if 0
916   /* use configured or generate random MAC address */
917   if (!args->hw_addr_set &&
918       tm->n_vlib_mains > 1 && pool_elts (mm->interfaces) == 1)
919     memif_worker_thread_enable ();
920 #endif
921
922 signal:
923   if (pool_elts (mm->interfaces) == 1)
924     {
925       vlib_process_signal_event (vm, memif_process_node.index,
926                                  MEMIF_PROCESS_EVENT_START, 0);
927     }
928   return 0;
929
930 error:
931   if (mif->hw_if_index != ~0)
932     {
933       ethernet_delete_interface (vnm, mif->hw_if_index);
934       mif->hw_if_index = ~0;
935     }
936   memif_close_if (mm, mif);
937   return ret;
938 }
939
940 int
941 memif_delete_if (vlib_main_t * vm, u64 key)
942 {
943   vnet_main_t *vnm = vnet_get_main ();
944   memif_main_t *mm = &memif_main;
945   memif_if_t *mif;
946   uword *p;
947
948   p = mhash_get (&mm->if_index_by_key, &key);
949   if (p == NULL)
950     {
951       clib_warning ("Memory interface with key 0x%" PRIx64 " does not exist",
952                     key);
953       return VNET_API_ERROR_SYSCALL_ERROR_1;
954     }
955   mif = pool_elt_at_index (mm->interfaces, p[0]);
956   mif->flags |= MEMIF_IF_FLAG_DELETING;
957
958   /* bring down the interface */
959   vnet_hw_interface_set_flags (vnm, mif->hw_if_index, 0);
960   vnet_sw_interface_set_flags (vnm, mif->sw_if_index, 0);
961
962   /* remove the interface */
963   ethernet_delete_interface (vnm, mif->hw_if_index);
964   mif->hw_if_index = ~0;
965   memif_close_if (mm, mif);
966
967   if (pool_elts (mm->interfaces) == 0)
968     {
969       vlib_process_signal_event (vm, memif_process_node.index,
970                                  MEMIF_PROCESS_EVENT_STOP, 0);
971     }
972
973 #if 0
974   if (tm->n_vlib_mains > 1 && pool_elts (mm->interfaces) == 0)
975     memif_worker_thread_disable ();
976 #endif
977
978   return 0;
979 }
980
981 static clib_error_t *
982 memif_init (vlib_main_t * vm)
983 {
984   memif_main_t *mm = &memif_main;
985   vlib_thread_main_t *tm = vlib_get_thread_main ();
986   vlib_thread_registration_t *tr;
987   uword *p;
988
989   memset (mm, 0, sizeof (memif_main_t));
990
991   mm->input_cpu_first_index = 0;
992   mm->input_cpu_count = 1;
993
994   /* initialize binary API */
995   memif_plugin_api_hookup (vm);
996
997   /* find out which cpus will be used for input */
998   p = hash_get_mem (tm->thread_registrations_by_name, "workers");
999   tr = p ? (vlib_thread_registration_t *) p[0] : 0;
1000
1001   if (tr && tr->count > 0)
1002     {
1003       mm->input_cpu_first_index = tr->first_index;
1004       mm->input_cpu_count = tr->count;
1005     }
1006
1007   mhash_init (&mm->if_index_by_key, sizeof (uword), sizeof (u64));
1008
1009   vec_validate_aligned (mm->rx_buffers, tm->n_vlib_mains - 1,
1010                         CLIB_CACHE_LINE_BYTES);
1011
1012   /* set default socket filename */
1013   vec_validate (mm->default_socket_filename,
1014                 strlen (MEMIF_DEFAULT_SOCKET_FILENAME));
1015   strncpy ((char *) mm->default_socket_filename,
1016            MEMIF_DEFAULT_SOCKET_FILENAME,
1017            vec_len (mm->default_socket_filename) - 1);
1018
1019   return 0;
1020 }
1021
1022 VLIB_INIT_FUNCTION (memif_init);
1023
1024 /* *INDENT-OFF* */
1025 VLIB_PLUGIN_REGISTER () = {
1026     .version = VPP_BUILD_VER,
1027     .description = "Packet Memory Interface (experimetal)",
1028 };
1029 /* *INDENT-ON* */
1030
1031 /*
1032  * fd.io coding-style-patch-verification: ON
1033  *
1034  * Local Variables:
1035  * eval: (c-set-style "gnu")
1036  * End:
1037  */