VCL: Fix accept state machine, EPOLLET logic.
[vpp.git] / src / vcl / vppcom.c
1 /*
2  * Copyright (c) 2017 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16 #include <stdio.h>
17 #include <stdlib.h>
18 #include <signal.h>
19 #include <svm/svm_fifo_segment.h>
20 #include <vlibmemory/api.h>
21 #include <vpp/api/vpe_msg_enum.h>
22 #include <vnet/session/application_interface.h>
23 #include <vcl/vppcom.h>
24 #include <vlib/unix/unix.h>
25 #include <vppinfra/vec_bootstrap.h>
26
27 #define vl_typedefs             /* define message structures */
28 #include <vpp/api/vpe_all_api_h.h>
29 #undef vl_typedefs
30
31 /* declare message handlers for each api */
32
33 #define vl_endianfun            /* define message structures */
34 #include <vpp/api/vpe_all_api_h.h>
35 #undef vl_endianfun
36
37 /* instantiate all the print functions we know about */
38 #define vl_print(handle, ...)
39 #define vl_printfun
40 #include <vpp/api/vpe_all_api_h.h>
41 #undef vl_printfun
42
43 #if (CLIB_DEBUG > 0)
44 /* Set VPPCOM_DEBUG_INIT 2 for connection debug,
45  *                       3 for read/write debug output
46  * or
47  *    export VCL_DEBUG=<#> to set dynamically.
48  */
49 #define VPPCOM_DEBUG_INIT 1
50 #else
51 #define VPPCOM_DEBUG_INIT 0
52 #endif
53
54 #define VPPCOM_DEBUG vcm->debug
55
56 /*
57  * VPPCOM Private definitions and functions.
58  */
59 typedef enum
60 {
61   STATE_APP_START,
62   STATE_APP_CONN_VPP,
63   STATE_APP_ENABLED,
64   STATE_APP_ATTACHED,
65 } app_state_t;
66
67 typedef enum
68 {
69   STATE_START,
70   STATE_CONNECT,
71   STATE_LISTEN,
72   STATE_ACCEPT,
73   STATE_DISCONNECT,
74   STATE_FAILED
75 } session_state_t;
76
77 typedef struct epoll_event vppcom_epoll_event_t;
78
79 typedef struct
80 {
81   u32 next_sid;
82   u32 prev_sid;
83   u32 vep_idx;
84   vppcom_epoll_event_t ev;
85 #define VEP_DEFAULT_ET_MASK  (EPOLLIN|EPOLLOUT)
86 #define VEP_UNSUPPORTED_EVENTS (EPOLLONESHOT|EPOLLEXCLUSIVE)
87   u32 et_mask;
88 } vppcom_epoll_t;
89
90 typedef struct
91 {
92   u8 is_ip4;
93   ip46_address_t ip46;
94 } vppcom_ip46_t;
95
96 typedef struct
97 {
98   volatile session_state_t state;
99
100   svm_fifo_t *server_rx_fifo;
101   svm_fifo_t *server_tx_fifo;
102   u8 *segment_name;
103   u32 sm_seg_index;
104   u32 client_context;
105   u64 vpp_handle;
106   unix_shared_memory_queue_t *vpp_event_queue;
107
108   /* Socket configuration state */
109   /* TBD: covert 'is_*' vars to bit in u8 flags; */
110   u8 is_server;
111   u8 is_listen;
112   u8 is_cut_thru;
113   u8 is_nonblocking;
114   u8 is_vep;
115   u8 is_vep_session;
116   u32 wait_cont_idx;
117   vppcom_epoll_t vep;
118   u32 vrf;
119   vppcom_ip46_t lcl_addr;
120   vppcom_ip46_t peer_addr;
121   u16 lcl_port;                 // network order
122   u16 peer_port;                // network order
123   u8 proto;
124   u64 client_queue_address;
125   u64 options[16];
126 } session_t;
127
128 typedef struct vppcom_cfg_t_
129 {
130   u64 heapsize;
131   u64 segment_baseva;
132   u32 segment_size;
133   u32 add_segment_size;
134   u32 preallocated_fifo_pairs;
135   u32 rx_fifo_size;
136   u32 tx_fifo_size;
137   u32 event_queue_size;
138   u32 listen_queue_size;
139   u8 app_proxy_transport_tcp;
140   u8 app_proxy_transport_udp;
141   u8 app_scope_local;
142   u8 app_scope_global;
143   u8 *namespace_id;
144   u64 namespace_secret;
145   f64 app_timeout;
146   f64 session_timeout;
147   f64 accept_timeout;
148 } vppcom_cfg_t;
149
150 typedef struct vppcom_main_t_
151 {
152   u8 init;
153   u32 debug;
154   u32 *client_session_index_fifo;
155   volatile u32 bind_session_index;
156   int main_cpu;
157
158   /* vpe input queue */
159   unix_shared_memory_queue_t *vl_input_queue;
160
161   /* API client handle */
162   u32 my_client_index;
163
164   /* Session pool */
165   clib_spinlock_t sessions_lockp;
166   session_t *sessions;
167
168   /* Hash table for disconnect processing */
169   uword *session_index_by_vpp_handles;
170
171   /* Select bitmaps */
172   clib_bitmap_t *rd_bitmap;
173   clib_bitmap_t *wr_bitmap;
174   clib_bitmap_t *ex_bitmap;
175
176   /* Our event queue */
177   unix_shared_memory_queue_t *app_event_queue;
178
179   /* unique segment name counter */
180   u32 unique_segment_index;
181
182   /* For deadman timers */
183   clib_time_t clib_time;
184
185   /* State of the connection, shared between msg RX thread and main thread */
186   volatile app_state_t app_state;
187
188   vppcom_cfg_t cfg;
189
190   /* VNET_API_ERROR_FOO -> "Foo" hash table */
191   uword *error_string_by_error_number;
192 } vppcom_main_t;
193
194 /* NOTE: _vppcom_main is only used until the heap is allocated.
195  *       Do not access it directly -- use vcm which will point to
196  *       the heap allocated copy after init.
197  */
198 static vppcom_main_t _vppcom_main = {
199   .debug = VPPCOM_DEBUG_INIT,
200   .my_client_index = ~0
201 };
202
203 static vppcom_main_t *vcm = &_vppcom_main;
204
205 #define VCL_LOCK_AND_GET_SESSION(I, S)                  \
206 do {                                                    \
207   clib_spinlock_lock (&vcm->sessions_lockp);            \
208   rv = vppcom_session_at_index (I, S);                  \
209   if (PREDICT_FALSE (rv))                               \
210     {                                                   \
211       clib_spinlock_unlock (&vcm->sessions_lockp);      \
212                                                         \
213       if (VPPCOM_DEBUG > 0)                             \
214         clib_warning ("[%s] ERROR: Invalid ##I (%u)!",  \
215                       getpid (), I);                  \
216                                                         \
217       goto done;                                        \
218     }                                                   \
219 } while (0)
220
221 static const char *
222 vppcom_app_state_str (app_state_t state)
223 {
224   char *st;
225
226   switch (state)
227     {
228     case STATE_APP_START:
229       st = "STATE_APP_START";
230       break;
231
232     case STATE_APP_CONN_VPP:
233       st = "STATE_APP_CONN_VPP";
234       break;
235
236     case STATE_APP_ENABLED:
237       st = "STATE_APP_ENABLED";
238       break;
239
240     case STATE_APP_ATTACHED:
241       st = "STATE_APP_ATTACHED";
242       break;
243
244     default:
245       st = "UNKNOWN_APP_STATE";
246       break;
247     }
248
249   return st;
250 }
251
252 static const char *
253 vppcom_session_state_str (session_state_t state)
254 {
255   char *st;
256
257   switch (state)
258     {
259     case STATE_START:
260       st = "STATE_START";
261       break;
262
263     case STATE_CONNECT:
264       st = "STATE_CONNECT";
265       break;
266
267     case STATE_LISTEN:
268       st = "STATE_LISTEN";
269       break;
270
271     case STATE_ACCEPT:
272       st = "STATE_ACCEPT";
273       break;
274
275     case STATE_DISCONNECT:
276       st = "STATE_DISCONNECT";
277       break;
278
279     case STATE_FAILED:
280       st = "STATE_FAILED";
281       break;
282
283     default:
284       st = "UNKNOWN_STATE";
285       break;
286     }
287
288   return st;
289 }
290
291 /*
292  * VPPCOM Utility Functions
293  */
294 static inline int
295 vppcom_session_at_index (u32 session_index, session_t * volatile *sess)
296 {
297   /* Assumes that caller has acquired spinlock: vcm->sessions_lockp */
298   if (PREDICT_FALSE ((session_index == ~0) ||
299                      pool_is_free_index (vcm->sessions, session_index)))
300     {
301       clib_warning ("[%d] invalid session, sid (%u) has been closed!",
302                     getpid (), session_index);
303       return VPPCOM_EBADFD;
304     }
305   *sess = pool_elt_at_index (vcm->sessions, session_index);
306   return VPPCOM_OK;
307 }
308
309 static int
310 vppcom_connect_to_vpp (char *app_name)
311 {
312   api_main_t *am = &api_main;
313
314   if (VPPCOM_DEBUG > 0)
315     printf ("\nConnecting to VPP api...");
316   if (vl_client_connect_to_vlib ("/vpe-api", app_name, 32) < 0)
317     {
318       clib_warning ("[%d] connect to vpp (%s) failed!", getpid (), app_name);
319       return VPPCOM_ECONNREFUSED;
320     }
321
322   vcm->vl_input_queue = am->shmem_hdr->vl_input_queue;
323   vcm->my_client_index = am->my_client_index;
324   if (VPPCOM_DEBUG > 0)
325     printf (" connected!\n");
326
327   vcm->app_state = STATE_APP_CONN_VPP;
328   return VPPCOM_OK;
329 }
330
331 static u8 *
332 format_api_error (u8 * s, va_list * args)
333 {
334   i32 error = va_arg (*args, u32);
335   uword *p;
336
337   p = hash_get (vcm->error_string_by_error_number, -error);
338
339   if (p)
340     s = format (s, "%s (%d)", p[0], error);
341   else
342     s = format (s, "%d", error);
343   return s;
344 }
345
346 static void
347 vppcom_init_error_string_table (void)
348 {
349   vcm->error_string_by_error_number = hash_create (0, sizeof (uword));
350
351 #define _(n,v,s) hash_set (vcm->error_string_by_error_number, -v, s);
352   foreach_vnet_api_error;
353 #undef _
354
355   hash_set (vcm->error_string_by_error_number, 99, "Misc");
356 }
357
358 static inline int
359 vppcom_wait_for_app_state_change (app_state_t app_state)
360 {
361   f64 timeout = clib_time_now (&vcm->clib_time) + vcm->cfg.app_timeout;
362
363   while (clib_time_now (&vcm->clib_time) < timeout)
364     {
365       if (vcm->app_state == app_state)
366         return VPPCOM_OK;
367     }
368   if (VPPCOM_DEBUG > 0)
369     clib_warning ("[%d] timeout waiting for state %s (%d)", getpid (),
370                   vppcom_app_state_str (app_state), app_state);
371   return VPPCOM_ETIMEDOUT;
372 }
373
374 static inline int
375 vppcom_wait_for_session_state_change (u32 session_index,
376                                       session_state_t state,
377                                       f64 wait_for_time)
378 {
379   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
380   session_t *volatile session;
381   int rv;
382
383   do
384     {
385       clib_spinlock_lock (&vcm->sessions_lockp);
386       rv = vppcom_session_at_index (session_index, &session);
387       if (PREDICT_FALSE (rv))
388         {
389           clib_spinlock_unlock (&vcm->sessions_lockp);
390           return rv;
391         }
392       if (session->state == state)
393         {
394           clib_spinlock_unlock (&vcm->sessions_lockp);
395           return VPPCOM_OK;
396         }
397       clib_spinlock_unlock (&vcm->sessions_lockp);
398     }
399   while (clib_time_now (&vcm->clib_time) < timeout);
400
401   if (VPPCOM_DEBUG > 0)
402     clib_warning ("[%d] timeout waiting for state %s (%d)", getpid (),
403                   vppcom_session_state_str (state), state);
404   return VPPCOM_ETIMEDOUT;
405 }
406
407 static inline int
408 vppcom_wait_for_client_session_index (f64 wait_for_time)
409 {
410   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
411
412   do
413     {
414       if (clib_fifo_elts (vcm->client_session_index_fifo))
415         return VPPCOM_OK;
416     }
417   while (clib_time_now (&vcm->clib_time) < timeout);
418
419   if (wait_for_time == 0)
420     return VPPCOM_EAGAIN;
421
422   if (VPPCOM_DEBUG > 0)
423     clib_warning ("[%d] timeout waiting for client_session_index", getpid ());
424   return VPPCOM_ETIMEDOUT;
425 }
426
427 /*
428  * VPP-API message functions
429  */
430 static void
431 vppcom_send_session_enable_disable (u8 is_enable)
432 {
433   vl_api_session_enable_disable_t *bmp;
434   bmp = vl_msg_api_alloc (sizeof (*bmp));
435   memset (bmp, 0, sizeof (*bmp));
436
437   bmp->_vl_msg_id = ntohs (VL_API_SESSION_ENABLE_DISABLE);
438   bmp->client_index = vcm->my_client_index;
439   bmp->context = htonl (0xfeedface);
440   bmp->is_enable = is_enable;
441   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
442 }
443
444 static int
445 vppcom_app_session_enable (void)
446 {
447   int rv;
448
449   if (vcm->app_state != STATE_APP_ENABLED)
450     {
451       vppcom_send_session_enable_disable (1 /* is_enabled == TRUE */ );
452       rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
453       if (PREDICT_FALSE (rv))
454         {
455           if (VPPCOM_DEBUG > 0)
456             clib_warning ("[%d] Session enable timed out, rv = %s (%d)",
457                           getpid (), vppcom_retval_str (rv), rv);
458           return rv;
459         }
460     }
461   return VPPCOM_OK;
462 }
463
464 static void
465   vl_api_session_enable_disable_reply_t_handler
466   (vl_api_session_enable_disable_reply_t * mp)
467 {
468   if (mp->retval)
469     {
470       clib_warning ("[%d] session_enable_disable failed: %U", getpid (),
471                     format_api_error, ntohl (mp->retval));
472     }
473   else
474     vcm->app_state = STATE_APP_ENABLED;
475 }
476
477 static void
478 vppcom_app_send_attach (void)
479 {
480   vl_api_application_attach_t *bmp;
481   u8 nsid_len = vec_len (vcm->cfg.namespace_id);
482   u8 app_is_proxy = (vcm->cfg.app_proxy_transport_tcp ||
483                      vcm->cfg.app_proxy_transport_udp);
484
485   bmp = vl_msg_api_alloc (sizeof (*bmp));
486   memset (bmp, 0, sizeof (*bmp));
487
488   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_ATTACH);
489   bmp->client_index = vcm->my_client_index;
490   bmp->context = htonl (0xfeedface);
491   bmp->options[APP_OPTIONS_FLAGS] =
492     APP_OPTIONS_FLAGS_ACCEPT_REDIRECT | APP_OPTIONS_FLAGS_ADD_SEGMENT |
493     (vcm->cfg.app_scope_local ? APP_OPTIONS_FLAGS_USE_LOCAL_SCOPE : 0) |
494     (vcm->cfg.app_scope_global ? APP_OPTIONS_FLAGS_USE_GLOBAL_SCOPE : 0) |
495     (app_is_proxy ? APP_OPTIONS_FLAGS_IS_PROXY : 0);
496   bmp->options[APP_OPTIONS_PROXY_TRANSPORT] =
497     (vcm->cfg.app_proxy_transport_tcp ? 1 << TRANSPORT_PROTO_TCP : 0) |
498     (vcm->cfg.app_proxy_transport_udp ? 1 << TRANSPORT_PROTO_UDP : 0);
499   bmp->options[SESSION_OPTIONS_SEGMENT_SIZE] = vcm->cfg.segment_size;
500   bmp->options[SESSION_OPTIONS_ADD_SEGMENT_SIZE] = vcm->cfg.add_segment_size;
501   bmp->options[SESSION_OPTIONS_RX_FIFO_SIZE] = vcm->cfg.rx_fifo_size;
502   bmp->options[SESSION_OPTIONS_TX_FIFO_SIZE] = vcm->cfg.tx_fifo_size;
503   if (nsid_len)
504     {
505       bmp->namespace_id_len = nsid_len;
506       clib_memcpy (bmp->namespace_id, vcm->cfg.namespace_id, nsid_len);
507       bmp->options[APP_OPTIONS_NAMESPACE_SECRET] = vcm->cfg.namespace_secret;
508     }
509   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
510 }
511
512 static int
513 vppcom_app_attach (void)
514 {
515   int rv;
516
517   vppcom_app_send_attach ();
518   rv = vppcom_wait_for_app_state_change (STATE_APP_ATTACHED);
519   if (PREDICT_FALSE (rv))
520     {
521       if (VPPCOM_DEBUG > 0)
522         clib_warning ("[%d] application attach timed out, rv = %s (%d)",
523                       getpid (), vppcom_retval_str (rv), rv);
524       return rv;
525     }
526   return VPPCOM_OK;
527 }
528
529 static void
530 vppcom_app_detach (void)
531 {
532   vl_api_application_detach_t *bmp;
533   bmp = vl_msg_api_alloc (sizeof (*bmp));
534   memset (bmp, 0, sizeof (*bmp));
535
536   bmp->_vl_msg_id = ntohs (VL_API_APPLICATION_DETACH);
537   bmp->client_index = vcm->my_client_index;
538   bmp->context = htonl (0xfeedface);
539   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
540 }
541
542 static void
543 vl_api_application_attach_reply_t_handler (vl_api_application_attach_reply_t *
544                                            mp)
545 {
546   static svm_fifo_segment_create_args_t _a;
547   svm_fifo_segment_create_args_t *a = &_a;
548   int rv;
549
550   memset (a, 0, sizeof (*a));
551   if (mp->retval)
552     {
553       clib_warning ("[%d] attach failed: %U", getpid (),
554                     format_api_error, ntohl (mp->retval));
555       return;
556     }
557
558   if (mp->segment_name_length == 0)
559     {
560       clib_warning ("[%d] segment_name_length zero", getpid ());
561       return;
562     }
563
564   a->segment_name = (char *) mp->segment_name;
565   a->segment_size = mp->segment_size;
566
567   ASSERT (mp->app_event_queue_address);
568
569   /* Attach to the segment vpp created */
570   rv = svm_fifo_segment_attach (a);
571   vec_reset_length (a->new_segment_indices);
572   if (PREDICT_FALSE (rv))
573     {
574       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed", getpid (),
575                     mp->segment_name);
576       return;
577     }
578
579   vcm->app_event_queue =
580     uword_to_pointer (mp->app_event_queue_address,
581                       unix_shared_memory_queue_t *);
582
583   vcm->app_state = STATE_APP_ATTACHED;
584 }
585
586 static void
587 vl_api_application_detach_reply_t_handler (vl_api_application_detach_reply_t *
588                                            mp)
589 {
590   if (mp->retval)
591     clib_warning ("[%d] detach failed: %U", getpid (), format_api_error,
592                   ntohl (mp->retval));
593
594   vcm->app_state = STATE_APP_ENABLED;
595 }
596
597 static void
598 vl_api_disconnect_session_reply_t_handler (vl_api_disconnect_session_reply_t *
599                                            mp)
600 {
601   uword *p;
602
603   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
604   if (p)
605     {
606       session_t *session = 0;
607       int rv;
608       clib_spinlock_lock (&vcm->sessions_lockp);
609       rv = vppcom_session_at_index (p[0], &session);
610       if (PREDICT_FALSE (rv))
611         {
612           if (VPPCOM_DEBUG > 1)
613             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
614                           getpid (), p[0]);
615         }
616       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
617       session->state = STATE_DISCONNECT;
618       clib_spinlock_unlock (&vcm->sessions_lockp);
619     }
620   else
621     {
622       if (VPPCOM_DEBUG > 1)
623         clib_warning ("[%d] couldn't find session key %llx", getpid (),
624                       mp->handle);
625     }
626
627   if (mp->retval)
628     clib_warning ("[%d] disconnect_session failed: %U", getpid (),
629                   format_api_error, ntohl (mp->retval));
630 }
631
632 static void
633 vl_api_map_another_segment_t_handler (vl_api_map_another_segment_t * mp)
634 {
635   static svm_fifo_segment_create_args_t _a;
636   svm_fifo_segment_create_args_t *a = &_a;
637   int rv;
638
639   memset (a, 0, sizeof (*a));
640   a->segment_name = (char *) mp->segment_name;
641   a->segment_size = mp->segment_size;
642   /* Attach to the segment vpp created */
643   rv = svm_fifo_segment_attach (a);
644   vec_reset_length (a->new_segment_indices);
645   if (PREDICT_FALSE (rv))
646     {
647       clib_warning ("[%d] svm_fifo_segment_attach ('%s') failed",
648                     getpid (), mp->segment_name);
649       return;
650     }
651   if (VPPCOM_DEBUG > 1)
652     clib_warning ("[%d] mapped new segment '%s' size %d", getpid (),
653                   mp->segment_name, mp->segment_size);
654 }
655
656 static void
657 vl_api_disconnect_session_t_handler (vl_api_disconnect_session_t * mp)
658 {
659   session_t *session = 0;
660   vl_api_disconnect_session_reply_t *rmp;
661   uword *p;
662   int rv = 0;
663
664   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
665   if (p)
666     {
667       int rval;
668       clib_spinlock_lock (&vcm->sessions_lockp);
669       rval = vppcom_session_at_index (p[0], &session);
670       if (PREDICT_FALSE (rval))
671         {
672           if (VPPCOM_DEBUG > 1)
673             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
674                           getpid (), p[0]);
675         }
676       else
677         pool_put (vcm->sessions, session);
678       clib_spinlock_unlock (&vcm->sessions_lockp);
679       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
680     }
681   else
682     {
683       clib_warning ("[%d] couldn't find session key %llx", getpid (),
684                     mp->handle);
685       rv = -11;
686     }
687
688   rmp = vl_msg_api_alloc (sizeof (*rmp));
689   memset (rmp, 0, sizeof (*rmp));
690
691   rmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION_REPLY);
692   rmp->retval = htonl (rv);
693   rmp->handle = mp->handle;
694   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
695 }
696
697 static void
698 vl_api_reset_session_t_handler (vl_api_reset_session_t * mp)
699 {
700   session_t *session = 0;
701   vl_api_reset_session_reply_t *rmp;
702   uword *p;
703   int rv = 0;
704
705   p = hash_get (vcm->session_index_by_vpp_handles, mp->handle);
706   if (p)
707     {
708       int rval;
709       clib_spinlock_lock (&vcm->sessions_lockp);
710       rval = vppcom_session_at_index (p[0], &session);
711       if (PREDICT_FALSE (rval))
712         {
713           if (VPPCOM_DEBUG > 1)
714             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
715                           getpid (), p[0]);
716         }
717       else
718         pool_put (vcm->sessions, session);
719       clib_spinlock_unlock (&vcm->sessions_lockp);
720       hash_unset (vcm->session_index_by_vpp_handles, mp->handle);
721     }
722   else
723     {
724       clib_warning ("[%d] couldn't find session key %llx", getpid (),
725                     mp->handle);
726       rv = -11;
727     }
728
729   rmp = vl_msg_api_alloc (sizeof (*rmp));
730   memset (rmp, 0, sizeof (*rmp));
731   rmp->_vl_msg_id = ntohs (VL_API_RESET_SESSION_REPLY);
732   rmp->retval = htonl (rv);
733   rmp->handle = mp->handle;
734   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
735 }
736
737 static void
738 vl_api_connect_session_reply_t_handler (vl_api_connect_session_reply_t * mp)
739 {
740   session_t *session;
741   u32 session_index;
742   svm_fifo_t *rx_fifo, *tx_fifo;
743   u8 is_cut_thru = 0;
744   int rv;
745
746   if (mp->retval)
747     {
748       clib_warning ("[%d] connect failed: %U", getpid (), format_api_error,
749                     ntohl (mp->retval));
750       return;
751     }
752
753   session_index = mp->context;
754   if (VPPCOM_DEBUG > 1)
755     clib_warning ("[%d] session_index = %d 0x%08x", getpid (),
756                   session_index, session_index);
757
758   clib_spinlock_lock (&vcm->sessions_lockp);
759   if (pool_is_free_index (vcm->sessions, session_index))
760     {
761       clib_spinlock_unlock (&vcm->sessions_lockp);
762       if (VPPCOM_DEBUG > 1)
763         clib_warning ("[%d] invalid session, sid %d is closed!",
764                       getpid (), session_index);
765       return;
766     }
767
768   /* We've been redirected */
769   if (mp->segment_name_length > 0)
770     {
771       static svm_fifo_segment_create_args_t _a;
772       svm_fifo_segment_create_args_t *a = &_a;
773
774       is_cut_thru = 1;
775       memset (a, 0, sizeof (*a));
776       a->segment_name = (char *) mp->segment_name;
777       if (VPPCOM_DEBUG > 1)
778         clib_warning ("[%d] cut-thru segment: %s\n",
779                       getpid (), a->segment_name);
780
781       rv = svm_fifo_segment_attach (a);
782       vec_reset_length (a->new_segment_indices);
783       if (PREDICT_FALSE (rv))
784         {
785           clib_spinlock_unlock (&vcm->sessions_lockp);
786           clib_warning ("[%d] sm_fifo_segment_attach ('%s') failed",
787                         getpid (), a->segment_name);
788           return;
789         }
790     }
791
792   /*
793    * Setup session
794    */
795   session = pool_elt_at_index (vcm->sessions, session_index);
796   session->is_cut_thru = is_cut_thru;
797   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
798                                                unix_shared_memory_queue_t *);
799
800   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
801   rx_fifo->client_session_index = session_index;
802   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
803   tx_fifo->client_session_index = session_index;
804
805   session->server_rx_fifo = rx_fifo;
806   session->server_tx_fifo = tx_fifo;
807   session->vpp_handle = mp->handle;
808   session->state = STATE_CONNECT;
809
810   /* Add it to lookup table */
811   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
812
813   if (VPPCOM_DEBUG > 1)
814     clib_warning ("[%d] client sid %d\n"
815                   "  session_rx_fifo %p, refcnt %d\n"
816                   "  session_tx_fifo %p, refcnt %d",
817                   getpid (), session_index,
818                   session->server_rx_fifo,
819                   session->server_rx_fifo->refcnt,
820                   session->server_tx_fifo, session->server_tx_fifo->refcnt);
821
822   clib_spinlock_unlock (&vcm->sessions_lockp);
823 }
824
825 static void
826 vppcom_send_connect_sock (session_t * session, u32 session_index)
827 {
828   vl_api_connect_sock_t *cmp;
829
830   /* Assumes caller as acquired the spinlock: vcm->sessions_lockp */
831   session->is_server = 0;
832   cmp = vl_msg_api_alloc (sizeof (*cmp));
833   memset (cmp, 0, sizeof (*cmp));
834   cmp->_vl_msg_id = ntohs (VL_API_CONNECT_SOCK);
835   cmp->client_index = vcm->my_client_index;
836   cmp->context = session_index;
837
838   if (VPPCOM_DEBUG > 1)
839     clib_warning ("[%d] session_index = %d 0x%08x",
840                   getpid (), session_index, session_index);
841
842   cmp->vrf = session->vrf;
843   cmp->is_ip4 = session->peer_addr.is_ip4;
844   clib_memcpy (cmp->ip, &session->peer_addr.ip46, sizeof (cmp->ip));
845   cmp->port = session->peer_port;
846   cmp->proto = session->proto;
847   clib_memcpy (cmp->options, session->options, sizeof (cmp->options));
848   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & cmp);
849 }
850
851 static inline void
852 vppcom_send_disconnect (session_t * session)
853 {
854   vl_api_disconnect_session_t *dmp;
855
856   /* Assumes caller as acquired the spinlock: vcm->sessions_lockp */
857   dmp = vl_msg_api_alloc (sizeof (*dmp));
858   memset (dmp, 0, sizeof (*dmp));
859   dmp->_vl_msg_id = ntohs (VL_API_DISCONNECT_SESSION);
860   dmp->client_index = vcm->my_client_index;
861   dmp->handle = session->vpp_handle;
862   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & dmp);
863 }
864
865 static void
866 vl_api_bind_sock_reply_t_handler (vl_api_bind_sock_reply_t * mp)
867 {
868   session_t *session = 0;
869   int rv;
870
871   if (mp->retval)
872     clib_warning ("[%d] bind failed: %U", getpid (), format_api_error,
873                   ntohl (mp->retval));
874
875   ASSERT (vcm->bind_session_index != ~0);
876
877   clib_spinlock_lock (&vcm->sessions_lockp);
878   rv = vppcom_session_at_index (vcm->bind_session_index, &session);
879   if (rv == VPPCOM_OK)
880     {
881       session->vpp_handle = mp->handle;
882       hash_set (vcm->session_index_by_vpp_handles, mp->handle,
883                 vcm->bind_session_index);
884       session->state = mp->retval ? STATE_FAILED : STATE_LISTEN;
885       vcm->bind_session_index = ~0;
886     }
887   clib_spinlock_unlock (&vcm->sessions_lockp);
888 }
889
890 static void
891 vl_api_unbind_sock_reply_t_handler (vl_api_unbind_sock_reply_t * mp)
892 {
893   session_t *session = 0;
894   int rv;
895
896   clib_spinlock_lock (&vcm->sessions_lockp);
897   rv = vppcom_session_at_index (vcm->bind_session_index, &session);
898   if (rv == VPPCOM_OK)
899     {
900       if ((VPPCOM_DEBUG > 1) && (mp->retval))
901         clib_warning ("[%d] unbind failed: %U", getpid (), format_api_error,
902                       ntohl (mp->retval));
903
904       vcm->bind_session_index = ~0;
905       session->state = STATE_START;
906     }
907   clib_spinlock_unlock (&vcm->sessions_lockp);
908 }
909
910 u8 *
911 format_ip4_address (u8 * s, va_list * args)
912 {
913   u8 *a = va_arg (*args, u8 *);
914   return format (s, "%d.%d.%d.%d", a[0], a[1], a[2], a[3]);
915 }
916
917 u8 *
918 format_ip6_address (u8 * s, va_list * args)
919 {
920   ip6_address_t *a = va_arg (*args, ip6_address_t *);
921   u32 i, i_max_n_zero, max_n_zeros, i_first_zero, n_zeros, last_double_colon;
922
923   i_max_n_zero = ARRAY_LEN (a->as_u16);
924   max_n_zeros = 0;
925   i_first_zero = i_max_n_zero;
926   n_zeros = 0;
927   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
928     {
929       u32 is_zero = a->as_u16[i] == 0;
930       if (is_zero && i_first_zero >= ARRAY_LEN (a->as_u16))
931         {
932           i_first_zero = i;
933           n_zeros = 0;
934         }
935       n_zeros += is_zero;
936       if ((!is_zero && n_zeros > max_n_zeros)
937           || (i + 1 >= ARRAY_LEN (a->as_u16) && n_zeros > max_n_zeros))
938         {
939           i_max_n_zero = i_first_zero;
940           max_n_zeros = n_zeros;
941           i_first_zero = ARRAY_LEN (a->as_u16);
942           n_zeros = 0;
943         }
944     }
945
946   last_double_colon = 0;
947   for (i = 0; i < ARRAY_LEN (a->as_u16); i++)
948     {
949       if (i == i_max_n_zero && max_n_zeros > 1)
950         {
951           s = format (s, "::");
952           i += max_n_zeros - 1;
953           last_double_colon = 1;
954         }
955       else
956         {
957           s = format (s, "%s%x",
958                       (last_double_colon || i == 0) ? "" : ":",
959                       clib_net_to_host_u16 (a->as_u16[i]));
960           last_double_colon = 0;
961         }
962     }
963
964   return s;
965 }
966
967 /* Format an IP46 address. */
968 u8 *
969 format_ip46_address (u8 * s, va_list * args)
970 {
971   ip46_address_t *ip46 = va_arg (*args, ip46_address_t *);
972   ip46_type_t type = va_arg (*args, ip46_type_t);
973   int is_ip4 = 1;
974
975   switch (type)
976     {
977     case IP46_TYPE_ANY:
978       is_ip4 = ip46_address_is_ip4 (ip46);
979       break;
980     case IP46_TYPE_IP4:
981       is_ip4 = 1;
982       break;
983     case IP46_TYPE_IP6:
984       is_ip4 = 0;
985       break;
986     }
987
988   return is_ip4 ?
989     format (s, "%U", format_ip4_address, &ip46->ip4) :
990     format (s, "%U", format_ip6_address, &ip46->ip6);
991 }
992
993 static inline void
994 vppcom_send_accept_session_reply (u32 handle, int retval)
995 {
996   vl_api_accept_session_reply_t *rmp;
997
998   rmp = vl_msg_api_alloc (sizeof (*rmp));
999   memset (rmp, 0, sizeof (*rmp));
1000   rmp->_vl_msg_id = ntohs (VL_API_ACCEPT_SESSION_REPLY);
1001   rmp->retval = htonl (retval);
1002   rmp->handle = handle;
1003   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & rmp);
1004 }
1005
1006 static void
1007 vl_api_accept_session_t_handler (vl_api_accept_session_t * mp)
1008 {
1009   svm_fifo_t *rx_fifo, *tx_fifo;
1010   session_t *session;
1011   u32 session_index;
1012
1013   clib_spinlock_lock (&vcm->sessions_lockp);
1014   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1015     {
1016       clib_warning ("[%d] client session queue is full!", getpid ());
1017       vppcom_send_accept_session_reply (VNET_API_ERROR_QUEUE_FULL,
1018                                         mp->handle);
1019       clib_spinlock_unlock (&vcm->sessions_lockp);
1020       return;
1021     }
1022
1023   /* Allocate local session and set it up */
1024   pool_get (vcm->sessions, session);
1025   memset (session, 0, sizeof (*session));
1026   session_index = session - vcm->sessions;
1027
1028   rx_fifo = uword_to_pointer (mp->server_rx_fifo, svm_fifo_t *);
1029   rx_fifo->client_session_index = session_index;
1030   tx_fifo = uword_to_pointer (mp->server_tx_fifo, svm_fifo_t *);
1031   tx_fifo->client_session_index = session_index;
1032
1033   session->vpp_handle = mp->handle;
1034   session->server_rx_fifo = rx_fifo;
1035   session->server_tx_fifo = tx_fifo;
1036   session->vpp_event_queue = uword_to_pointer (mp->vpp_event_queue_address,
1037                                                unix_shared_memory_queue_t *);
1038   session->state = STATE_ACCEPT;
1039   session->is_cut_thru = 0;
1040   session->is_server = 1;
1041   session->peer_port = mp->port;
1042   session->peer_addr.is_ip4 = mp->is_ip4;
1043   clib_memcpy (&session->peer_addr.ip46, mp->ip,
1044                sizeof (session->peer_addr.ip46));
1045
1046   /* Add it to lookup table */
1047   hash_set (vcm->session_index_by_vpp_handles, mp->handle, session_index);
1048
1049   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1050   clib_spinlock_unlock (&vcm->sessions_lockp);
1051
1052   if (VPPCOM_DEBUG > 1)
1053     {
1054       u8 *ip_str = format (0, "%U", format_ip46_address, &mp->ip, mp->is_ip4);
1055       clib_warning ("[%d] received request to accept session (sid %d) "
1056                     "from %s:%d", getpid (), session_index, ip_str,
1057                     clib_net_to_host_u16 (mp->port));
1058       vec_free (ip_str);
1059     }
1060 }
1061
1062 static void
1063 vppcom_send_connect_session_reply (session_t * session, u32 context,
1064                                    int retval, int handle)
1065 {
1066   vl_api_connect_session_reply_t *rmp;
1067   u32 len;
1068   unix_shared_memory_queue_t *client_q;
1069
1070   rmp = vl_msg_api_alloc (sizeof (*rmp));
1071   memset (rmp, 0, sizeof (*rmp));
1072
1073   rmp->_vl_msg_id = ntohs (VL_API_CONNECT_SESSION_REPLY);
1074   rmp->context = session ? session->client_context : context;
1075   rmp->retval = htonl (retval);
1076   rmp->handle = session ? session->vpp_handle : handle;
1077
1078   if (session)
1079     {
1080       rmp->server_rx_fifo = pointer_to_uword (session->server_rx_fifo);
1081       rmp->server_tx_fifo = pointer_to_uword (session->server_tx_fifo);
1082       rmp->vpp_event_queue_address =
1083         pointer_to_uword (session->vpp_event_queue);
1084       rmp->segment_size = vcm->cfg.segment_size;
1085       len = vec_len (session->segment_name);
1086       rmp->segment_name_length = clib_min (len, sizeof (rmp->segment_name));
1087       clib_memcpy (rmp->segment_name, session->segment_name,
1088                    rmp->segment_name_length - 1);
1089       clib_memcpy (rmp->lcl_ip, session->lcl_addr.ip46.as_u8,
1090                    sizeof (rmp->lcl_ip));
1091       rmp->is_ip4 = session->lcl_addr.is_ip4;
1092     }
1093
1094   client_q = uword_to_pointer (session->client_queue_address,
1095                                unix_shared_memory_queue_t *);
1096   ASSERT (client_q);
1097   vl_msg_api_send_shmem (client_q, (u8 *) & rmp);
1098 }
1099
1100 /*
1101  * Acting as server for redirected connect requests
1102  */
1103 static void
1104 vl_api_connect_sock_t_handler (vl_api_connect_sock_t * mp)
1105 {
1106   u32 session_index;
1107   session_t *session = 0;
1108
1109   clib_spinlock_lock (&vcm->sessions_lockp);
1110   if (!clib_fifo_free_elts (vcm->client_session_index_fifo))
1111     {
1112       if (VPPCOM_DEBUG > 1)
1113         clib_warning ("[%d] client session queue is full!", getpid ());
1114       clib_spinlock_unlock (&vcm->sessions_lockp);
1115       vppcom_send_accept_session_reply (VNET_API_ERROR_QUEUE_FULL, 0);
1116       return;
1117     }
1118
1119   pool_get (vcm->sessions, session);
1120   memset (session, 0, sizeof (*session));
1121   session_index = session - vcm->sessions;
1122
1123   session->client_context = mp->context;
1124   session->vpp_handle = session_index;
1125   session->client_queue_address = mp->client_queue_address;
1126   session->is_cut_thru = 1;
1127   session->is_server = 1;
1128   session->peer_port = mp->port;
1129   session->peer_addr.is_ip4 = mp->is_ip4;
1130   clib_memcpy (&session->peer_addr.ip46, mp->ip,
1131                sizeof (session->peer_addr.ip46));
1132
1133   session->state = STATE_ACCEPT;
1134   clib_fifo_add1 (vcm->client_session_index_fifo, session_index);
1135   if (VPPCOM_DEBUG > 1)
1136     clib_warning
1137       ("[%d] Got a cut-thru connect request to client: "
1138        "sid %d, clib_fifo_elts %u!\n", getpid (), session_index,
1139        clib_fifo_elts (vcm->client_session_index_fifo));
1140   clib_spinlock_unlock (&vcm->sessions_lockp);
1141 }
1142
1143 static void
1144 vppcom_send_bind_sock (session_t * session)
1145 {
1146   vl_api_bind_sock_t *bmp;
1147
1148   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
1149   session->is_server = 1;
1150   bmp = vl_msg_api_alloc (sizeof (*bmp));
1151   memset (bmp, 0, sizeof (*bmp));
1152
1153   bmp->_vl_msg_id = ntohs (VL_API_BIND_SOCK);
1154   bmp->client_index = vcm->my_client_index;
1155   bmp->context = htonl (0xfeedface);
1156   bmp->vrf = session->vrf;
1157   bmp->is_ip4 = session->lcl_addr.is_ip4;
1158   clib_memcpy (bmp->ip, &session->lcl_addr.ip46, sizeof (bmp->ip));
1159   bmp->port = session->lcl_port;
1160   bmp->proto = session->proto;
1161   clib_memcpy (bmp->options, session->options, sizeof (bmp->options));
1162   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & bmp);
1163 }
1164
1165 static void
1166 vppcom_send_unbind_sock (u32 session_index)
1167 {
1168   vl_api_unbind_sock_t *ump;
1169   session_t *session = 0;
1170   int rv;
1171
1172   clib_spinlock_lock (&vcm->sessions_lockp);
1173   rv = vppcom_session_at_index (session_index, &session);
1174   if (PREDICT_FALSE (rv))
1175     {
1176       clib_spinlock_unlock (&vcm->sessions_lockp);
1177       if (VPPCOM_DEBUG > 0)
1178         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1179                       getpid (), session_index);
1180       return;
1181     }
1182
1183   ump = vl_msg_api_alloc (sizeof (*ump));
1184   memset (ump, 0, sizeof (*ump));
1185
1186   ump->_vl_msg_id = ntohs (VL_API_UNBIND_SOCK);
1187   ump->client_index = vcm->my_client_index;
1188   ump->handle = session->vpp_handle;
1189   clib_spinlock_unlock (&vcm->sessions_lockp);
1190   vl_msg_api_send_shmem (vcm->vl_input_queue, (u8 *) & ump);
1191 }
1192
1193 static int
1194 vppcom_session_unbind_cut_thru (session_t * session, u32 session_index)
1195 {
1196   svm_fifo_segment_main_t *sm = &svm_fifo_segment_main;
1197   svm_fifo_segment_private_t *seg;
1198   int rv = VPPCOM_OK;
1199
1200   if (VPPCOM_DEBUG > 1)
1201     clib_warning ("[%d] sid %d, seg_nxd %d:\n"
1202                   "  server_rx_fifo %p, refcnt = %d\n"
1203                   "  server_tx_fifo %p, refcnt = %d",
1204                   getpid (), session_index, session->sm_seg_index,
1205                   session->server_rx_fifo, session->server_rx_fifo->refcnt,
1206                   session->server_tx_fifo, session->server_tx_fifo->refcnt);
1207
1208   seg = vec_elt_at_index (sm->segments, session->sm_seg_index);
1209   svm_fifo_segment_free_fifo (seg, session->server_rx_fifo,
1210                               FIFO_SEGMENT_RX_FREELIST);
1211   svm_fifo_segment_free_fifo (seg, session->server_tx_fifo,
1212                               FIFO_SEGMENT_TX_FREELIST);
1213   svm_fifo_segment_delete (seg);
1214
1215   return rv;
1216 }
1217
1218 static int
1219 vppcom_session_unbind (u32 session_index)
1220 {
1221   int rv;
1222
1223   clib_spinlock_lock (&vcm->sessions_lockp);
1224   if (PREDICT_FALSE (pool_is_free_index (vcm->sessions, session_index)))
1225     {
1226       clib_spinlock_unlock (&vcm->sessions_lockp);
1227       if (VPPCOM_DEBUG > 1)
1228         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1229                       getpid (), session_index);
1230       return VPPCOM_EBADFD;
1231     }
1232   clib_spinlock_unlock (&vcm->sessions_lockp);
1233
1234   vcm->bind_session_index = session_index;
1235   vppcom_send_unbind_sock (session_index);
1236   rv = vppcom_wait_for_session_state_change (session_index, STATE_START,
1237                                              vcm->cfg.session_timeout);
1238   if (PREDICT_FALSE (rv))
1239     {
1240       vcm->bind_session_index = ~0;
1241       if (VPPCOM_DEBUG > 0)
1242         clib_warning ("[%d] server unbind timed out, rv = %s (%d)",
1243                       getpid (), vppcom_retval_str (rv), rv);
1244       return rv;
1245     }
1246   return VPPCOM_OK;
1247 }
1248
1249 static inline int
1250 vppcom_session_disconnect (u32 session_index)
1251 {
1252   int rv;
1253   session_t *session;
1254
1255   clib_spinlock_lock (&vcm->sessions_lockp);
1256   rv = vppcom_session_at_index (session_index, &session);
1257   if (PREDICT_FALSE (rv))
1258     {
1259       clib_spinlock_unlock (&vcm->sessions_lockp);
1260       if (VPPCOM_DEBUG > 1)
1261         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
1262                       getpid (), session_index);
1263       return rv;
1264     }
1265
1266   if (!session->is_cut_thru)
1267     {
1268       vppcom_send_disconnect (session);
1269       clib_spinlock_unlock (&vcm->sessions_lockp);
1270
1271       rv = vppcom_wait_for_session_state_change (session_index,
1272                                                  STATE_DISCONNECT, 1.0);
1273       if ((VPPCOM_DEBUG > 0) && (rv < 0))
1274         clib_warning ("[%d] disconnect (session %d) failed, rv = %s (%d)",
1275                       getpid (), session_index, vppcom_retval_str (rv), rv);
1276     }
1277   else
1278     clib_spinlock_unlock (&vcm->sessions_lockp);
1279
1280   return VPPCOM_OK;
1281 }
1282
1283 #define foreach_sock_msg                                        \
1284 _(SESSION_ENABLE_DISABLE_REPLY, session_enable_disable_reply)   \
1285 _(BIND_SOCK_REPLY, bind_sock_reply)                             \
1286 _(UNBIND_SOCK_REPLY, unbind_sock_reply)                         \
1287 _(ACCEPT_SESSION, accept_session)                               \
1288 _(CONNECT_SOCK, connect_sock)                                   \
1289 _(CONNECT_SESSION_REPLY, connect_session_reply)                 \
1290 _(DISCONNECT_SESSION, disconnect_session)                       \
1291 _(DISCONNECT_SESSION_REPLY, disconnect_session_reply)           \
1292 _(RESET_SESSION, reset_session)                                 \
1293 _(APPLICATION_ATTACH_REPLY, application_attach_reply)           \
1294 _(APPLICATION_DETACH_REPLY, application_detach_reply)           \
1295 _(MAP_ANOTHER_SEGMENT, map_another_segment)
1296
1297 static void
1298 vppcom_api_hookup (void)
1299 {
1300 #define _(N,n)                                                  \
1301     vl_msg_api_set_handlers(VL_API_##N, #n,                     \
1302                            vl_api_##n##_t_handler,              \
1303                            vl_noop_handler,                     \
1304                            vl_api_##n##_t_endian,               \
1305                            vl_api_##n##_t_print,                \
1306                            sizeof(vl_api_##n##_t), 1);
1307   foreach_sock_msg;
1308 #undef _
1309 }
1310
1311 static void
1312 vppcom_cfg_init (vppcom_cfg_t * vcl_cfg)
1313 {
1314   ASSERT (vcl_cfg);
1315
1316   vcl_cfg->heapsize = (256ULL << 20);
1317   vcl_cfg->segment_baseva = 0x200000000ULL;
1318   vcl_cfg->segment_size = (256 << 20);
1319   vcl_cfg->add_segment_size = (128 << 20);
1320   vcl_cfg->preallocated_fifo_pairs = 8;
1321   vcl_cfg->rx_fifo_size = (1 << 20);
1322   vcl_cfg->tx_fifo_size = (1 << 20);
1323   vcl_cfg->event_queue_size = 2048;
1324   vcl_cfg->listen_queue_size = CLIB_CACHE_LINE_BYTES / sizeof (u32);
1325   vcl_cfg->app_timeout = 10 * 60.0;
1326   vcl_cfg->session_timeout = 10 * 60.0;
1327   vcl_cfg->accept_timeout = 60.0;
1328 }
1329
1330 static void
1331 vppcom_cfg_heapsize (char *conf_fname)
1332 {
1333   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1334   FILE *fp;
1335   char inbuf[4096];
1336   int argc = 1;
1337   char **argv = NULL;
1338   char *arg = NULL;
1339   char *p;
1340   int i;
1341   u8 *sizep;
1342   u32 size;
1343   void *vcl_mem;
1344   void *heap;
1345
1346   fp = fopen (conf_fname, "r");
1347   if (fp == NULL)
1348     {
1349       if (VPPCOM_DEBUG > 0)
1350         fprintf (stderr, "open configuration file '%s' failed\n", conf_fname);
1351       goto defaulted;
1352     }
1353   argv = calloc (1, sizeof (char *));
1354   if (argv == NULL)
1355     goto defaulted;
1356
1357   while (1)
1358     {
1359       if (fgets (inbuf, 4096, fp) == 0)
1360         break;
1361       p = strtok (inbuf, " \t\n");
1362       while (p != NULL)
1363         {
1364           if (*p == '#')
1365             break;
1366           argc++;
1367           char **tmp = realloc (argv, argc * sizeof (char *));
1368           if (tmp == NULL)
1369             goto defaulted;
1370           argv = tmp;
1371           arg = strndup (p, 1024);
1372           if (arg == NULL)
1373             goto defaulted;
1374           argv[argc - 1] = arg;
1375           p = strtok (NULL, " \t\n");
1376         }
1377     }
1378
1379   fclose (fp);
1380   fp = NULL;
1381
1382   char **tmp = realloc (argv, (argc + 1) * sizeof (char *));
1383   if (tmp == NULL)
1384     goto defaulted;
1385   argv = tmp;
1386   argv[argc] = NULL;
1387
1388   /*
1389    * Look for and parse the "heapsize" config parameter.
1390    * Manual since none of the clib infra has been bootstrapped yet.
1391    *
1392    * Format: heapsize <nn>[mM][gG]
1393    */
1394
1395   for (i = 1; i < (argc - 1); i++)
1396     {
1397       if (!strncmp (argv[i], "heapsize", 8))
1398         {
1399           sizep = (u8 *) argv[i + 1];
1400           size = 0;
1401           while (*sizep >= '0' && *sizep <= '9')
1402             {
1403               size *= 10;
1404               size += *sizep++ - '0';
1405             }
1406           if (size == 0)
1407             {
1408               if (VPPCOM_DEBUG > 0)
1409                 clib_warning ("[%d] parse error '%s %s', "
1410                               "using default heapsize %lld (0x%llx)",
1411                               getpid (), argv[i], argv[i + 1],
1412                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1413               goto defaulted;
1414             }
1415
1416           if (*sizep == 'g' || *sizep == 'G')
1417             vcl_cfg->heapsize = size << 30;
1418           else if (*sizep == 'm' || *sizep == 'M')
1419             vcl_cfg->heapsize = size << 20;
1420           else
1421             {
1422               if (VPPCOM_DEBUG > 0)
1423                 clib_warning ("[%d] parse error '%s %s', "
1424                               "using default heapsize %lld (0x%llx)",
1425                               getpid (), argv[i], argv[i + 1],
1426                               vcl_cfg->heapsize, vcl_cfg->heapsize);
1427               goto defaulted;
1428             }
1429         }
1430     }
1431
1432 defaulted:
1433   if (fp != NULL)
1434     fclose (fp);
1435   if (argv != NULL)
1436     free (argv);
1437
1438   vcl_mem = mmap (0, vcl_cfg->heapsize, PROT_READ | PROT_WRITE,
1439                   MAP_SHARED | MAP_ANONYMOUS, -1, 0);
1440   if (vcl_mem <= 0)
1441     {
1442       clib_unix_error ("[%d] ERROR: mmap(0, %lld == 0x%llx, "
1443                        "PROT_READ | PROT_WRITE,MAP_SHARED | MAP_ANONYMOUS, "
1444                        "-1, 0) failed!",
1445                        getpid (), vcl_cfg->heapsize, vcl_cfg->heapsize);
1446       return;
1447     }
1448   heap = clib_mem_init (vcl_mem, vcl_cfg->heapsize);
1449   if (!heap)
1450     {
1451       clib_warning ("[%d] ERROR: clib_mem_init() failed!", getpid ());
1452       return;
1453     }
1454   vcl_mem = clib_mem_alloc (sizeof (_vppcom_main));
1455   if (!vcl_mem)
1456     {
1457       clib_warning ("[%d] ERROR: clib_mem_alloc() failed!", getpid ());
1458       return;
1459     }
1460
1461   clib_memcpy (vcl_mem, &_vppcom_main, sizeof (_vppcom_main));
1462   vcm = vcl_mem;
1463
1464   if (VPPCOM_DEBUG > 0)
1465     clib_warning ("[%d] allocated VCL heap = %p, size %lld (0x%llx)",
1466                   getpid (), heap, vcl_cfg->heapsize, vcl_cfg->heapsize);
1467 }
1468
1469 static void
1470 vppcom_cfg_read (char *conf_fname)
1471 {
1472   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1473   int fd;
1474   unformat_input_t _input, *input = &_input;
1475   unformat_input_t _line_input, *line_input = &_line_input;
1476   u8 vc_cfg_input = 0;
1477   u8 *chroot_path;
1478   struct stat s;
1479   u32 uid, gid;
1480
1481   fd = open (conf_fname, O_RDONLY);
1482   if (fd < 0)
1483     {
1484       if (VPPCOM_DEBUG > 0)
1485         clib_warning ("[%d] open configuration file '%s' failed!",
1486                       getpid (), conf_fname);
1487       goto file_done;
1488     }
1489
1490   if (fstat (fd, &s) < 0)
1491     {
1492       if (VPPCOM_DEBUG > 0)
1493         clib_warning ("[%d] failed to stat `%s'", getpid (), conf_fname);
1494       goto file_done;
1495     }
1496
1497   if (!(S_ISREG (s.st_mode) || S_ISLNK (s.st_mode)))
1498     {
1499       if (VPPCOM_DEBUG > 0)
1500         clib_warning ("[%d] not a regular file `%s'", getpid (), conf_fname);
1501       goto file_done;
1502     }
1503
1504   unformat_init_clib_file (input, fd);
1505
1506   while (unformat_check_input (input) != UNFORMAT_END_OF_INPUT)
1507     {
1508       (void) unformat_user (input, unformat_line_input, line_input);
1509       unformat_skip_white_space (line_input);
1510
1511       if (unformat (line_input, "vcl {"))
1512         {
1513           vc_cfg_input = 1;
1514           continue;
1515         }
1516
1517       if (vc_cfg_input)
1518         {
1519           if (unformat (line_input, "heapsize %s", &chroot_path))
1520             {
1521               vec_terminate_c_string (chroot_path);
1522               if (VPPCOM_DEBUG > 0)
1523                 clib_warning ("[%d] configured heapsize %s, "
1524                               "actual heapsize %lld (0x%llx)",
1525                               getpid (), chroot_path, vcl_cfg->heapsize,
1526                               vcl_cfg->heapsize);
1527               vec_free (chroot_path);
1528             }
1529           else if (unformat (line_input, "api-prefix %s", &chroot_path))
1530             {
1531               vec_terminate_c_string (chroot_path);
1532               vl_set_memory_root_path ((char *) chroot_path);
1533               if (VPPCOM_DEBUG > 0)
1534                 clib_warning ("[%d] configured api-prefix %s",
1535                               getpid (), chroot_path);
1536               chroot_path = 0;  /* Don't vec_free() it! */
1537             }
1538           else if (unformat (line_input, "uid %d", &uid))
1539             {
1540               vl_set_memory_uid (uid);
1541               if (VPPCOM_DEBUG > 0)
1542                 clib_warning ("[%d] configured uid %d", getpid (), uid);
1543             }
1544           else if (unformat (line_input, "gid %d", &gid))
1545             {
1546               vl_set_memory_gid (gid);
1547               if (VPPCOM_DEBUG > 0)
1548                 clib_warning ("[%d] configured gid %d", getpid (), gid);
1549             }
1550           else if (unformat (line_input, "segment-baseva 0x%lx",
1551                              &vcl_cfg->segment_baseva))
1552             {
1553               if (VPPCOM_DEBUG > 0)
1554                 clib_warning ("[%d] configured segment_baseva 0x%lx",
1555                               getpid (), vcl_cfg->segment_baseva);
1556             }
1557           else if (unformat (line_input, "segment-size 0x%lx",
1558                              &vcl_cfg->segment_size))
1559             {
1560               if (VPPCOM_DEBUG > 0)
1561                 clib_warning ("[%d] configured segment_size 0x%lx (%ld)",
1562                               getpid (), vcl_cfg->segment_size,
1563                               vcl_cfg->segment_size);
1564             }
1565           else if (unformat (line_input, "segment-size %ld",
1566                              &vcl_cfg->segment_size))
1567             {
1568               if (VPPCOM_DEBUG > 0)
1569                 clib_warning ("[%d] configured segment_size %ld (0x%lx)",
1570                               getpid (), vcl_cfg->segment_size,
1571                               vcl_cfg->segment_size);
1572             }
1573           else if (unformat (line_input, "add-segment-size 0x%lx",
1574                              &vcl_cfg->add_segment_size))
1575             {
1576               if (VPPCOM_DEBUG > 0)
1577                 clib_warning
1578                   ("[%d] configured add_segment_size 0x%lx (%ld)",
1579                    getpid (), vcl_cfg->add_segment_size,
1580                    vcl_cfg->add_segment_size);
1581             }
1582           else if (unformat (line_input, "add-segment-size %ld",
1583                              &vcl_cfg->add_segment_size))
1584             {
1585               if (VPPCOM_DEBUG > 0)
1586                 clib_warning
1587                   ("[%d] configured add_segment_size %ld (0x%lx)",
1588                    getpid (), vcl_cfg->add_segment_size,
1589                    vcl_cfg->add_segment_size);
1590             }
1591           else if (unformat (line_input, "preallocated-fifo-pairs %d",
1592                              &vcl_cfg->preallocated_fifo_pairs))
1593             {
1594               if (VPPCOM_DEBUG > 0)
1595                 clib_warning ("[%d] configured preallocated_fifo_pairs "
1596                               "%d (0x%x)", getpid (),
1597                               vcl_cfg->preallocated_fifo_pairs,
1598                               vcl_cfg->preallocated_fifo_pairs);
1599             }
1600           else if (unformat (line_input, "rx-fifo-size 0x%lx",
1601                              &vcl_cfg->rx_fifo_size))
1602             {
1603               if (VPPCOM_DEBUG > 0)
1604                 clib_warning ("[%d] configured rx_fifo_size 0x%lx (%ld)",
1605                               getpid (), vcl_cfg->rx_fifo_size,
1606                               vcl_cfg->rx_fifo_size);
1607             }
1608           else if (unformat (line_input, "rx-fifo-size %ld",
1609                              &vcl_cfg->rx_fifo_size))
1610             {
1611               if (VPPCOM_DEBUG > 0)
1612                 clib_warning ("[%d] configured rx_fifo_size %ld (0x%lx)",
1613                               getpid (), vcl_cfg->rx_fifo_size,
1614                               vcl_cfg->rx_fifo_size);
1615             }
1616           else if (unformat (line_input, "tx-fifo-size 0x%lx",
1617                              &vcl_cfg->tx_fifo_size))
1618             {
1619               if (VPPCOM_DEBUG > 0)
1620                 clib_warning ("[%d] configured tx_fifo_size 0x%lx (%ld)",
1621                               getpid (), vcl_cfg->tx_fifo_size,
1622                               vcl_cfg->tx_fifo_size);
1623             }
1624           else if (unformat (line_input, "tx-fifo-size %ld",
1625                              &vcl_cfg->tx_fifo_size))
1626             {
1627               if (VPPCOM_DEBUG > 0)
1628                 clib_warning ("[%d] configured tx_fifo_size %ld (0x%lx)",
1629                               getpid (), vcl_cfg->tx_fifo_size,
1630                               vcl_cfg->tx_fifo_size);
1631             }
1632           else if (unformat (line_input, "event-queue-size 0x%lx",
1633                              &vcl_cfg->event_queue_size))
1634             {
1635               if (VPPCOM_DEBUG > 0)
1636                 clib_warning ("[%d] configured event_queue_size 0x%lx (%ld)",
1637                               getpid (), vcl_cfg->event_queue_size,
1638                               vcl_cfg->event_queue_size);
1639             }
1640           else if (unformat (line_input, "event-queue-size %ld",
1641                              &vcl_cfg->event_queue_size))
1642             {
1643               if (VPPCOM_DEBUG > 0)
1644                 clib_warning ("[%d] configured event_queue_size %ld (0x%lx)",
1645                               getpid (), vcl_cfg->event_queue_size,
1646                               vcl_cfg->event_queue_size);
1647             }
1648           else if (unformat (line_input, "listen-queue-size 0x%lx",
1649                              &vcl_cfg->listen_queue_size))
1650             {
1651               if (VPPCOM_DEBUG > 0)
1652                 clib_warning ("[%d] configured listen_queue_size 0x%lx (%ld)",
1653                               getpid (), vcl_cfg->listen_queue_size,
1654                               vcl_cfg->listen_queue_size);
1655             }
1656           else if (unformat (line_input, "listen-queue-size %ld",
1657                              &vcl_cfg->listen_queue_size))
1658             {
1659               if (VPPCOM_DEBUG > 0)
1660                 clib_warning ("[%d] configured listen_queue_size %ld (0x%lx)",
1661                               getpid (), vcl_cfg->listen_queue_size,
1662                               vcl_cfg->listen_queue_size);
1663             }
1664           else if (unformat (line_input, "app-timeout %f",
1665                              &vcl_cfg->app_timeout))
1666             {
1667               if (VPPCOM_DEBUG > 0)
1668                 clib_warning ("[%d] configured app_timeout %f",
1669                               getpid (), vcl_cfg->app_timeout);
1670             }
1671           else if (unformat (line_input, "session-timeout %f",
1672                              &vcl_cfg->session_timeout))
1673             {
1674               if (VPPCOM_DEBUG > 0)
1675                 clib_warning ("[%d] configured session_timeout %f",
1676                               getpid (), vcl_cfg->session_timeout);
1677             }
1678           else if (unformat (line_input, "accept-timeout %f",
1679                              &vcl_cfg->accept_timeout))
1680             {
1681               if (VPPCOM_DEBUG > 0)
1682                 clib_warning ("[%d] configured accept_timeout %f",
1683                               getpid (), vcl_cfg->accept_timeout);
1684             }
1685           else if (unformat (line_input, "app-proxy-transport-tcp"))
1686             {
1687               vcl_cfg->app_proxy_transport_tcp = 1;
1688               if (VPPCOM_DEBUG > 0)
1689                 clib_warning ("[%d] configured app_proxy_transport_tcp (%d)",
1690                               getpid (), vcl_cfg->app_proxy_transport_tcp);
1691             }
1692           else if (unformat (line_input, "app-proxy-transport-udp"))
1693             {
1694               vcl_cfg->app_proxy_transport_udp = 1;
1695               if (VPPCOM_DEBUG > 0)
1696                 clib_warning ("[%d] configured app_proxy_transport_udp (%d)",
1697                               getpid (), vcl_cfg->app_proxy_transport_udp);
1698             }
1699           else if (unformat (line_input, "app-scope-local"))
1700             {
1701               vcl_cfg->app_scope_local = 1;
1702               if (VPPCOM_DEBUG > 0)
1703                 clib_warning ("[%d] configured app_scope_local (%d)",
1704                               getpid (), vcl_cfg->app_scope_local);
1705             }
1706           else if (unformat (line_input, "app-scope-global"))
1707             {
1708               vcl_cfg->app_scope_global = 1;
1709               if (VPPCOM_DEBUG > 0)
1710                 clib_warning ("[%d] configured app_scope_global (%d)",
1711                               getpid (), vcl_cfg->app_scope_global);
1712             }
1713           else if (unformat (line_input, "namespace-secret %lu",
1714                              &vcl_cfg->namespace_secret))
1715             {
1716               if (VPPCOM_DEBUG > 0)
1717                 clib_warning
1718                   ("[%d] configured namespace_secret %lu (0x%lx)",
1719                    getpid (), vcl_cfg->namespace_secret,
1720                    vcl_cfg->namespace_secret);
1721             }
1722           else if (unformat (line_input, "namespace-id %v",
1723                              &vcl_cfg->namespace_id))
1724             {
1725               vl_api_application_attach_t *mp;
1726               u32 max_nsid_vec_len = sizeof (mp->namespace_id) - 1;
1727               u32 nsid_vec_len = vec_len (vcl_cfg->namespace_id);
1728               if (nsid_vec_len > max_nsid_vec_len)
1729                 {
1730                   _vec_len (vcl_cfg->namespace_id) = max_nsid_vec_len;
1731                   if (VPPCOM_DEBUG > 0)
1732                     clib_warning ("[%d] configured namespace_id is too long,"
1733                                   " truncated to %d characters!", getpid (),
1734                                   max_nsid_vec_len);
1735                 }
1736
1737               if (VPPCOM_DEBUG > 0)
1738                 clib_warning ("[%d] configured namespace_id %v",
1739                               getpid (), vcl_cfg->namespace_id);
1740             }
1741           else if (unformat (line_input, "}"))
1742             {
1743               vc_cfg_input = 0;
1744               if (VPPCOM_DEBUG > 0)
1745                 clib_warning ("[%d] completed parsing vppcom config!",
1746                               getpid ());
1747               goto input_done;
1748             }
1749           else
1750             {
1751               if (line_input->buffer[line_input->index] != '#')
1752                 {
1753                   clib_warning ("[%d] Unknown vppcom config option: '%s'",
1754                                 getpid (), (char *)
1755                                 &line_input->buffer[line_input->index]);
1756                 }
1757             }
1758         }
1759     }
1760
1761 input_done:
1762   unformat_free (input);
1763
1764 file_done:
1765   if (fd >= 0)
1766     close (fd);
1767 }
1768
1769 /*
1770  * VPPCOM Public API functions
1771  */
1772 int
1773 vppcom_app_create (char *app_name)
1774 {
1775   vppcom_cfg_t *vcl_cfg = &vcm->cfg;
1776   u8 *heap;
1777   mheap_t *h;
1778   int rv;
1779
1780   if (!vcm->init)
1781     {
1782       char *conf_fname;
1783       char *env_var_str;
1784
1785       vcm->init = 1;
1786       vppcom_cfg_init (vcl_cfg);
1787       env_var_str = getenv (VPPCOM_ENV_DEBUG);
1788       if (env_var_str)
1789         {
1790           u32 tmp;
1791           if (sscanf (env_var_str, "%u", &tmp) != 1)
1792             clib_warning ("[%d] Invalid debug level specified in "
1793                           "the environment variable "
1794                           VPPCOM_ENV_DEBUG
1795                           " (%s)!\n", getpid (), env_var_str);
1796           else
1797             {
1798               vcm->debug = tmp;
1799               clib_warning ("[%d] configured debug level (%u) from "
1800                             VPPCOM_ENV_DEBUG "!", getpid (), vcm->debug);
1801             }
1802         }
1803       conf_fname = getenv (VPPCOM_ENV_CONF);
1804       if (!conf_fname)
1805         {
1806           conf_fname = VPPCOM_CONF_DEFAULT;
1807           if (VPPCOM_DEBUG > 0)
1808             clib_warning ("[%d] getenv '%s' failed!", getpid (),
1809                           VPPCOM_ENV_CONF);
1810         }
1811       vppcom_cfg_heapsize (conf_fname);
1812       clib_fifo_validate (vcm->client_session_index_fifo,
1813                           vcm->cfg.listen_queue_size);
1814       vppcom_cfg_read (conf_fname);
1815       env_var_str = getenv (VPPCOM_ENV_APP_NAMESPACE_ID);
1816       if (env_var_str)
1817         {
1818           u32 ns_id_vec_len = strlen (env_var_str);
1819
1820           vec_reset_length (vcm->cfg.namespace_id);
1821           vec_validate (vcm->cfg.namespace_id, ns_id_vec_len - 1);
1822           clib_memcpy (vcm->cfg.namespace_id, env_var_str, ns_id_vec_len);
1823
1824           if (VPPCOM_DEBUG > 0)
1825             clib_warning ("[%d] configured namespace_id (%v) from "
1826                           VPPCOM_ENV_APP_NAMESPACE_ID "!", getpid (),
1827                           vcm->cfg.namespace_id);
1828         }
1829       env_var_str = getenv (VPPCOM_ENV_APP_NAMESPACE_SECRET);
1830       if (env_var_str)
1831         {
1832           u64 tmp;
1833           if (sscanf (env_var_str, "%lu", &tmp) != 1)
1834             clib_warning ("[%d] Invalid namespace secret specified in "
1835                           "the environment variable "
1836                           VPPCOM_ENV_APP_NAMESPACE_SECRET
1837                           " (%s)!\n", getpid (), env_var_str);
1838           else
1839             {
1840               vcm->cfg.namespace_secret = tmp;
1841               if (VPPCOM_DEBUG > 0)
1842                 clib_warning ("[%d] configured namespace secret (%lu) from "
1843                               VPPCOM_ENV_APP_NAMESPACE_ID "!", getpid (),
1844                               vcm->cfg.namespace_secret);
1845             }
1846         }
1847       if (getenv (VPPCOM_ENV_APP_PROXY_TRANSPORT_TCP))
1848         {
1849           vcm->cfg.app_proxy_transport_tcp = 1;
1850           if (VPPCOM_DEBUG > 0)
1851             clib_warning ("[%d] configured app_proxy_transport_tcp (%u) from "
1852                           VPPCOM_ENV_APP_PROXY_TRANSPORT_TCP "!", getpid (),
1853                           vcm->cfg.app_proxy_transport_tcp);
1854         }
1855       if (getenv (VPPCOM_ENV_APP_PROXY_TRANSPORT_UDP))
1856         {
1857           vcm->cfg.app_proxy_transport_udp = 1;
1858           if (VPPCOM_DEBUG > 0)
1859             clib_warning ("[%d] configured app_proxy_transport_udp (%u) from "
1860                           VPPCOM_ENV_APP_PROXY_TRANSPORT_UDP "!", getpid (),
1861                           vcm->cfg.app_proxy_transport_udp);
1862         }
1863       if (getenv (VPPCOM_ENV_APP_SCOPE_LOCAL))
1864         {
1865           vcm->cfg.app_scope_local = 1;
1866           if (VPPCOM_DEBUG > 0)
1867             clib_warning ("[%d] configured app_scope_local (%u) from "
1868                           VPPCOM_ENV_APP_SCOPE_LOCAL "!", getpid (),
1869                           vcm->cfg.app_scope_local);
1870         }
1871       if (getenv (VPPCOM_ENV_APP_SCOPE_GLOBAL))
1872         {
1873           vcm->cfg.app_scope_global = 1;
1874           if (VPPCOM_DEBUG > 0)
1875             clib_warning ("[%d] configured app_scope_global (%u) from "
1876                           VPPCOM_ENV_APP_SCOPE_GLOBAL "!", getpid (),
1877                           vcm->cfg.app_scope_global);
1878         }
1879
1880       vcm->bind_session_index = ~0;
1881       vcm->main_cpu = os_get_thread_index ();
1882       heap = clib_mem_get_per_cpu_heap ();
1883       h = mheap_header (heap);
1884
1885       /* make the main heap thread-safe */
1886       h->flags |= MHEAP_FLAG_THREAD_SAFE;
1887
1888       vcm->session_index_by_vpp_handles = hash_create (0, sizeof (uword));
1889
1890       clib_time_init (&vcm->clib_time);
1891       vppcom_init_error_string_table ();
1892       svm_fifo_segment_init (vcl_cfg->segment_baseva,
1893                              20 /* timeout in secs */ );
1894       clib_spinlock_init (&vcm->sessions_lockp);
1895       vppcom_api_hookup ();
1896     }
1897
1898   if (vcm->my_client_index == ~0)
1899     {
1900       vcm->app_state = STATE_APP_START;
1901       rv = vppcom_connect_to_vpp (app_name);
1902       if (rv)
1903         {
1904           clib_warning ("[%d] couldn't connect to VPP.", getpid ());
1905           return rv;
1906         }
1907
1908       if (VPPCOM_DEBUG > 0)
1909         clib_warning ("[%d] sending session enable", getpid ());
1910
1911       rv = vppcom_app_session_enable ();
1912       if (rv)
1913         {
1914           clib_warning ("[%d] vppcom_app_session_enable() failed!",
1915                         getpid ());
1916           return rv;
1917         }
1918
1919       if (VPPCOM_DEBUG > 0)
1920         clib_warning ("[%d] sending app attach", getpid ());
1921
1922       rv = vppcom_app_attach ();
1923       if (rv)
1924         {
1925           clib_warning ("[%d] vppcom_app_attach() failed!", getpid ());
1926           return rv;
1927         }
1928
1929       if (VPPCOM_DEBUG > 0)
1930         clib_warning ("[%d] app_name '%s', my_client_index %d (0x%x)",
1931                       getpid (), app_name, vcm->my_client_index,
1932                       vcm->my_client_index);
1933     }
1934
1935   return VPPCOM_OK;
1936 }
1937
1938 void
1939 vppcom_app_destroy (void)
1940 {
1941   int rv;
1942
1943   if (vcm->my_client_index == ~0)
1944     return;
1945
1946   if (VPPCOM_DEBUG > 0)
1947     clib_warning ("[%d] detaching from VPP, my_client_index %d (0x%x)",
1948                   getpid (), vcm->my_client_index, vcm->my_client_index);
1949
1950   vppcom_app_detach ();
1951   rv = vppcom_wait_for_app_state_change (STATE_APP_ENABLED);
1952   if (PREDICT_FALSE (rv))
1953     {
1954       if (VPPCOM_DEBUG > 0)
1955         clib_warning ("[%d] application detach timed out, rv = %s (%d)",
1956                       getpid (), vppcom_retval_str (rv), rv);
1957     }
1958   vl_client_disconnect_from_vlib ();
1959   vcm->my_client_index = ~0;
1960   vcm->app_state = STATE_APP_START;
1961 }
1962
1963 int
1964 vppcom_session_create (u32 vrf, u8 proto, u8 is_nonblocking)
1965 {
1966   session_t *session;
1967   u32 session_index;
1968
1969   clib_spinlock_lock (&vcm->sessions_lockp);
1970   pool_get (vcm->sessions, session);
1971   memset (session, 0, sizeof (*session));
1972   session_index = session - vcm->sessions;
1973
1974   session->vrf = vrf;
1975   session->proto = proto;
1976   session->state = STATE_START;
1977   session->is_nonblocking = is_nonblocking ? 1 : 0;
1978   clib_spinlock_unlock (&vcm->sessions_lockp);
1979
1980   if (VPPCOM_DEBUG > 0)
1981     clib_warning ("[%d] sid %d", getpid (), session_index);
1982
1983   return (int) session_index;
1984 }
1985
1986 int
1987 vppcom_session_close (uint32_t session_index)
1988 {
1989   session_t *session = 0;
1990   int rv;
1991   u8 is_server;
1992   u8 is_listen;
1993   u8 is_cut_thru;
1994   u8 is_vep;
1995   u8 is_vep_session;
1996   u32 next_sid;
1997   u32 vep_idx;
1998   session_state_t state;
1999
2000   clib_spinlock_lock (&vcm->sessions_lockp);
2001   rv = vppcom_session_at_index (session_index, &session);
2002   if (PREDICT_FALSE (rv))
2003     {
2004       if (VPPCOM_DEBUG > 0)
2005         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2006                       getpid (), session_index);
2007       clib_spinlock_unlock (&vcm->sessions_lockp);
2008       goto done;
2009     }
2010   is_server = session->is_server;
2011   is_listen = session->is_listen;
2012   is_cut_thru = session->is_cut_thru;
2013   is_vep = session->is_vep;
2014   is_vep_session = session->is_vep_session;
2015   next_sid = session->vep.next_sid;
2016   vep_idx = session->vep.vep_idx;
2017   state = session->state;
2018   clib_spinlock_unlock (&vcm->sessions_lockp);
2019
2020   if (VPPCOM_DEBUG > 0)
2021     clib_warning ("[%d] sid %d", getpid (), session_index);
2022
2023   if (is_vep)
2024     {
2025       while (next_sid != ~0)
2026         {
2027           rv = vppcom_epoll_ctl (session_index, EPOLL_CTL_DEL, next_sid, 0);
2028           if ((VPPCOM_DEBUG > 0) && (rv < 0))
2029             clib_warning ("[%d] EPOLL_CTL_DEL vep_idx %u, sid %u failed, "
2030                           "rv = %s (%d)", getpid (), vep_idx, next_sid,
2031                           vppcom_retval_str (rv), rv);
2032
2033           clib_spinlock_lock (&vcm->sessions_lockp);
2034           rv = vppcom_session_at_index (session_index, &session);
2035           if (PREDICT_FALSE (rv))
2036             {
2037               if (VPPCOM_DEBUG > 0)
2038                 clib_warning
2039                   ("[%d] invalid session, sid (%u) has been closed!",
2040                    getpid (), session_index);
2041               clib_spinlock_unlock (&vcm->sessions_lockp);
2042               goto done;
2043             }
2044           next_sid = session->vep.next_sid;
2045           clib_spinlock_unlock (&vcm->sessions_lockp);
2046         }
2047     }
2048   else
2049     {
2050       if (is_vep_session)
2051         {
2052           rv = vppcom_epoll_ctl (vep_idx, EPOLL_CTL_DEL, session_index, 0);
2053           if ((VPPCOM_DEBUG > 0) && (rv < 0))
2054             clib_warning ("[%d] EPOLL_CTL_DEL vep_idx %u, sid %u failed, "
2055                           "rv = %s (%d)", getpid (), vep_idx, session_index,
2056                           vppcom_retval_str (rv), rv);
2057         }
2058
2059       if (is_cut_thru && is_server && (state == STATE_ACCEPT))
2060         {
2061           rv = vppcom_session_unbind_cut_thru (session, session_index);
2062           if ((VPPCOM_DEBUG > 0) && (rv < 0))
2063             clib_warning ("[%d] unbind cut-thru (session %d) failed, "
2064                           "rv = %s (%d)",
2065                           getpid (), session_index,
2066                           vppcom_retval_str (rv), rv);
2067         }
2068       else if (is_server && is_listen)
2069         {
2070           rv = vppcom_session_unbind (session_index);
2071           if ((VPPCOM_DEBUG > 0) && (rv < 0))
2072             clib_warning ("[%d] unbind (session %d) failed, rv = %s (%d)",
2073                           getpid (), session_index,
2074                           vppcom_retval_str (rv), rv);
2075         }
2076       else if (state == STATE_CONNECT)
2077         if (vppcom_session_disconnect (session_index))
2078           goto done;
2079     }
2080   clib_spinlock_lock (&vcm->sessions_lockp);
2081   pool_put_index (vcm->sessions, session_index);
2082   clib_spinlock_unlock (&vcm->sessions_lockp);
2083 done:
2084   return rv;
2085 }
2086
2087 int
2088 vppcom_session_bind (uint32_t session_index, vppcom_endpt_t * ep)
2089 {
2090   session_t *session = 0;
2091   int rv;
2092
2093   if (!ep || !ep->ip)
2094     return VPPCOM_EINVAL;
2095
2096   clib_spinlock_lock (&vcm->sessions_lockp);
2097   rv = vppcom_session_at_index (session_index, &session);
2098   if (PREDICT_FALSE (rv))
2099     {
2100       clib_spinlock_unlock (&vcm->sessions_lockp);
2101       if (VPPCOM_DEBUG > 0)
2102         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2103                       getpid (), session_index);
2104       return rv;
2105     }
2106
2107   if (session->is_vep)
2108     {
2109       clib_spinlock_unlock (&vcm->sessions_lockp);
2110       if (VPPCOM_DEBUG > 0)
2111         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2112                       getpid (), session_index);
2113       return VPPCOM_EBADFD;
2114     }
2115
2116   session->vrf = ep->vrf;
2117   session->lcl_addr.is_ip4 = ep->is_ip4;
2118   session->lcl_addr.ip46 = to_ip46 (!ep->is_ip4, ep->ip);
2119   session->lcl_port = ep->port;
2120
2121   if (VPPCOM_DEBUG > 0)
2122     clib_warning ("[%d] sid %d, bound to lcl address %U lcl port %u",
2123                   getpid (), session_index, format_ip46_address,
2124                   &session->lcl_addr.ip46, session->lcl_addr.is_ip4,
2125                   clib_net_to_host_u16 (session->lcl_port));
2126
2127   clib_spinlock_unlock (&vcm->sessions_lockp);
2128   return VPPCOM_OK;
2129 }
2130
2131 int
2132 vppcom_session_listen (uint32_t listen_session_index, uint32_t q_len)
2133 {
2134   session_t *listen_session = 0;
2135   int rv;
2136
2137   clib_spinlock_lock (&vcm->sessions_lockp);
2138   rv = vppcom_session_at_index (listen_session_index, &listen_session);
2139   if (PREDICT_FALSE (rv))
2140     {
2141       clib_spinlock_unlock (&vcm->sessions_lockp);
2142       if (VPPCOM_DEBUG > 0)
2143         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2144                       getpid (), listen_session_index);
2145       return rv;
2146     }
2147
2148   if (listen_session->is_vep)
2149     {
2150       clib_spinlock_unlock (&vcm->sessions_lockp);
2151       if (VPPCOM_DEBUG > 0)
2152         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2153                       getpid (), listen_session_index);
2154       return VPPCOM_EBADFD;
2155     }
2156
2157   if (listen_session->is_listen)
2158     {
2159       clib_spinlock_unlock (&vcm->sessions_lockp);
2160       if (VPPCOM_DEBUG > 0)
2161         clib_warning ("[%d] sid (%u) is already in listen state!",
2162                       getpid (), listen_session_index);
2163       return VPPCOM_OK;
2164     }
2165
2166   if (VPPCOM_DEBUG > 0)
2167     clib_warning ("[%d] sid %d", getpid (), listen_session_index);
2168
2169   ASSERT (vcm->bind_session_index == ~0);
2170   vcm->bind_session_index = listen_session_index;
2171   vppcom_send_bind_sock (listen_session);
2172   clib_spinlock_unlock (&vcm->sessions_lockp);
2173   rv =
2174     vppcom_wait_for_session_state_change (listen_session_index, STATE_LISTEN,
2175                                           vcm->cfg.session_timeout);
2176   if (PREDICT_FALSE (rv))
2177     {
2178       vcm->bind_session_index = ~0;
2179       if (VPPCOM_DEBUG > 0)
2180         clib_warning ("[%d] server listen timed out, rv = %d (%d)",
2181                       getpid (), vppcom_retval_str (rv), rv);
2182       return rv;
2183     }
2184
2185   clib_spinlock_lock (&vcm->sessions_lockp);
2186   rv = vppcom_session_at_index (listen_session_index, &listen_session);
2187   if (PREDICT_FALSE (rv))
2188     {
2189       clib_spinlock_unlock (&vcm->sessions_lockp);
2190       if (VPPCOM_DEBUG > 0)
2191         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2192                       getpid (), listen_session_index);
2193       return rv;
2194     }
2195   listen_session->is_listen = 1;
2196   clib_fifo_validate (vcm->client_session_index_fifo, q_len);
2197   clib_spinlock_unlock (&vcm->sessions_lockp);
2198
2199   return VPPCOM_OK;
2200 }
2201
2202 int
2203 vppcom_session_accept (uint32_t listen_session_index, vppcom_endpt_t * ep,
2204                        double wait_for_time)
2205 {
2206   session_t *listen_session = 0;
2207   session_t *client_session = 0;
2208   u32 client_session_index;
2209   int rv;
2210   f64 wait_for;
2211   char *cut_thru_str;
2212
2213   clib_spinlock_lock (&vcm->sessions_lockp);
2214   rv = vppcom_session_at_index (listen_session_index, &listen_session);
2215   if (PREDICT_FALSE (rv))
2216     {
2217       clib_spinlock_unlock (&vcm->sessions_lockp);
2218       if (VPPCOM_DEBUG > 0)
2219         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2220                       getpid (), listen_session_index);
2221       return rv;
2222     }
2223
2224   if (listen_session->is_vep)
2225     {
2226       clib_spinlock_unlock (&vcm->sessions_lockp);
2227       if (VPPCOM_DEBUG > 0)
2228         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2229                       getpid (), listen_session_index);
2230       return VPPCOM_EBADFD;
2231     }
2232
2233   if (listen_session->state != STATE_LISTEN)
2234     {
2235       clib_spinlock_unlock (&vcm->sessions_lockp);
2236       if (VPPCOM_DEBUG > 0)
2237         clib_warning ("[%d] session not in listen state, state = %s",
2238                       getpid (),
2239                       vppcom_session_state_str (listen_session->state));
2240       return VPPCOM_EBADFD;
2241     }
2242   wait_for = listen_session->is_nonblocking ? 0 :
2243     (wait_for_time < 0) ? vcm->cfg.accept_timeout : wait_for_time;
2244
2245   if (VPPCOM_DEBUG > 0)
2246     clib_warning ("[%d] sid %d: %s (%d)", getpid (),
2247                   listen_session_index,
2248                   vppcom_session_state_str (listen_session->state),
2249                   listen_session->state);
2250   clib_spinlock_unlock (&vcm->sessions_lockp);
2251
2252   while (1)
2253     {
2254       rv = vppcom_wait_for_client_session_index (wait_for);
2255       if (rv)
2256         {
2257           if ((VPPCOM_DEBUG > 0))
2258             clib_warning ("[%d] sid %d, accept timed out, rv = %s (%d)",
2259                           getpid (), listen_session_index,
2260                           vppcom_retval_str (rv), rv);
2261           if ((wait_for == 0) || (wait_for_time > 0))
2262             return rv;
2263         }
2264       else
2265         break;
2266     }
2267
2268   clib_spinlock_lock (&vcm->sessions_lockp);
2269   clib_fifo_sub1 (vcm->client_session_index_fifo, client_session_index);
2270   rv = vppcom_session_at_index (client_session_index, &client_session);
2271   ASSERT (rv == VPPCOM_OK);
2272   ASSERT (client_session->peer_addr.is_ip4 ==
2273           listen_session->lcl_addr.is_ip4);
2274
2275   if (VPPCOM_DEBUG > 0)
2276     clib_warning ("[%d] Got a request: client sid %d", getpid (),
2277                   client_session_index);
2278
2279   ep->vrf = client_session->vrf;
2280   ep->is_cut_thru = client_session->is_cut_thru;
2281   ep->is_ip4 = client_session->peer_addr.is_ip4;
2282   ep->port = client_session->peer_port;
2283   if (client_session->peer_addr.is_ip4)
2284     clib_memcpy (ep->ip, &client_session->peer_addr.ip46.ip4,
2285                  sizeof (ip4_address_t));
2286   else
2287     clib_memcpy (ep->ip, &client_session->peer_addr.ip46.ip6,
2288                  sizeof (ip6_address_t));
2289
2290   if (client_session->is_server && client_session->is_cut_thru)
2291     {
2292       static svm_fifo_segment_create_args_t _a;
2293       svm_fifo_segment_create_args_t *a = &_a;
2294       svm_fifo_segment_private_t *seg;
2295
2296       cut_thru_str = "cut-thru ";
2297
2298       /* Create the segment */
2299       memset (a, 0, sizeof (*a));
2300       a->segment_name = (char *)
2301         format ((u8 *) a->segment_name, "%d:segment%d%c",
2302                 getpid (), vcm->unique_segment_index++, 0);
2303       a->segment_size = vcm->cfg.segment_size;
2304       a->preallocated_fifo_pairs = vcm->cfg.preallocated_fifo_pairs;
2305       a->rx_fifo_size = vcm->cfg.rx_fifo_size;
2306       a->tx_fifo_size = vcm->cfg.tx_fifo_size;
2307
2308       rv = svm_fifo_segment_create (a);
2309       if (PREDICT_FALSE (rv))
2310         {
2311           if (VPPCOM_DEBUG > 1)
2312             clib_warning ("[%d] svm_fifo_segment_create ('%s') failed",
2313                           getpid (), a->segment_name);
2314           vec_reset_length (a->new_segment_indices);
2315           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2316           vppcom_send_connect_session_reply (client_session, 0, rv, 0);
2317           clib_spinlock_unlock (&vcm->sessions_lockp);
2318           return VPPCOM_ENOMEM;
2319         }
2320
2321       client_session->segment_name = vec_dup ((u8 *) a->segment_name);
2322       client_session->sm_seg_index = a->new_segment_indices[0];
2323       vec_free (a->new_segment_indices);
2324
2325       seg = svm_fifo_segment_get_segment (client_session->sm_seg_index);
2326       client_session->server_rx_fifo =
2327         svm_fifo_segment_alloc_fifo (seg, vcm->cfg.rx_fifo_size,
2328                                      FIFO_SEGMENT_RX_FREELIST);
2329       if (PREDICT_FALSE (!client_session->server_rx_fifo))
2330         {
2331           svm_fifo_segment_delete (seg);
2332           clib_warning ("[%d] rx fifo alloc failed, size %ld (0x%lx)",
2333                         getpid (), vcm->cfg.rx_fifo_size,
2334                         vcm->cfg.rx_fifo_size);
2335           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2336           vppcom_send_connect_session_reply (client_session, 0, rv, 0);
2337           clib_spinlock_unlock (&vcm->sessions_lockp);
2338           return VPPCOM_ENOMEM;
2339         }
2340       client_session->server_rx_fifo->master_session_index =
2341         client_session_index;
2342
2343       client_session->server_tx_fifo =
2344         svm_fifo_segment_alloc_fifo (seg, vcm->cfg.tx_fifo_size,
2345                                      FIFO_SEGMENT_TX_FREELIST);
2346       if (PREDICT_FALSE (!client_session->server_tx_fifo))
2347         {
2348           svm_fifo_segment_delete (seg);
2349           if (VPPCOM_DEBUG > 1)
2350             clib_warning ("[%d] tx fifo alloc failed, size %ld (0x%lx)",
2351                           getpid (), vcm->cfg.tx_fifo_size,
2352                           vcm->cfg.tx_fifo_size);
2353           rv = VNET_API_ERROR_URI_FIFO_CREATE_FAILED;
2354           vppcom_send_connect_session_reply (client_session, 0, rv, 0);
2355           clib_spinlock_unlock (&vcm->sessions_lockp);
2356           return VPPCOM_ENOMEM;
2357         }
2358       client_session->server_tx_fifo->master_session_index =
2359         client_session_index;
2360
2361       if (VPPCOM_DEBUG > 1)
2362         clib_warning ("[%d] created segment '%s': rx_fifo %p, tx_fifo %p",
2363                       getpid (), client_session->segment_name,
2364                       client_session->server_rx_fifo,
2365                       client_session->server_tx_fifo);
2366
2367 #ifdef CUT_THRU_EVENT_QUEUE     /* TBD */
2368       {
2369         void *oldheap;
2370         ssvm_shared_header_t *sh = seg->ssvm.sh;
2371
2372         ssvm_lock_non_recursive (sh, 1);
2373         oldheap = ssvm_push_heap (sh);
2374         event_q = client_session->vpp_event_queue =
2375           unix_shared_memory_queue_init (vcm->cfg.event_queue_size,
2376                                          sizeof (session_fifo_event_t),
2377                                          getpid (), 0 /* signal not sent */ );
2378         ssvm_pop_heap (oldheap);
2379         ssvm_unlock_non_recursive (sh);
2380       }
2381 #endif
2382       vppcom_send_connect_session_reply (client_session, 0, 0, 0);
2383     }
2384   else
2385     {
2386       cut_thru_str = " ";
2387       vppcom_send_accept_session_reply (0, client_session->vpp_handle);
2388     }
2389
2390   if (VPPCOM_DEBUG > 0)
2391     clib_warning ("[%d] sid %d, accepted %sconnection to peer address "
2392                   "%U peer port %u",
2393                   getpid (), client_session_index, cut_thru_str,
2394                   format_ip46_address, &client_session->peer_addr.ip46,
2395                   client_session->peer_addr.is_ip4,
2396                   clib_net_to_host_u16 (client_session->peer_port));
2397
2398   clib_spinlock_unlock (&vcm->sessions_lockp);
2399   return (int) client_session_index;
2400 }
2401
2402 int
2403 vppcom_session_connect (uint32_t session_index, vppcom_endpt_t * server_ep)
2404 {
2405   session_t *session = 0;
2406   int rv;
2407
2408   clib_spinlock_lock (&vcm->sessions_lockp);
2409   rv = vppcom_session_at_index (session_index, &session);
2410   if (PREDICT_FALSE (rv))
2411     {
2412       clib_spinlock_unlock (&vcm->sessions_lockp);
2413       if (VPPCOM_DEBUG > 0)
2414         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2415                       getpid (), session_index);
2416       return rv;
2417     }
2418
2419   if (session->is_vep)
2420     {
2421       clib_spinlock_unlock (&vcm->sessions_lockp);
2422       if (VPPCOM_DEBUG > 0)
2423         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2424                       getpid (), session_index);
2425       return VPPCOM_EBADFD;
2426     }
2427
2428   if (session->state == STATE_CONNECT)
2429     {
2430       clib_spinlock_unlock (&vcm->sessions_lockp);
2431       if (VPPCOM_DEBUG > 0)
2432         clib_warning ("[%d] session, sid (%u) already connected!",
2433                       getpid (), session_index);
2434       return VPPCOM_OK;
2435     }
2436
2437   session->vrf = server_ep->vrf;
2438   session->peer_addr.is_ip4 = server_ep->is_ip4;
2439   session->peer_addr.ip46 = to_ip46 (!server_ep->is_ip4, server_ep->ip);
2440   session->peer_port = server_ep->port;
2441
2442   if (VPPCOM_DEBUG > 0)
2443     {
2444       u8 *ip_str = format (0, "%U", format_ip46_address,
2445                            &session->peer_addr.ip46,
2446                            session->peer_addr.is_ip4);
2447       clib_warning ("[%d] connect sid %d to %s server port %d proto %s",
2448                     getpid (), session_index, ip_str,
2449                     clib_net_to_host_u16 (session->peer_port),
2450                     session->proto ? "UDP" : "TCP");
2451       vec_free (ip_str);
2452     }
2453
2454   vppcom_send_connect_sock (session, session_index);
2455   clib_spinlock_unlock (&vcm->sessions_lockp);
2456   rv = vppcom_wait_for_session_state_change (session_index, STATE_CONNECT,
2457                                              vcm->cfg.session_timeout);
2458   if (PREDICT_FALSE (rv))
2459     {
2460       if (VPPCOM_DEBUG > 0)
2461         clib_warning ("[%d] connect timed out, rv = %s (%d)",
2462                       getpid (), vppcom_retval_str (rv), rv);
2463       return rv;
2464     }
2465   if (VPPCOM_DEBUG > 0)
2466     clib_warning ("[%d] sid %d connected!", getpid (), session_index);
2467
2468   return VPPCOM_OK;
2469 }
2470
2471 static inline int
2472 vppcom_session_read_internal (uint32_t session_index, void *buf, int n,
2473                               u8 peek)
2474 {
2475   session_t *session = 0;
2476   svm_fifo_t *rx_fifo;
2477   int n_read = 0;
2478   int rv;
2479   char *fifo_str;
2480   u32 poll_et;
2481
2482   ASSERT (buf);
2483
2484   clib_spinlock_lock (&vcm->sessions_lockp);
2485   rv = vppcom_session_at_index (session_index, &session);
2486   if (PREDICT_FALSE (rv))
2487     {
2488       clib_spinlock_unlock (&vcm->sessions_lockp);
2489       if (VPPCOM_DEBUG > 0)
2490         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2491                       getpid (), session_index);
2492       return rv;
2493     }
2494
2495   if (session->is_vep)
2496     {
2497       clib_spinlock_unlock (&vcm->sessions_lockp);
2498       if (VPPCOM_DEBUG > 0)
2499         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2500                       getpid (), session_index);
2501       return VPPCOM_EBADFD;
2502     }
2503
2504   if (session->state == STATE_DISCONNECT)
2505     {
2506       clib_spinlock_unlock (&vcm->sessions_lockp);
2507       if (VPPCOM_DEBUG > 0)
2508         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2509                       getpid (), session_index);
2510       return VPPCOM_ECONNRESET;
2511     }
2512
2513   rx_fifo = ((!session->is_cut_thru || session->is_server) ?
2514              session->server_rx_fifo : session->server_tx_fifo);
2515   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2516               "server_rx_fifo" : "server_tx_fifo");
2517   poll_et =
2518     ((EPOLLET | EPOLLIN) & session->vep.ev.events) == (EPOLLET | EPOLLIN);
2519   clib_spinlock_unlock (&vcm->sessions_lockp);
2520
2521   do
2522     {
2523       if (peek)
2524         n_read = svm_fifo_peek (rx_fifo, 0, n, buf);
2525       else
2526         n_read = svm_fifo_dequeue_nowait (rx_fifo, n, buf);
2527     }
2528   while (!session->is_nonblocking && (n_read <= 0));
2529
2530   if (poll_et && (n_read <= 0))
2531     {
2532       clib_spinlock_lock (&vcm->sessions_lockp);
2533       session->vep.et_mask |= EPOLLIN;
2534       clib_spinlock_unlock (&vcm->sessions_lockp);
2535     }
2536
2537   if ((VPPCOM_DEBUG > 2) && (n_read > 0))
2538     clib_warning ("[%d] sid %d, read %d bytes from %s (%p)", getpid (),
2539                   session_index, n_read, fifo_str, rx_fifo);
2540
2541   return (n_read <= 0) ? VPPCOM_EAGAIN : n_read;
2542 }
2543
2544 int
2545 vppcom_session_read (uint32_t session_index, void *buf, int n)
2546 {
2547   return (vppcom_session_read_internal (session_index, buf, n, 0));
2548 }
2549
2550 static int
2551 vppcom_session_peek (uint32_t session_index, void *buf, int n)
2552 {
2553   return (vppcom_session_read_internal (session_index, buf, n, 1));
2554 }
2555
2556 static inline int
2557 vppcom_session_read_ready (session_t * session, u32 session_index)
2558 {
2559   svm_fifo_t *rx_fifo = 0;
2560   int ready = 0;
2561   u32 poll_et;
2562
2563   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2564   if (session->is_vep)
2565     {
2566       clib_spinlock_unlock (&vcm->sessions_lockp);
2567       if (VPPCOM_DEBUG > 0)
2568         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2569                       getpid (), session_index);
2570       return VPPCOM_EBADFD;
2571     }
2572
2573   if (session->state == STATE_DISCONNECT)
2574     {
2575       if (VPPCOM_DEBUG > 0)
2576         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2577                       getpid (), session_index);
2578       return VPPCOM_ECONNRESET;
2579     }
2580
2581   if (session->is_listen)
2582     ready = clib_fifo_elts (vcm->client_session_index_fifo);
2583   else
2584     {
2585       rx_fifo = ((!session->is_cut_thru || session->is_server) ?
2586                  session->server_rx_fifo : session->server_tx_fifo);
2587
2588       ready = svm_fifo_max_dequeue (rx_fifo);
2589     }
2590
2591   poll_et =
2592     ((EPOLLET | EPOLLIN) & session->vep.ev.events) == (EPOLLET | EPOLLIN);
2593   if (poll_et && (ready == 0))
2594     {
2595       if (VPPCOM_DEBUG > 11)
2596         clib_warning ("[%d] sid %d: current vep.et_mask = 0x%x", getpid (),
2597                       session_index, session->vep.et_mask);
2598       session->vep.et_mask |= EPOLLIN;
2599       if (VPPCOM_DEBUG > 11)
2600         clib_warning ("[%d] sid %d: updated vep.et_mask = 0x%x", getpid (),
2601                       session_index, session->vep.et_mask);
2602     }
2603
2604   if (session->vep.et_mask && (VPPCOM_DEBUG > 11))
2605     clib_warning ("[%d] sid %d, is_listen %u, peek %s (%p), ready = %d, "
2606                   "et_mask 0x%x",
2607                   getpid (), session_index, session->is_listen,
2608                   session->is_server ? "server_rx_fifo" : "server_tx_fifo",
2609                   rx_fifo, ready, session->vep.et_mask);
2610   return ready;
2611 }
2612
2613 int
2614 vppcom_session_write (uint32_t session_index, void *buf, int n)
2615 {
2616   session_t *session = 0;
2617   svm_fifo_t *tx_fifo;
2618   unix_shared_memory_queue_t *q;
2619   session_fifo_event_t evt;
2620   int rv, n_write;
2621   char *fifo_str;
2622   u32 poll_et;
2623
2624   ASSERT (buf);
2625
2626   clib_spinlock_lock (&vcm->sessions_lockp);
2627   rv = vppcom_session_at_index (session_index, &session);
2628   if (PREDICT_FALSE (rv))
2629     {
2630       clib_spinlock_unlock (&vcm->sessions_lockp);
2631       if (VPPCOM_DEBUG > 0)
2632         clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2633                       getpid (), session_index);
2634       return rv;
2635     }
2636
2637   if (session->is_vep)
2638     {
2639       clib_spinlock_unlock (&vcm->sessions_lockp);
2640       if (VPPCOM_DEBUG > 0)
2641         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2642                       getpid (), session_index);
2643       return VPPCOM_EBADFD;
2644     }
2645
2646   if (session->state == STATE_DISCONNECT)
2647     {
2648       clib_spinlock_unlock (&vcm->sessions_lockp);
2649       if (VPPCOM_DEBUG > 0)
2650         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2651                       getpid (), session_index);
2652       return VPPCOM_ECONNRESET;
2653     }
2654
2655   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2656              session->server_tx_fifo : session->server_rx_fifo);
2657   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2658               "server_tx_fifo" : "server_rx_fifo");
2659   q = session->vpp_event_queue;
2660   poll_et = (((EPOLLET | EPOLLOUT) & session->vep.ev.events) ==
2661              (EPOLLET | EPOLLOUT));
2662   clib_spinlock_unlock (&vcm->sessions_lockp);
2663
2664   do
2665     {
2666       n_write = svm_fifo_enqueue_nowait (tx_fifo, n, buf);
2667     }
2668   while (!session->is_nonblocking && (n_write <= 0));
2669
2670   /* If event wasn't set, add one */
2671   if (!session->is_cut_thru && (n_write > 0) && svm_fifo_set_event (tx_fifo))
2672     {
2673       int rval;
2674
2675       /* Fabricate TX event, send to vpp */
2676       evt.fifo = tx_fifo;
2677       evt.event_type = FIFO_EVENT_APP_TX;
2678
2679       rval = vppcom_session_at_index (session_index, &session);
2680       if (PREDICT_FALSE (rval))
2681         {
2682           if (VPPCOM_DEBUG > 1)
2683             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
2684                           getpid (), session_index);
2685           return rval;
2686         }
2687       ASSERT (q);
2688       unix_shared_memory_queue_add (q, (u8 *) & evt,
2689                                     0 /* do wait for mutex */ );
2690     }
2691
2692   if (poll_et && (n_write <= 0))
2693     {
2694       clib_spinlock_lock (&vcm->sessions_lockp);
2695       session->vep.et_mask |= EPOLLOUT;
2696       clib_spinlock_unlock (&vcm->sessions_lockp);
2697     }
2698
2699   if (VPPCOM_DEBUG > 2)
2700     {
2701       if (n_write == -2)
2702         clib_warning ("[%d] sid %d, FIFO-FULL %s (%p)", getpid (),
2703                       session_index, fifo_str, tx_fifo);
2704       else
2705         clib_warning ("[%d] sid %d, wrote %d bytes to %s (%p)", getpid (),
2706                       session_index, n_write, fifo_str, tx_fifo);
2707     }
2708   return (n_write < 0) ? VPPCOM_EAGAIN : n_write;
2709 }
2710
2711 static inline int
2712 vppcom_session_write_ready (session_t * session, u32 session_index)
2713 {
2714   svm_fifo_t *tx_fifo;
2715   char *fifo_str;
2716   int ready;
2717   u32 poll_et;
2718
2719   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2720   if (session->is_vep)
2721     {
2722       clib_spinlock_unlock (&vcm->sessions_lockp);
2723       if (VPPCOM_DEBUG > 0)
2724         clib_warning ("[%d] invalid session, sid (%u) is an epoll session!",
2725                       getpid (), session_index);
2726       return VPPCOM_EBADFD;
2727     }
2728
2729   if (session->state == STATE_DISCONNECT)
2730     {
2731       if (VPPCOM_DEBUG > 0)
2732         clib_warning ("[%d] sid (%u) has been closed by remote peer!",
2733                       getpid (), session_index);
2734       return VPPCOM_ECONNRESET;
2735     }
2736
2737   tx_fifo = ((!session->is_cut_thru || session->is_server) ?
2738              session->server_tx_fifo : session->server_rx_fifo);
2739   fifo_str = ((!session->is_cut_thru || session->is_server) ?
2740               "server_tx_fifo" : "server_rx_fifo");
2741
2742   ready = svm_fifo_max_enqueue (tx_fifo);
2743
2744   if (VPPCOM_DEBUG > 3)
2745     clib_warning ("[%d] sid %d, peek %s (%p), ready = %d", getpid (),
2746                   session_index, fifo_str, tx_fifo, ready);
2747   poll_et = (((EPOLLET | EPOLLOUT) & session->vep.ev.events) ==
2748              (EPOLLET | EPOLLOUT));
2749   if (poll_et && (ready == 0))
2750     session->vep.et_mask |= EPOLLOUT;
2751
2752   return ready;
2753 }
2754
2755 int
2756 vppcom_select (unsigned long n_bits, unsigned long *read_map,
2757                unsigned long *write_map, unsigned long *except_map,
2758                double time_to_wait)
2759 {
2760   u32 session_index;
2761   session_t *session = 0;
2762   int rv, bits_set = 0;
2763   f64 timeout = clib_time_now (&vcm->clib_time) + time_to_wait;
2764   u32 minbits = clib_max (n_bits, BITS (uword));
2765
2766   ASSERT (sizeof (clib_bitmap_t) == sizeof (long int));
2767
2768   if (n_bits && read_map)
2769     {
2770       clib_bitmap_validate (vcm->rd_bitmap, minbits);
2771       clib_memcpy (vcm->rd_bitmap, read_map, vec_len (vcm->rd_bitmap));
2772       memset (read_map, 0, vec_len (vcm->rd_bitmap));
2773     }
2774   if (n_bits && write_map)
2775     {
2776       clib_bitmap_validate (vcm->wr_bitmap, minbits);
2777       clib_memcpy (vcm->wr_bitmap, write_map, vec_len (vcm->wr_bitmap));
2778       memset (write_map, 0, vec_len (vcm->wr_bitmap));
2779     }
2780   if (n_bits && except_map)
2781     {
2782       clib_bitmap_validate (vcm->ex_bitmap, minbits);
2783       clib_memcpy (vcm->ex_bitmap, except_map, vec_len (vcm->ex_bitmap));
2784       memset (except_map, 0, vec_len (vcm->ex_bitmap));
2785     }
2786
2787   do
2788     {
2789       /* *INDENT-OFF* */
2790       if (n_bits)
2791         {
2792           if (read_map)
2793             {
2794               clib_bitmap_foreach (session_index, vcm->rd_bitmap,
2795                 ({
2796                   clib_spinlock_lock (&vcm->sessions_lockp);
2797                   rv = vppcom_session_at_index (session_index, &session);
2798                   if (rv < 0)
2799                     {
2800                       clib_spinlock_unlock (&vcm->sessions_lockp);
2801                       if (VPPCOM_DEBUG > 1)
2802                         clib_warning ("[%d] session %d specified in "
2803                                       "read_map is closed.", getpid (),
2804                                       session_index);
2805                       bits_set = VPPCOM_EBADFD;
2806                       goto select_done;
2807                     }
2808
2809                   rv = vppcom_session_read_ready (session, session_index);
2810                   clib_spinlock_unlock (&vcm->sessions_lockp);
2811                   if (except_map && vcm->ex_bitmap &&
2812                       clib_bitmap_get (vcm->ex_bitmap, session_index) &&
2813                       (rv < 0))
2814                     {
2815                       // TBD: clib_warning
2816                       clib_bitmap_set_no_check (except_map, session_index, 1);
2817                       bits_set++;
2818                     }
2819                   else if (rv > 0)
2820                     {
2821                       // TBD: clib_warning
2822                       clib_bitmap_set_no_check (read_map, session_index, 1);
2823                       bits_set++;
2824                     }
2825                 }));
2826             }
2827
2828           if (write_map)
2829             {
2830               clib_bitmap_foreach (session_index, vcm->wr_bitmap,
2831                 ({
2832                   clib_spinlock_lock (&vcm->sessions_lockp);
2833                   rv = vppcom_session_at_index (session_index, &session);
2834                   if (rv < 0)
2835                     {
2836                       clib_spinlock_unlock (&vcm->sessions_lockp);
2837                       if (VPPCOM_DEBUG > 0)
2838                         clib_warning ("[%d] session %d specified in "
2839                                       "write_map is closed.", getpid (),
2840                                       session_index);
2841                       bits_set = VPPCOM_EBADFD;
2842                       goto select_done;
2843                     }
2844
2845                   rv = vppcom_session_write_ready (session, session_index);
2846                   clib_spinlock_unlock (&vcm->sessions_lockp);
2847                   if (write_map && (rv > 0))
2848                     {
2849                       // TBD: clib_warning
2850                       clib_bitmap_set_no_check (write_map, session_index, 1);
2851                       bits_set++;
2852                     }
2853                 }));
2854             }
2855
2856           if (except_map)
2857             {
2858               clib_bitmap_foreach (session_index, vcm->ex_bitmap,
2859                 ({
2860                   clib_spinlock_lock (&vcm->sessions_lockp);
2861                   rv = vppcom_session_at_index (session_index, &session);
2862                   if (rv < 0)
2863                     {
2864                       clib_spinlock_unlock (&vcm->sessions_lockp);
2865                       if (VPPCOM_DEBUG > 1)
2866                         clib_warning ("[%d] session %d specified in "
2867                                       "except_map is closed.", getpid (),
2868                                       session_index);
2869                       bits_set = VPPCOM_EBADFD;
2870                       goto select_done;
2871                     }
2872
2873                   rv = vppcom_session_read_ready (session, session_index);
2874                   clib_spinlock_unlock (&vcm->sessions_lockp);
2875                   if (rv < 0)
2876                     {
2877                       // TBD: clib_warning
2878                       clib_bitmap_set_no_check (except_map, session_index, 1);
2879                       bits_set++;
2880                     }
2881                 }));
2882             }
2883         }
2884       /* *INDENT-ON* */
2885     }
2886   while (clib_time_now (&vcm->clib_time) < timeout);
2887
2888 select_done:
2889   return (bits_set);
2890 }
2891
2892 static inline void
2893 vep_verify_epoll_chain (u32 vep_idx)
2894 {
2895   session_t *session;
2896   vppcom_epoll_t *vep;
2897   int rv;
2898   u32 sid = vep_idx;
2899
2900   if (VPPCOM_DEBUG <= 1)
2901     return;
2902
2903   /* Assumes caller has acquired spinlock: vcm->sessions_lockp */
2904   rv = vppcom_session_at_index (vep_idx, &session);
2905   if (PREDICT_FALSE (rv))
2906     {
2907       clib_warning ("[%d] ERROR: Invalid vep_idx (%u)!", getpid (), vep_idx);
2908       goto done;
2909     }
2910   if (PREDICT_FALSE (!session->is_vep))
2911     {
2912       clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!", getpid (),
2913                     vep_idx);
2914       goto done;
2915     }
2916   clib_warning ("[%d] vep_idx (%u): Dumping epoll chain\n"
2917                 "{\n"
2918                 "   is_vep         = %u\n"
2919                 "   is_vep_session = %u\n"
2920                 "   wait_cont_idx  = 0x%x (%u)\n"
2921                 "}\n", getpid (),
2922                 vep_idx, session->is_vep, session->is_vep_session,
2923                 session->wait_cont_idx, session->wait_cont_idx);
2924   do
2925     {
2926       vep = &session->vep;
2927       sid = vep->next_sid;
2928       if (sid != ~0)
2929         {
2930           rv = vppcom_session_at_index (sid, &session);
2931           if (PREDICT_FALSE (rv))
2932             {
2933               clib_warning ("[%d] ERROR: Invalid sid (%u)!", getpid (), sid);
2934               goto done;
2935             }
2936           if (PREDICT_FALSE (session->is_vep))
2937             clib_warning ("[%d] ERROR: sid (%u) is a vep!",
2938                           getpid (), vep_idx);
2939           else if (PREDICT_FALSE (!session->is_vep_session))
2940             {
2941               clib_warning ("[%d] ERROR: session (%u) is not a vep session!",
2942                             getpid (), sid);
2943               goto done;
2944             }
2945           if (PREDICT_FALSE (session->vep.vep_idx != vep_idx))
2946             clib_warning ("[%d] ERROR: session (%u) vep_idx (%u) != "
2947                           "vep_idx (%u)!", getpid (),
2948                           sid, session->vep.vep_idx, vep_idx);
2949           if (session->is_vep_session)
2950             {
2951               clib_warning ("vep_idx[%u]: sid 0x%x (%u)\n"
2952                             "{\n"
2953                             "   next_sid       = 0x%x (%u)\n"
2954                             "   prev_sid       = 0x%x (%u)\n"
2955                             "   vep_idx        = 0x%x (%u)\n"
2956                             "   ev.events      = 0x%x\n"
2957                             "   ev.data.u64    = 0x%llx\n"
2958                             "   et_mask        = 0x%x\n"
2959                             "}\n",
2960                             vep_idx, sid, sid,
2961                             vep->next_sid, vep->next_sid,
2962                             vep->prev_sid, vep->prev_sid,
2963                             vep->vep_idx, vep->vep_idx,
2964                             vep->ev.events, vep->ev.data.u64, vep->et_mask);
2965             }
2966         }
2967     }
2968   while (sid != ~0);
2969
2970 done:
2971   clib_warning ("[%d] vep_idx (%u): Dump complete!\n", getpid (), vep_idx);
2972 }
2973
2974 int
2975 vppcom_epoll_create (void)
2976 {
2977   session_t *vep_session;
2978   u32 vep_idx;
2979
2980   clib_spinlock_lock (&vcm->sessions_lockp);
2981   pool_get (vcm->sessions, vep_session);
2982   memset (vep_session, 0, sizeof (*vep_session));
2983   vep_idx = vep_session - vcm->sessions;
2984
2985   vep_session->is_vep = 1;
2986   vep_session->vep.vep_idx = ~0;
2987   vep_session->vep.next_sid = ~0;
2988   vep_session->vep.prev_sid = ~0;
2989   vep_session->wait_cont_idx = ~0;
2990   clib_spinlock_unlock (&vcm->sessions_lockp);
2991
2992   if (VPPCOM_DEBUG > 0)
2993     clib_warning ("[%d] Created vep_idx %u!", getpid (), vep_idx);
2994
2995   return (vep_idx);
2996 }
2997
2998 int
2999 vppcom_epoll_ctl (uint32_t vep_idx, int op, uint32_t session_index,
3000                   struct epoll_event *event)
3001 {
3002   session_t *vep_session;
3003   session_t *session;
3004   int rv;
3005
3006   if (vep_idx == session_index)
3007     {
3008       if (VPPCOM_DEBUG > 0)
3009         clib_warning ("[%d] ERROR: vep_idx == session_index (%u)!",
3010                       getpid (), vep_idx);
3011       return VPPCOM_EINVAL;
3012     }
3013
3014   clib_spinlock_lock (&vcm->sessions_lockp);
3015   rv = vppcom_session_at_index (vep_idx, &vep_session);
3016   if (PREDICT_FALSE (rv))
3017     {
3018       if (VPPCOM_DEBUG > 0)
3019         clib_warning ("[%d] ERROR: Invalid vep_idx (%u)!", vep_idx);
3020       goto done;
3021     }
3022   if (PREDICT_FALSE (!vep_session->is_vep))
3023     {
3024       if (VPPCOM_DEBUG > 0)
3025         clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!",
3026                       getpid (), vep_idx);
3027       rv = VPPCOM_EINVAL;
3028       goto done;
3029     }
3030
3031   ASSERT (vep_session->vep.vep_idx == ~0);
3032   ASSERT (vep_session->vep.prev_sid == ~0);
3033
3034   rv = vppcom_session_at_index (session_index, &session);
3035   if (PREDICT_FALSE (rv))
3036     {
3037       if (VPPCOM_DEBUG > 0)
3038         clib_warning ("[%d] ERROR: Invalid session_index (%u)!",
3039                       getpid (), session_index);
3040       goto done;
3041     }
3042   if (PREDICT_FALSE (session->is_vep))
3043     {
3044       if (VPPCOM_DEBUG > 0)
3045         clib_warning ("ERROR: session_index (%u) is a vep!", vep_idx);
3046       rv = VPPCOM_EINVAL;
3047       goto done;
3048     }
3049
3050   switch (op)
3051     {
3052     case EPOLL_CTL_ADD:
3053       if (PREDICT_FALSE (!event))
3054         {
3055           clib_warning ("[%d] ERROR: EPOLL_CTL_ADD: NULL pointer to "
3056                         "epoll_event structure!", getpid ());
3057           rv = VPPCOM_EINVAL;
3058           goto done;
3059         }
3060       if (vep_session->vep.next_sid != ~0)
3061         {
3062           session_t *next_session;
3063           rv = vppcom_session_at_index (vep_session->vep.next_sid,
3064                                         &next_session);
3065           if (PREDICT_FALSE (rv))
3066             {
3067               if (VPPCOM_DEBUG > 0)
3068                 clib_warning ("[%d] ERROR: EPOLL_CTL_ADD: Invalid "
3069                               "vep.next_sid (%u) on vep_idx (%u)!",
3070                               getpid (), vep_session->vep.next_sid, vep_idx);
3071               goto done;
3072             }
3073           ASSERT (next_session->vep.prev_sid == vep_idx);
3074           next_session->vep.prev_sid = session_index;
3075         }
3076       session->vep.next_sid = vep_session->vep.next_sid;
3077       session->vep.prev_sid = vep_idx;
3078       session->vep.vep_idx = vep_idx;
3079       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
3080       session->vep.ev = *event;
3081       session->is_vep_session = 1;
3082       vep_session->vep.next_sid = session_index;
3083       if (VPPCOM_DEBUG > 1)
3084         clib_warning ("[%d] EPOLL_CTL_ADD: vep_idx %u, sid %u, events 0x%x,"
3085                       " data 0x%llx!", getpid (), vep_idx, session_index,
3086                       event->events, event->data.u64);
3087       break;
3088
3089     case EPOLL_CTL_MOD:
3090       if (PREDICT_FALSE (!event))
3091         {
3092           clib_warning ("[%d] ERROR: EPOLL_CTL_MOD: NULL pointer to "
3093                         "epoll_event structure!", getpid ());
3094           rv = VPPCOM_EINVAL;
3095           goto done;
3096         }
3097       if (PREDICT_FALSE (!session->is_vep_session &&
3098                          (session->vep.vep_idx != vep_idx)))
3099         {
3100           if (VPPCOM_DEBUG > 0)
3101             {
3102               if (!session->is_vep_session)
3103                 clib_warning ("[%d] ERROR: EPOLL_CTL_MOD: session (%u) "
3104                               "is not a vep session!",
3105                               getpid (), session_index);
3106               else
3107                 clib_warning ("[%d] ERROR: EPOLL_CTL_MOD: session (%u) "
3108                               "vep_idx (%u) != vep_idx (%u)!",
3109                               getpid (), session_index,
3110                               session->vep.vep_idx, vep_idx);
3111             }
3112           rv = VPPCOM_EINVAL;
3113           goto done;
3114         }
3115       session->vep.et_mask = VEP_DEFAULT_ET_MASK;
3116       session->vep.ev = *event;
3117       if (VPPCOM_DEBUG > 1)
3118         clib_warning ("[%d] EPOLL_CTL_MOD: vep_idx %u, sid %u, events 0x%x,"
3119                       " data 0x%llx!", getpid (), vep_idx, session_index,
3120                       event->events, event->data.u64);
3121       break;
3122
3123     case EPOLL_CTL_DEL:
3124       if (PREDICT_FALSE (!session->is_vep_session &&
3125                          (session->vep.vep_idx != vep_idx)))
3126         {
3127           if (VPPCOM_DEBUG > 0)
3128             {
3129               if (!session->is_vep_session)
3130                 clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: session (%u) "
3131                               "is not a vep session!",
3132                               getpid (), session_index);
3133               else
3134                 clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: session (%u) "
3135                               "vep_idx (%u) != vep_idx (%u)!",
3136                               getpid (), session_index,
3137                               session->vep.vep_idx, vep_idx);
3138             }
3139           rv = VPPCOM_EINVAL;
3140           goto done;
3141         }
3142
3143       vep_session->wait_cont_idx =
3144         (vep_session->wait_cont_idx == session_index) ?
3145         session->vep.next_sid : vep_session->wait_cont_idx;
3146
3147       if (session->vep.prev_sid == vep_idx)
3148         vep_session->vep.next_sid = session->vep.next_sid;
3149       else
3150         {
3151           session_t *prev_session;
3152           rv = vppcom_session_at_index (session->vep.prev_sid, &prev_session);
3153           if (PREDICT_FALSE (rv))
3154             {
3155               if (VPPCOM_DEBUG > 0)
3156                 clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: Invalid "
3157                               "vep.prev_sid (%u) on sid (%u)!",
3158                               getpid (), session->vep.prev_sid,
3159                               session_index);
3160               goto done;
3161             }
3162           ASSERT (prev_session->vep.next_sid == session_index);
3163           prev_session->vep.next_sid = session->vep.next_sid;
3164         }
3165       if (session->vep.next_sid != ~0)
3166         {
3167           session_t *next_session;
3168           rv = vppcom_session_at_index (session->vep.next_sid, &next_session);
3169           if (PREDICT_FALSE (rv))
3170             {
3171               if (VPPCOM_DEBUG > 0)
3172                 clib_warning ("[%d] ERROR: EPOLL_CTL_DEL: Invalid "
3173                               "vep.next_sid (%u) on sid (%u)!",
3174                               getpid (), session->vep.next_sid,
3175                               session_index);
3176               goto done;
3177             }
3178           ASSERT (next_session->vep.prev_sid == session_index);
3179           next_session->vep.prev_sid = session->vep.prev_sid;
3180         }
3181
3182       memset (&session->vep, 0, sizeof (session->vep));
3183       session->vep.next_sid = ~0;
3184       session->vep.prev_sid = ~0;
3185       session->vep.vep_idx = ~0;
3186       session->is_vep_session = 0;
3187       if (VPPCOM_DEBUG > 1)
3188         clib_warning ("[%d] EPOLL_CTL_DEL: vep_idx %u, sid %u!",
3189                       getpid (), vep_idx, session_index);
3190       break;
3191
3192     default:
3193       clib_warning ("[%d] ERROR: Invalid operation (%d)!", getpid (), op);
3194       rv = VPPCOM_EINVAL;
3195     }
3196
3197   vep_verify_epoll_chain (vep_idx);
3198
3199 done:
3200   clib_spinlock_unlock (&vcm->sessions_lockp);
3201   return rv;
3202 }
3203
3204 int
3205 vppcom_epoll_wait (uint32_t vep_idx, struct epoll_event *events,
3206                    int maxevents, double wait_for_time)
3207 {
3208   session_t *vep_session;
3209   int rv;
3210   f64 timeout = clib_time_now (&vcm->clib_time) + wait_for_time;
3211   u32 keep_trying = 1;
3212   int num_ev = 0;
3213   u32 vep_next_sid, wait_cont_idx;
3214   u8 is_vep;
3215
3216   if (PREDICT_FALSE (maxevents <= 0))
3217     {
3218       if (VPPCOM_DEBUG > 0)
3219         clib_warning ("[%d] ERROR: Invalid maxevents (%d)!",
3220                       getpid (), maxevents);
3221       return VPPCOM_EINVAL;
3222     }
3223   memset (events, 0, sizeof (*events) * maxevents);
3224
3225   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3226   vep_next_sid = vep_session->vep.next_sid;
3227   is_vep = vep_session->is_vep;
3228   wait_cont_idx = vep_session->wait_cont_idx;
3229   clib_spinlock_unlock (&vcm->sessions_lockp);
3230
3231   if (PREDICT_FALSE (!is_vep))
3232     {
3233       if (VPPCOM_DEBUG > 0)
3234         clib_warning ("[%d] ERROR: vep_idx (%u) is not a vep!",
3235                       getpid (), vep_idx);
3236       rv = VPPCOM_EINVAL;
3237       goto done;
3238     }
3239   if (PREDICT_FALSE (vep_next_sid == ~0))
3240     {
3241       if (VPPCOM_DEBUG > 0)
3242         clib_warning ("[%d] WARNING: vep_idx (%u) is empty!",
3243                       getpid (), vep_idx);
3244       goto done;
3245     }
3246
3247   do
3248     {
3249       u32 sid;
3250       u32 next_sid = ~0;
3251       session_t *session;
3252
3253       for (sid = (wait_cont_idx == ~0) ? vep_next_sid : wait_cont_idx;
3254            sid != ~0; sid = next_sid)
3255         {
3256           u32 session_events, et_mask, clear_et_mask, session_vep_idx;
3257           u8 add_event, is_vep_session;
3258           int ready;
3259           u64 session_ev_data;
3260
3261           VCL_LOCK_AND_GET_SESSION (sid, &session);
3262           next_sid = session->vep.next_sid;
3263           session_events = session->vep.ev.events;
3264           et_mask = session->vep.et_mask;
3265           is_vep = session->is_vep;
3266           is_vep_session = session->is_vep_session;
3267           session_vep_idx = session->vep.vep_idx;
3268           session_ev_data = session->vep.ev.data.u64;
3269           clib_spinlock_unlock (&vcm->sessions_lockp);
3270
3271           if (PREDICT_FALSE (is_vep))
3272             {
3273               if (VPPCOM_DEBUG > 0)
3274                 clib_warning ("[%d] ERROR: sid (%u) is a vep!",
3275                               getpid (), vep_idx);
3276               rv = VPPCOM_EINVAL;
3277               goto done;
3278             }
3279           if (PREDICT_FALSE (!is_vep_session))
3280             {
3281               if (VPPCOM_DEBUG > 0)
3282                 clib_warning ("[%d] ERROR: session (%u) is not "
3283                               "a vep session!", getpid (), sid);
3284               rv = VPPCOM_EINVAL;
3285               goto done;
3286             }
3287           if (PREDICT_FALSE (session_vep_idx != vep_idx))
3288             {
3289               clib_warning ("[%d] ERROR: session (%u) "
3290                             "vep_idx (%u) != vep_idx (%u)!",
3291                             getpid (), sid, session->vep.vep_idx, vep_idx);
3292               rv = VPPCOM_EINVAL;
3293               goto done;
3294             }
3295
3296           add_event = clear_et_mask = 0;
3297
3298           if (EPOLLIN & session_events)
3299             {
3300               VCL_LOCK_AND_GET_SESSION (sid, &session);
3301               ready = vppcom_session_read_ready (session, sid);
3302               clib_spinlock_unlock (&vcm->sessions_lockp);
3303               if ((ready > 0) && (EPOLLIN & et_mask))
3304                 {
3305                   add_event = 1;
3306                   events[num_ev].events |= EPOLLIN;
3307                   if (((EPOLLET | EPOLLIN) & session_events) ==
3308                       (EPOLLET | EPOLLIN))
3309                     clear_et_mask |= EPOLLIN;
3310                 }
3311               else if (ready < 0)
3312                 {
3313                   add_event = 1;
3314                   switch (ready)
3315                     {
3316                     case VPPCOM_ECONNRESET:
3317                       events[num_ev].events |= EPOLLHUP | EPOLLRDHUP;
3318                       break;
3319
3320                     default:
3321                       events[num_ev].events |= EPOLLERR;
3322                       break;
3323                     }
3324                 }
3325             }
3326
3327           if (EPOLLOUT & session_events)
3328             {
3329               VCL_LOCK_AND_GET_SESSION (sid, &session);
3330               ready = vppcom_session_write_ready (session, sid);
3331               clib_spinlock_unlock (&vcm->sessions_lockp);
3332               if ((ready > 0) && (EPOLLOUT & et_mask))
3333                 {
3334                   add_event = 1;
3335                   events[num_ev].events |= EPOLLOUT;
3336                   if (((EPOLLET | EPOLLOUT) & session_events) ==
3337                       (EPOLLET | EPOLLOUT))
3338                     clear_et_mask |= EPOLLOUT;
3339                 }
3340               else if (ready < 0)
3341                 {
3342                   add_event = 1;
3343                   switch (ready)
3344                     {
3345                     case VPPCOM_ECONNRESET:
3346                       events[num_ev].events |= EPOLLHUP;
3347                       break;
3348
3349                     default:
3350                       events[num_ev].events |= EPOLLERR;
3351                       break;
3352                     }
3353                 }
3354             }
3355
3356           if (add_event)
3357             {
3358               events[num_ev].data.u64 = session_ev_data;
3359               if (EPOLLONESHOT & session_events)
3360                 {
3361                   VCL_LOCK_AND_GET_SESSION (sid, &session);
3362                   session->vep.ev.events = 0;
3363                   clib_spinlock_unlock (&vcm->sessions_lockp);
3364                 }
3365               num_ev++;
3366               if (num_ev == maxevents)
3367                 {
3368                   VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3369                   vep_session->wait_cont_idx = next_sid;
3370                   clib_spinlock_unlock (&vcm->sessions_lockp);
3371                   goto done;
3372                 }
3373             }
3374           if (wait_cont_idx != ~0)
3375             {
3376               if (next_sid == ~0)
3377                 next_sid = vep_next_sid;
3378               else if (next_sid == wait_cont_idx)
3379                 next_sid = ~0;
3380             }
3381         }
3382       if (wait_for_time != -1)
3383         keep_trying = (clib_time_now (&vcm->clib_time) <= timeout) ? 1 : 0;
3384     }
3385   while ((num_ev == 0) && keep_trying);
3386
3387   if (wait_cont_idx != ~0)
3388     {
3389       VCL_LOCK_AND_GET_SESSION (vep_idx, &vep_session);
3390       vep_session->wait_cont_idx = ~0;
3391       clib_spinlock_unlock (&vcm->sessions_lockp);
3392     }
3393 done:
3394   return (rv != VPPCOM_OK) ? rv : num_ev;
3395 }
3396
3397 int
3398 vppcom_session_attr (uint32_t session_index, uint32_t op,
3399                      void *buffer, uint32_t * buflen)
3400 {
3401   session_t *session;
3402   int rv = VPPCOM_OK;
3403   u32 *flags = buffer;
3404   vppcom_endpt_t *ep = buffer;
3405
3406   VCL_LOCK_AND_GET_SESSION (session_index, &session);
3407   switch (op)
3408     {
3409     case VPPCOM_ATTR_GET_NREAD:
3410       rv = vppcom_session_read_ready (session, session_index);
3411       if (VPPCOM_DEBUG > 1)
3412         clib_warning ("[%d] VPPCOM_ATTR_GET_NREAD: nread = %d",
3413                       getpid (), rv);
3414
3415       break;
3416
3417     case VPPCOM_ATTR_PEEK_NREAD:
3418       /* TBD */
3419       break;
3420
3421     case VPPCOM_ATTR_GET_FLAGS:
3422       if (buffer && buflen && (*buflen >= sizeof (*flags)))
3423         {
3424           *flags = O_RDWR | ((session->is_nonblocking) ? O_NONBLOCK : 0);
3425           *buflen = sizeof (*flags);
3426           if (VPPCOM_DEBUG > 1)
3427             clib_warning ("[%d] VPPCOM_ATTR_GET_FLAGS: flags = 0x%08x, "
3428                           "is_nonblocking = %u", getpid (), *flags,
3429                           session->is_nonblocking);
3430         }
3431       else
3432         rv = VPPCOM_EINVAL;
3433       break;
3434
3435     case VPPCOM_ATTR_SET_FLAGS:
3436       if (buffer && buflen && (*buflen >= sizeof (*flags)))
3437         {
3438           session->is_nonblocking = (*flags & O_NONBLOCK) ? 1 : 0;
3439           if (VPPCOM_DEBUG > 1)
3440             clib_warning ("[%d] VPPCOM_ATTR_SET_FLAGS: flags = 0x%08x, "
3441                           "is_nonblocking = %u", getpid (), *flags,
3442                           session->is_nonblocking);
3443         }
3444       else
3445         rv = VPPCOM_EINVAL;
3446       break;
3447
3448     case VPPCOM_ATTR_GET_PEER_ADDR:
3449       if (buffer && buflen && (*buflen >= sizeof (*ep)))
3450         {
3451           ep->vrf = session->vrf;
3452           ep->is_ip4 = session->peer_addr.is_ip4;
3453           ep->port = session->peer_port;
3454           if (session->peer_addr.is_ip4)
3455             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
3456                          sizeof (ip4_address_t));
3457           else
3458             clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
3459                          sizeof (ip6_address_t));
3460           *buflen = sizeof (*ep);
3461           if (VPPCOM_DEBUG > 1)
3462             clib_warning ("[%d] VPPCOM_ATTR_GET_PEER_ADDR: sid %u is_ip4 = "
3463                           "%u, addr = %U, port %u", getpid (),
3464                           session_index, ep->is_ip4, format_ip46_address,
3465                           &session->peer_addr.ip46, ep->is_ip4,
3466                           clib_net_to_host_u16 (ep->port));
3467         }
3468       else
3469         rv = VPPCOM_EINVAL;
3470       break;
3471
3472     case VPPCOM_ATTR_GET_LCL_ADDR:
3473       if (buffer && buflen && (*buflen >= sizeof (*ep)))
3474         {
3475           ep->vrf = session->vrf;
3476           ep->is_ip4 = session->lcl_addr.is_ip4;
3477           ep->port = session->lcl_port;
3478           if (session->lcl_addr.is_ip4)
3479             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip4,
3480                          sizeof (ip4_address_t));
3481           else
3482             clib_memcpy (ep->ip, &session->lcl_addr.ip46.ip6,
3483                          sizeof (ip6_address_t));
3484           *buflen = sizeof (*ep);
3485           if (VPPCOM_DEBUG > 1)
3486             clib_warning ("[%d] VPPCOM_ATTR_GET_LCL_ADDR: sid %u is_ip4 = "
3487                           "%u, addr = %U port %d", getpid (),
3488                           session_index, ep->is_ip4, format_ip46_address,
3489                           &session->lcl_addr.ip46, ep->is_ip4,
3490                           clib_net_to_host_u16 (ep->port));
3491         }
3492       else
3493         rv = VPPCOM_EINVAL;
3494       break;
3495
3496     case VPPCOM_ATTR_SET_REUSEADDR:
3497       break;
3498
3499     case VPPCOM_ATTR_SET_BROADCAST:
3500       break;
3501
3502     case VPPCOM_ATTR_SET_V6ONLY:
3503       break;
3504
3505     case VPPCOM_ATTR_SET_KEEPALIVE:
3506       break;
3507
3508     case VPPCOM_ATTR_SET_TCP_KEEPIDLE:
3509       break;
3510
3511     case VPPCOM_ATTR_SET_TCP_KEEPINTVL:
3512       break;
3513
3514     default:
3515       rv = VPPCOM_EINVAL;
3516       break;
3517     }
3518
3519 done:
3520   clib_spinlock_unlock (&vcm->sessions_lockp);
3521   return rv;
3522 }
3523
3524 int
3525 vppcom_session_recvfrom (uint32_t session_index, void *buffer,
3526                          uint32_t buflen, int flags, vppcom_endpt_t * ep)
3527 {
3528   int rv = VPPCOM_OK;
3529   session_t *session = 0;
3530
3531   if (ep)
3532     {
3533       clib_spinlock_lock (&vcm->sessions_lockp);
3534       rv = vppcom_session_at_index (session_index, &session);
3535       if (PREDICT_FALSE (rv))
3536         {
3537           clib_spinlock_unlock (&vcm->sessions_lockp);
3538           if (VPPCOM_DEBUG > 0)
3539             clib_warning ("[%d] invalid session, sid (%u) has been closed!",
3540                           getpid (), session_index);
3541           rv = VPPCOM_EBADFD;
3542           clib_spinlock_unlock (&vcm->sessions_lockp);
3543           goto done;
3544         }
3545       ep->vrf = session->vrf;
3546       ep->is_ip4 = session->peer_addr.is_ip4;
3547       ep->port = session->peer_port;
3548       if (session->peer_addr.is_ip4)
3549         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip4,
3550                      sizeof (ip4_address_t));
3551       else
3552         clib_memcpy (ep->ip, &session->peer_addr.ip46.ip6,
3553                      sizeof (ip6_address_t));
3554       clib_spinlock_unlock (&vcm->sessions_lockp);
3555     }
3556
3557   if (flags == 0)
3558     rv = vppcom_session_read (session_index, buffer, buflen);
3559   else if (flags & MSG_PEEK)
3560     rv = vppcom_session_peek (session_index, buffer, buflen);
3561   else
3562     {
3563       clib_warning ("[%d] Unsupport flags for recvfrom %d", getpid (), flags);
3564       rv = VPPCOM_EAFNOSUPPORT;
3565     }
3566
3567 done:
3568   return rv;
3569 }
3570
3571 int
3572 vppcom_session_sendto (uint32_t session_index, void *buffer,
3573                        uint32_t buflen, int flags, vppcom_endpt_t * ep)
3574 {
3575   if (!buffer)
3576     return VPPCOM_EINVAL;
3577
3578   if (ep)
3579     {
3580       // TBD
3581       return VPPCOM_EINVAL;
3582     }
3583
3584   if (flags)
3585     {
3586       // TBD check the flags and do the right thing
3587       if (VPPCOM_DEBUG > 2)
3588         clib_warning ("[%d] handling flags 0x%u (%d) not implemented yet.",
3589                       getpid (), flags, flags);
3590     }
3591
3592   return (vppcom_session_write (session_index, buffer, buflen));
3593 }
3594
3595 /*
3596  * fd.io coding-style-patch-verification: ON
3597  *
3598  * Local Variables:
3599  * eval: (c-set-style "gnu")
3600  * End:
3601  */